Skip to content

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

Go

MUL-6924: feat(billing): notify workspaces about autopilot quota (#7681)

LinYushen3c23c491fab1
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx
index 6806bf44be..9186644f29 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx
@@ -28,7 +28,10 @@ import {
import { useWorkspaceStore } from "@/data/workspace-store";
import { useColorScheme } from "@/lib/use-color-scheme";
import { THEME } from "@/lib/theme";
-import { deduplicateInboxItems } from "@/lib/inbox-display";
+import {
+ deduplicateInboxItems,
+ getInboxNavigationTarget,
+} from "@/lib/inbox-display";
export default function Inbox() {
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
@@ -58,17 +61,8 @@ export default function Inbox() {
// snapshot for the native stack push transition.
markRead.mutate(item.id);
}
- if (item.issue_id && wsSlug) {
- router.push({
- pathname: "/[workspace]/issue/[id]",
- params: {
- workspace: wsSlug,
- id: item.issue_id,
- highlight: item.details?.comment_id,
- h: String(Date.now()),
- },
- });
- }
+ const target = getInboxNavigationTarget(item, wsSlug, String(Date.now()));
+ if (target) router.push(target);
};
// Trailing batch menu — mirrors web's dropdown
diff --git a/apps/mobile/app/(app)/[workspace]/_layout.tsx b/apps/mobile/app/(app)/[workspace]/_layout.tsx
index 420c53d40b..4eebd15dff 100644
--- a/apps/mobile/app/(app)/[workspace]/_layout.tsx
+++ b/apps/mobile/app/(app)/[workspace]/_layout.tsx
@@ -170,6 +170,7 @@ export default function WorkspaceLayout() {
headerLeft: () => <ModalCloseButton />,
}}
/>
+ <Stack.Screen name="inbox/[id]" options={SHEET_OPTIONS} />
{/* Issue-detail formSheet pickers. All share the same sheet config:
explicit numeric detents to dodge expo/expo#42904+#42965 (the
`fitToContents` zero-size / padding bugs on iOS 26 + Expo 55),
diff --git a/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx b/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx
new file mode 100644
index 0000000000..a9357a2835
--- /dev/null
+++ b/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx
@@ -0,0 +1,150 @@
+import { ActivityIndicator, Linking, ScrollView, View } from "react-native";
+import { router, useLocalSearchParams } from "expo-router";
+import { useQuery } from "@tanstack/react-query";
+import {
+ resolveBillingRecovery,
+ type BillingRecoveryKind,
+} from "@multica/core/billing/recovery";
+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
+import { Text } from "@/components/ui/text";
+import { Button } from "@/components/ui/button";
+import { IconButton } from "@/components/ui/icon-button";
+import { inboxListOptions } from "@/data/queries/inbox";
+import {
+ appConfigOptions,
+ workspaceSubscriptionSummaryOptions,
+} from "@/data/queries/billing";
+import { useWorkspaceStore } from "@/data/workspace-store";
+import {
+ getAutopilotQuotaBody,
+ getInboxDisplayTitle,
+} from "@/lib/inbox-display";
+
+function BillingRecovery({
+ recovery,
+ billingUrl,
+}: {
+ recovery: BillingRecoveryKind;
+ billingUrl: string | null;
+}) {
+ switch (recovery) {
+ case "checking":
+ return <ActivityIndicator />;
+ case "billing_disabled":
+ return (
+ <Text className="text-sm leading-5 text-muted-foreground">
+ Billing changes are unavailable for this workspace. Contact your
+ workspace administrator for help.
+ </Text>
+ );
+ case "contact_admin":
+ return (
+ <Text className="text-sm leading-5 text-muted-foreground">
+ Ask a workspace owner or admin to review the billing options.
+ </Text>
+ );
+ case "checkout":
+ case "portal":
+ case "billing":
+ case "billing_unavailable":
+ return billingUrl ? (
+ <Button
+ onPress={() => void Linking.openURL(billingUrl)}
+ accessibilityLabel="Review billing options"
+ >
+ <Text>Review billing options</Text>
+ </Button>
+ ) : (
+ <Text className="text-sm leading-5 text-muted-foreground">
+ Open Multica on the web to review billing options.
+ </Text>
+ );
+ }
+}
+
+export default function InboxNoticeDetail() {
+ const { id } = useLocalSearchParams<{ id: string }>();
+ const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
+ const wsSlug = useWorkspaceStore((s) => s.currentWorkspaceSlug);
+ const { data: items, isLoading } = useQuery(inboxListOptions(wsId));
+
+ // Read the raw workspace-scoped cache: deduplication can replace a row,
+ // but a sheet already opened for a specific notification must remain stable.
+ const item = items?.find(
+ (candidate) => candidate.id === id && candidate.workspace_id === wsId,
+ );
+ const isQuotaNotice = item?.type === "autopilot_quota_exceeded";
+ const configQuery = useQuery({
+ ...appConfigOptions(),
+ enabled: isQuotaNotice,
+ });
+ const billingEnabled =
+ configQuery.data?.feature_flags?.[
+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG
+ ] === true;
+ const summaryQuery = useQuery(
+ workspaceSubscriptionSummaryOptions(wsId, isQuotaNotice && billingEnabled),
+ );
+ const checkingConfig =
+ isQuotaNotice && !configQuery.data && configQuery.isFetching;
+ const recovery = resolveBillingRecovery({
+ actions: summaryQuery.data?.availableActions,
+ billingEnabled: checkingConfig || billingEnabled,
+ loading:
+ checkingConfig ||
+ (billingEnabled &&
+ !summaryQuery.data?.availableActions &&
+ summaryQuery.isFetching),
+ });
+ const webUrl = process.env.EXPO_PUBLIC_WEB_URL?.replace(/\/+$/, "");
+ const billingUrl =
+ webUrl && wsSlug ? `${webUrl}/${wsSlug}/settings?tab=billing` : null;
+ const body = item ? getAutopilotQuotaBody(item) : null;
+
+ return (
+ <View className="flex-1 bg-background">
+ <View className="flex-row items-center border-b border-border px-4 py-3">
+ <Text className="flex-1 text-lg font-semibold text-foreground">
+ {item ? getInboxDisplayTitle(item) : "Notification"}
+ </Text>
+ <IconButton
+ name="close"
+ variant="secondary"
+ className="size-7 rounded-full"
+ onPress={() => router.back()}
+ accessibilityLabel="Close notification"
+ />
+ </View>
+
+ {isLoading ? (
+ <View className="flex-1 items-center justify-center">
+ <ActivityIndicator />
+ </View>
+ ) : !item ||
+ (item.type !== "autopilot_quota_exceeded" &&
+ item.type !== "autopilot_paused") ? (
+ <View className="px-4 py-8">
+ <Text className="text-sm text-muted-foreground text-center">
+ This notification is no longer available.
+ </Text>
+ </View>
+ ) : (
+ <ScrollView
+ className="flex-1"
+ contentContainerClassName="gap-5 px-4 py-5"
+ showsVerticalScrollIndicator={false}
+ >
+ {body ? (
+ <Text className="text-base leading-6 text-foreground">
+ {body}
+ </Text>
+ ) : null}
+
+ {isQuotaNotice ? (
+ <BillingRecovery recovery={recovery} billingUrl={billingUrl} />
+ ) : null}
+ </ScrollView>
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsx
index 4b892dc467..5effa13faf 100644
--- a/apps/mobile/components/inbox/detail-label.tsx
+++ b/apps/mobile/components/inbox/detail-label.tsx
@@ -54,6 +54,8 @@ const TYPE_LABEL: Record<InboxItemType, string> = {
quick_create_done: "Quick-create done",
quick_create_failed: "Quick-create failed",
quick_create_unconfirmed: "Quick-create needs a check",
+ autopilot_paused: "Autopilot paused",
+ autopilot_quota_exceeded: "Autopilot run limit reached",
};
// due_date is a calendar day — format timezone-safely (no offset day shift).
@@ -150,6 +152,8 @@ export function InboxDetailLabel({
const detail = singleLine(details.error) || singleLine(item.body);
return detail || TYPE_LABEL[item.type];
}
+ case "autopilot_quota_exceeded":
+ return "Run blocked because the limit was reached";
default:
return TYPE_LABEL[item.type] ?? item.type;
}
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index d6df965beb..0be8316239 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -57,8 +57,11 @@ import type {
UpdateProjectRequest,
User,
Workspace,
+ WorkspaceSubscriptionSummary,
} from "@multica/core/types";
import {
+ AppConfigSchema,
+ EMPTY_APP_CONFIG,
EMPTY_LIST_ISSUE_STATUSES_RESPONSE,
EMPTY_LIST_ISSUES_RESPONSE,
EMPTY_TIMELINE_ENTRIES,
@@ -66,7 +69,9 @@ import {
ListIssuesResponseSchema,
ListIssueStatusesResponseSchema,
TimelineEntriesSchema,
+ WorkspaceSubscriptionSummarySchema,
} from "@multica/core/api/schemas";
+import type { AppConfigResponse } from "@multica/core/api/schemas";
import {
ActiveTasksResponseSchema,
AgentListSchema,
@@ -389,6 +394,26 @@ class ApiClient {
);
}
+ async getConfig(opts?: { signal?: AbortSignal }): Promise<AppConfigResponse> {
+ return this.fetchValidated<AppConfigResponse>(
+ "/api/config",
+ AppConfigSchema,
+ EMPTY_APP_CONFIG,
+ { ...opts, endpoint: "getConfig" },
+ );
+ }
+
+ async getWorkspaceSubscriptionSummary(opts?: {
+ signal?: AbortSignal;
+ }): Promise<WorkspaceSubscriptionSummary | null> {
+ return this.fetchValidated<WorkspaceSubscriptionSummary | null>(
+ "/api/cloud-subscriptions/summary",
+ WorkspaceSubscriptionSummarySchema,
+ null,
+ { ...opts, endpoint: "getWorkspaceSubscriptionSummary" },
+ );
+ }
+
// PATCH /api/me — name, avatar_url, language. Server returns the updated
// user; we parse so a partial drift doesn't bleed into the auth store.
async updateMe(data: UpdateMeRequest): Promise<User> {
diff --git a/apps/mobile/data/queries/billing.ts b/apps/mobile/data/queries/billing.ts
new file mode 100644
index 0000000000..db6ec4e625
--- /dev/null
+++ b/apps/mobile/data/queries/billing.ts
@@ -0,0 +1,32 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "@/data/api";
+
+export const appConfigOptions = () =>
+ queryOptions({
+ queryKey: ["config"] as const,
+ queryFn: ({ signal }) => api.getConfig({ signal }),
+ staleTime: 5 * 60 * 1000,
+ });
+
+// Mirrors packages/core/billing/workspace-subscription-queries.ts. The route
+// resolves the workspace from X-Workspace-Slug, while the cache key prevents a
+// summary from one workspace being rendered after a mobile workspace switch.
+export const workspaceSubscriptionKeys = {
+ all: (wsId: string | null) => ["workspace-subscriptions", wsId] as const,
+ summary: (wsId: string | null) =>
+ [...workspaceSubscriptionKeys.all(wsId), "summary"] as const,
+};
+
+export const workspaceSubscriptionSummaryOptions = (
+ wsId: string | null,
+ enabled: boolean,
+) =>
+ queryOptions({
+ queryKey: workspaceSubscriptionKeys.summary(wsId),
+ queryFn: ({ signal }) => api.getWorkspaceSubscriptionSummary({ signal }),
+ enabled: !!wsId && enabled,
+ // Recovery actions are Cloud-authoritative and may change immediately
+ // after an upgrade, so opening a notice must revalidate this summary.
+ staleTime: 0,
+ retry: false,
+ });
diff --git a/apps/mobile/lib/inbox-display.test.ts b/apps/mobile/lib/inbox-display.test.ts
index 3baa5b3c9e..25b5376e8d 100644
--- a/apps/mobile/lib/inbox-display.test.ts
+++ b/apps/mobile/lib/inbox-display.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
import type { InboxItem } from "@multica/core/types";
-import { deduplicateInboxItems } from "./inbox-display";
+import {
+ deduplicateInboxItems,
+ getAutopilotQuotaBody,
+ getInboxDisplayTitle,
+ getInboxNavigationTarget,
+} from "./inbox-display";
function item(overrides: Partial<InboxItem>): InboxItem {
return {
@@ -52,3 +57,97 @@ describe("deduplicateInboxItems", () => {
});
});
});
+
+describe("getInboxDisplayTitle", () => {
+ it("uses the same stable quota title as web instead of backend fallback copy", () => {
+ expect(
+ getInboxDisplayTitle(
+ item({
+ issue_id: null,
+ type: "autopilot_quota_exceeded",
+ title: "Autopilot quota exceeded (100/100)",
+ }),
+ ),
+ ).toBe("Autopilot run limit reached");
+ });
+
+ it("keeps paused autopilot copy on the server fallback path", () => {
+ expect(
+ getInboxDisplayTitle(
+ item({
+ issue_id: null,
+ type: "autopilot_paused",
+ title: "Paused after repeated failures",
+ }),
+ ),
+ ).toBe("Paused after repeated failures");
+ });
+});
+
+describe("getInboxNavigationTarget", () => {
+ it("opens issue-less quota notices in their workspace sheet", () => {
+ expect(
+ getInboxNavigationTarget(
+ item({ issue_id: null, type: "autopilot_quota_exceeded" }),
+ "acme",
+ "history-1",
+ ),
+ ).toEqual({
+ pathname: "/[workspace]/inbox/[id]",
+ params: { workspace: "acme", id: "inbox-1" },
+ });
+ });
+
+ it("preserves issue navigation and opens paused notices in the same sheet", () => {
+ expect(
+ getInboxNavigationTarget(item({}), "acme", "history-1"),
+ ).toMatchObject({
+ pathname: "/[workspace]/issue/[id]",
+ params: { workspace: "acme", id: "issue-1", h: "history-1" },
+ });
+ expect(
+ getInboxNavigationTarget(
+ item({ issue_id: null, type: "autopilot_paused" }),
+ "acme",
+ "history-1",
+ ),
+ ).toEqual({
+ pathname: "/[workspace]/inbox/[id]",
+ params: { workspace: "acme", id: "inbox-1" },
+ });
+ });
+});
+
+describe("getAutopilotQuotaBody", () => {
+ it("formats the machine reset timestamp for the device locale", () => {
+ const body = getAutopilotQuotaBody(
+ item({
+ issue_id: null,
+ type: "autopilot_quota_exceeded",
+ body: "Raw fallback 2026-09-01T00:00:00Z",
+ details: {
+ limit: "100",
+ reset_at: "2026-09-01T00:00:00Z",
+ autopilot_title: "Daily triage",
+ },
+ }),
+ );
+
+ expect(body).toContain("Daily triage");
+ expect(body).toContain("limit of 100 runs");
+ expect(body).not.toContain("2026-09-01T00:00:00Z");
+ });
+
+ it("keeps the server fallback when structured facts are incomplete", () => {
+ expect(
+ getAutopilotQuotaBody(
+ item({
+ issue_id: null,
+ type: "autopilot_quota_exceeded",
+ body: "Readable server fallback",
+ details: { limit: "100" },
+ }),
+ ),
+ ).toBe("Readable server fallback");
+ });
+});
diff --git a/apps/mobile/lib/inbox-display.ts b/apps/mobile/lib/inbox-display.ts
index f9e2b70adb..3137750c8c 100644
--- a/apps/mobile/lib/inbox-display.ts
+++ b/apps/mobile/lib/inbox-display.ts
@@ -8,6 +8,27 @@
*/
import type { InboxItem } from "@multica/core/types";
+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);
+}
+
+export function getAutopilotQuotaBody(item: InboxItem): string | null {
+ if (item.type !== "autopilot_quota_exceeded") return item.body;
+ const details = item.details ?? {};
+ const resetAt = formatResetAt(details.reset_at);
+ if (!details.limit || !resetAt) return item.body;
+ if (details.autopilot_title) {
+ return `Autopilot “${details.autopilot_title}” was not started because this workspace has reached its limit of ${details.limit} runs for the current period. The allowance resets ${resetAt}.`;
+ }
+ return `This workspace has reached its limit of ${details.limit} autopilot runs for the current period. This execution was not started. The allowance resets ${resetAt}.`;
+}
+
function singleLine(value: string | null | undefined): string {
return (value ?? "").replace(/\s+/g, " ").trim();
}
@@ -35,6 +56,12 @@ export function stripQuickCreatePrefix(
export function getInboxDisplayTitle(item: InboxItem): string {
const details = item.details ?? {};
+ // Mobile is English-only today. Mirror web's localized system-notice titles
+ // rather than exposing backend fallback copy that can include raw counts.
+ switch (item.type) {
+ case "autopilot_quota_exceeded":
+ return "Autopilot run limit reached";
+ }
if (item.type === "quick_create_done") {
const cleanedTitle = stripQuickCreatePrefix(item.title, details.identifier);
if (cleanedTitle) return cleanedTitle;
@@ -51,6 +78,35 @@ export function getInboxDisplayTitle(item: InboxItem): string {
return item.title;
}
+export function getInboxNavigationTarget(
+ item: InboxItem,
+ workspace: string | null,
+ historyToken: string,
+) {
+ if (!workspace) return null;
+ if (item.issue_id) {
+ return {
+ pathname: "/[workspace]/issue/[id]" as const,
+ params: {
+ workspace,
+ id: item.issue_id,
+ highlight: item.details?.comment_id,
+ h: historyToken,
+ },
+ };
+ }
+ if (
+ item.type === "autopilot_quota_exceeded" ||
+ item.type === "autopilot_paused"
+ ) {
+ return {
+ pathname: "/[workspace]/inbox/[id]" as const,
+ params: { workspace, id: item.id },
+ };
+ }
+ return null;
+}
+
/**
* Deduplicate inbox items by issue_id (Linear-style: one entry per issue).
*
diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.ts
index c48edd4189..36c877a0dc 100644
--- a/packages/core/billing/index.ts
+++ b/packages/core/billing/index.ts
@@ -2,3 +2,4 @@ export * from "./queries";
export * from "./mutations";
export * from "./workspace-subscription-queries";
export * from "./workspace-subscription-mutations";
+export * from "./recovery";
diff --git a/packages/core/billing/recovery.test.ts b/packages/core/billing/recovery.test.ts
new file mode 100644
index 0000000000..4278e09a5d
--- /dev/null
+++ b/packages/core/billing/recovery.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { resolveBillingRecovery } from "./recovery";
+
+const actions = (
+ overrides: Partial<{
+ checkout: boolean;
+ portal: boolean;
+ purchaseSeats: boolean;
+ }> = {},
+) => ({ checkout: false, portal: false, purchaseSeats: false, ...overrides });
+
+describe("resolveBillingRecovery", () => {
+ it("fails closed when workspace billing is disabled", () => {
+ expect(
+ resolveBillingRecovery({
+ actions: actions({ checkout: true }),
+ billingEnabled: false,
+ loading: false,
+ }),
+ ).toBe("billing_disabled");
+ });
+
+ it.each([
+ [actions({ checkout: true }), "checkout"],
+ [actions({ portal: true }), "portal"],
+ [actions({ purchaseSeats: true }), "billing"],
+ [actions(), "contact_admin"],
+ ] as const)("uses Cloud actions %# as %s", (availableActions, expected) => {
+ expect(
+ resolveBillingRecovery({
+ actions: availableActions,
+ billingEnabled: true,
+ loading: false,
+ }),
+ ).toBe(expected);
+ });
+
+ it("distinguishes a pending read from an unavailable one", () => {
+ expect(
+ resolveBillingRecovery({
+ actions: undefined,
+ billingEnabled: true,
+ loading: true,
+ }),
+ ).toBe("checking");
+ expect(
+ resolveBillingRecovery({
+ actions: undefined,
+ billingEnabled: true,
+ loading: false,
+ }),
+ ).toBe("billing_unavailable");
+ });
+
+ it("falls back to Billing after a portal launch fails", () => {
+ expect(
+ resolveBillingRecovery({
+ actions: actions({ portal: true }),
+ billingEnabled: true,
+ loading: false,
+ portalFailed: true,
+ }),
+ ).toBe("billing_unavailable");
+ });
+});
diff --git a/packages/core/billing/recovery.ts b/packages/core/billing/recovery.ts
new file mode 100644
index 0000000000..e21b2bc346
--- /dev/null
+++ b/packages/core/billing/recovery.ts
@@ -0,0 +1,38 @@
+import type { WorkspaceSubscriptionSummary } from "../types";
+
+export type BillingRecoveryKind =
+ | "billing_disabled"
+ | "checkout"
+ | "portal"
+ | "billing"
+ | "contact_admin"
+ | "checking"
+ | "billing_unavailable";
+
+type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
+
+/**
+ * Resolve the one recovery state shared by every issue/quota-limit surface.
+ * Cloud's complete availableActions object is authoritative: callers must not
+ * infer checkout or portal access from a locally cached member role or plan.
+ */
+export function resolveBillingRecovery({
+ actions,
+ billingEnabled,
+ loading,
+ portalFailed = false,
+}: {
+ actions: BillingActions | undefined;
+ billingEnabled: boolean;
+ loading: boolean;
+ portalFailed?: boolean;
+}): BillingRecoveryKind {
+ if (!billingEnabled) return "billing_disabled";
+ if (portalFailed) return "billing_unavailable";
+ if (actions?.checkout) return "checkout";
+ if (actions?.portal) return "portal";
+ if (actions?.purchaseSeats) return "billing";
+ if (actions) return "contact_admin";
+ if (loading) return "checking";
+ return "billing_unavailable";
+}
diff --git a/packages/core/modals/index.ts b/packages/core/modals/index.ts
index f3f1a9c021..69c6261e94 100644
--- a/packages/core/modals/index.ts
+++ b/packages/core/modals/index.ts
@@ -1 +1,2 @@
export { useModalStore } from "./store";
+export type { IssueLimitRecoveryReason } from "./store";
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index 5a08e3977a..01ccfabc58 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -14,13 +14,19 @@ type ModalType =
| "issue-run-confirm"
| null;
+export type IssueLimitRecoveryReason = "issue_limit" | "autopilot_quota";
+
interface ModalStore {
modal: ModalType;
data: Record<string, unknown> | null;
issueLimitRecoveryWorkspaceId: string | null;
+ issueLimitRecoveryReason: IssueLimitRecoveryReason;
open: (modal: NonNullable<ModalType>, data?: Record<string, unknown> | null) => void;
close: () => void;
- showIssueLimitRecovery: (workspaceId: string) => void;
+ showIssueLimitRecovery: (
+ workspaceId: string,
+ reason?: IssueLimitRecoveryReason,
+ ) => void;
dismissIssueLimitRecovery: () => void;
}
@@ -28,10 +34,17 @@ export const useModalStore = create<ModalStore>((set) => ({
modal: null,
data: null,
issueLimitRecoveryWorkspaceId: null,
+ issueLimitRecoveryReason: "issue_limit",
open: (modal, data = null) => set({ modal, data }),
close: () => set({ modal: null, data: null }),
- showIssueLimitRecovery: (workspaceId) =>
- set({ issueLimitRecoveryWorkspaceId: workspaceId }),
+ showIssueLimitRecovery: (workspaceId, reason = "issue_limit") =>
+ set({
+ issueLimitRecoveryWorkspaceId: workspaceId,
+ issueLimitRecoveryReason: reason,
+ }),
dismissIssueLimitRecovery: () =>
- set({ issueLimitRecoveryWorkspaceId: null }),
+ set({
+ issueLimitRecoveryWorkspaceId: null,
+ issueLimitRecoveryReason: "issue_limit",
+ }),
}));
diff --git a/packages/core/package.json b/packages/core/package.json
index 0ea7437232..d6c1c491d9 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -111,6 +111,7 @@
"./issue-views/baseline": "./issue-views/baseline.ts",
"./issue-views/preferences": "./issue-views/preferences.ts",
"./billing": "./billing/index.ts",
+ "./billing/recovery": "./billing/recovery.ts",
"./billing/queries": "./billing/queries.ts",
"./billing/mutations": "./billing/mutations.ts",
"./github": "./github/index.ts",
diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.ts
index 61638d7a4c..1605f18050 100644
--- a/packages/core/types/inbox.ts
+++ b/packages/core/types/inbox.ts
@@ -24,7 +24,11 @@ export type InboxItemType =
// Quick create whose outcome could not be verified. Distinct from
// quick_create_failed because it must NOT be rendered with failure framing:
// the issue may actually have been created.
- | "quick_create_unconfirmed";
+ | "quick_create_unconfirmed"
+ // System notifications are intentionally issue-less. Keep them in the
+ // same Inbox model so read/archive/realtime behavior remains consistent.
+ | "autopilot_paused"
+ | "autopilot_quota_exceeded";
/**
* One workspace's unread inbox count in the cross-workspace summary
diff --git a/packages/views/inbox/components/autopilot-quota-notice.test.tsx b/packages/views/inbox/components/autopilot-quota-notice.test.tsx
new file mode 100644
index 0000000000..56b66f9fb4
--- /dev/null
+++ b/packages/views/inbox/components/autopilot-quota-notice.test.tsx
@@ -0,0 +1,79 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { InboxItem } from "@multica/core/types";
+import en from "../../locales/en/inbox.json";
+import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
+
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (accessor: (dict: unknown) => string, params?: Record<string, string>) => {
+ const template = accessor(en);
+ if (!params) return template;
+ return template.replace(
+ /\{\{(\w+)\}\}/g,
+ (_, key: string) => params[key] ?? "",
+ );
+ },
+ }),
+}));
+
+function item(overrides: Partial<InboxItem> = {}): InboxItem {
+ return {
+ id: "inbox-1",
+ workspace_id: "workspace-1",
+ recipient_type: "member",
+ recipient_id: "member-1",
+ actor_type: "system",
+ actor_id: null,
+ type: "autopilot_quota_exceeded",
+ severity: "attention",
+ issue_id: null,
+ title: "Autopilot run limit reached",
+ body: "Fallback body",
+ issue_status: null,
+ read: false,
+ archived: false,
+ created_at: "2026-08-28T08:00:00Z",
+ details: {
+ limit: "100",
+ reset_at: "2026-09-01T00:00:00Z",
+ },
+ ...overrides,
+ };
+}
+
+describe("AutopilotQuotaNotice", () => {
+ it("shows localized rejection facts and opens the shared recovery surface", () => {
+ const onOpenRecovery = vi.fn();
+
+ render(
+ <AutopilotQuotaNotice
+ item={item()}
+ onOpenRecovery={onOpenRecovery}
+ />,
+ );
+
+ expect(screen.getByText(/limit of 100 autopilot runs/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View upgrade options" }));
+ expect(onOpenRecovery).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the first blocked autopilot out of the workspace-level body", () => {
+ render(
+ <AutopilotQuotaNotice
+ item={item({
+ details: {
+ limit: "100",
+ reset_at: "2026-09-01T00:00:00Z",
+ autopilot_title: "Daily triage",
+ },
+ })}
+ onOpenRecovery={vi.fn()}
+ />,
+ );
+
+ expect(screen.queryByText(/Daily triage/)).not.toBeInTheDocument();
+ expect(screen.getByText(/limit of 100 autopilot runs/)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "View upgrade options" })).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/inbox/components/autopilot-quota-notice.tsx b/packages/views/inbox/components/autopilot-quota-notice.tsx
new file mode 100644
index 0000000000..aed08cd615
--- /dev/null
+++ b/packages/views/inbox/components/autopilot-quota-notice.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import type { InboxItem } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { useT } from "../../i18n";
+
+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);
+}
+
+export function AutopilotQuotaNotice({
+ item,
+ onOpenRecovery,
+}: {
+ item: InboxItem;
+ onOpenRecovery: () => void;
+}) {
+ const { t } = useT("inbox");
+ const details = item.details ?? {};
+ const resetAt = formatResetAt(details.reset_at);
+
+ let body = item.body;
+ if (details.limit && resetAt) {
+ body = t(($) => $.detail.autopilot_quota_exceeded_body, {
+ limit: details.limit,
+ resetAt,
+ });
+ }
+
+ return (
+ <>
+ {body && (
+ <div className="mt-4 whitespace-pre-wrap text-body leading-relaxed text-foreground">
+ {body}
+ </div>
+ )}
+ <Button className="mt-4" size="sm" onClick={onOpenRecovery}>
+ {t(($) => $.detail.autopilot_quota_upgrade)}
+ </Button>
+ </>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsx
index 78d02a0100..2e0f44e4df 100644
--- a/packages/views/inbox/components/inbox-context-menu.test.tsx
+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx
@@ -27,7 +27,10 @@ vi.mock("../../issues/components/issue-agent-activity-indicator", () => ({
IssueAgentActivityIndicator: () => null,
}));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
-vi.mock("./inbox-detail-label", () => ({ InboxDetailLabel: () => null }));
+vi.mock("./inbox-detail-label", () => ({
+ InboxDetailLabel: () => null,
+ useTypeLabels: () => ({}),
+}));
// Import after mocks.
import { InboxContextMenuProvider } from "./inbox-context-menu";
diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsx
index 335a8aa2f3..cf18167efb 100644
--- a/packages/views/inbox/components/inbox-detail-label.tsx
+++ b/packages/views/inbox/components/inbox-detail-label.tsx
@@ -35,6 +35,8 @@ export function useTypeLabels(): Record<InboxItemType, string> {
quick_create_done: t(($) => $.types.quick_create_done),
quick_create_failed: t(($) => $.types.quick_create_failed),
quick_create_unconfirmed: t(($) => $.types.quick_create_unconfirmed),
+ autopilot_paused: t(($) => $.types.autopilot_paused),
+ autopilot_quota_exceeded: t(($) => $.types.autopilot_quota_exceeded),
};
}
@@ -131,6 +133,8 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {
if (detail) return <span>{detail}</span>;
return <span>{typeLabels[item.type]}</span>;
}
+ case "autopilot_quota_exceeded":
+ return <span>{t(($) => $.labels.autopilot_quota_blocked)}</span>;
default:
return <span>{typeLabels[item.type] ?? item.type}</span>;
}
diff --git a/packages/views/inbox/components/inbox-display.test.ts b/packages/views/inbox/components/inbox-display.test.ts
index 39c0e943a0..35d639e6bc 100644
--- a/packages/views/inbox/components/inbox-display.test.ts
+++ b/packages/views/inbox/components/inbox-display.test.ts
@@ -4,6 +4,7 @@ import type { InboxItem } from "@multica/core/types";
import {
getInboxDisplayTitle,
getQuickCreateOutcomeDetail,
+ isAutopilotQuotaNotice,
isQuickCreateOutcome,
resolveDetailItem,
stripQuickCreatePrefix,
@@ -103,6 +104,11 @@ describe("inbox display helpers", () => {
"File a bug about the flaky test",
);
});
+
+ 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);
+ });
});
describe("resolveDetailItem", () => {
diff --git a/packages/views/inbox/components/inbox-display.ts b/packages/views/inbox/components/inbox-display.ts
index 93f2b457c5..7e681c5dd6 100644
--- a/packages/views/inbox/components/inbox-display.ts
+++ b/packages/views/inbox/components/inbox-display.ts
@@ -52,6 +52,10 @@ export function isQuickCreateOutcome(type: InboxItem["type"]): boolean {
return type === "quick_create_failed" || type === "quick_create_unconfirmed";
}
+export function isAutopilotQuotaNotice(type: InboxItem["type"]): boolean {
+ return type === "autopilot_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-list-item.test.tsx b/packages/views/inbox/components/inbox-list-item.test.tsx
index b9540ae2c4..43a12a8ea3 100644
--- a/packages/views/inbox/components/inbox-list-item.test.tsx
+++ b/packages/views/inbox/components/inbox-list-item.test.tsx
@@ -70,7 +70,13 @@ vi.mock("../../common/actor-avatar", () => ({
/>
),
}));
-vi.mock("./inbox-detail-label", () => ({ InboxDetailLabel: () => null }));
+vi.mock("./inbox-detail-label", () => ({
+ InboxDetailLabel: () => null,
+ useTypeLabels: () => ({
+ autopilot_paused: "Autopilot paused",
+ autopilot_quota_exceeded: "Autopilot run limit reached",
+ }),
+}));
vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }) }));
function item(overrides: Partial<InboxItem> = {}): InboxItem {
diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsx
index dbf46b56e5..d76c0b5ca8 100644
--- a/packages/views/inbox/components/inbox-list-item.tsx
+++ b/packages/views/inbox/components/inbox-list-item.tsx
@@ -9,8 +9,11 @@ import { ActorAvatar } from "../../common/actor-avatar";
import { Archive, ArchiveRestore } from "lucide-react";
import type { InboxItem } from "@multica/core/types";
import type { InboxView } from "./inbox-view";
-import { InboxDetailLabel } from "./inbox-detail-label";
-import { getInboxDisplayTitle } from "./inbox-display";
+import { InboxDetailLabel, useTypeLabels } from "./inbox-detail-label";
+import {
+ getInboxDisplayTitle,
+ isAutopilotQuotaNotice,
+} from "./inbox-display";
import { useInboxContextMenu } from "./inbox-context-menu";
import { useStatusLabel } from "../../issues/utils/status-label";
import { InboxRowMenu } from "./inbox-row-menu";
@@ -53,6 +56,7 @@ export function InboxListItem({
}) {
const { t } = useT("inbox");
const timeAgo = useTimeAgo();
+ const typeLabels = useTypeLabels();
// Inbox is a cross-workspace surface, so the catalog is read against the
// item's OWN workspace rather than the route's. (MUL-6243)
const { categoryOf: statusCategoryOf, colorOf: statusColorOf } =
@@ -68,7 +72,9 @@ export function InboxListItem({
? paths.workspace(slug).issueDetail(item.issue_id)
: null;
const intentNavigate = useIntentNavigate();
- const displayTitle = getInboxDisplayTitle(item);
+ const displayTitle = isAutopilotQuotaNotice(item.type)
+ ? typeLabels[item.type]
+ : getInboxDisplayTitle(item);
const isArchivedView = view === "archived";
// Archiving deliberately leaves `read` untouched so unarchiving restores the
// real unread state, so archived rows would otherwise keep an unread marker
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 94be394836..d3a5b9fe52 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -69,9 +69,13 @@ const archiveMutate = vi.fn();
const unarchiveMutate = vi.fn();
const retrySourceContextMutateAsync = vi.fn();
const showIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());
+const showAutopilotQuotaRecoveryPrompt = vi.hoisted(() => vi.fn());
vi.mock("../../modals/use-issue-limit-upgrade-prompt", () => ({
- useIssueLimitUpgradePrompt: () => showIssueLimitUpgradePrompt,
+ useIssueLimitUpgradePrompt: (reason?: string) =>
+ reason === "autopilot_quota"
+ ? showAutopilotQuotaRecoveryPrompt
+ : showIssueLimitUpgradePrompt,
}));
vi.mock("@multica/core/inbox/mutations", () => {
@@ -190,6 +194,21 @@ vi.mock("./inbox-context-menu", () => ({
},
}));
vi.mock("./inbox-detail-label", () => ({ useTypeLabels: () => ({}) }));
+vi.mock("./autopilot-quota-notice", () => ({
+ AutopilotQuotaNotice: ({
+ onOpenRecovery,
+ }: {
+ onOpenRecovery: () => void;
+ }) => (
+ <button
+ type="button"
+ data-testid="autopilot-quota-recovery"
+ onClick={onOpenRecovery}
+ >
+ Recover
+ </button>
+ ),
+}));
vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }) }));
function item(overrides: Partial<InboxItem> = {}): InboxItem {
@@ -227,6 +246,7 @@ function reset() {
retrySourceContextMutateAsync.mockReset();
retrySourceContextMutateAsync.mockResolvedValue({});
showIssueLimitUpgradePrompt.mockClear();
+ showAutopilotQuotaRecoveryPrompt.mockClear();
modalState.modal = null;
vi.mocked(toast.success).mockClear();
vi.mocked(toast.error).mockClear();
@@ -483,6 +503,24 @@ describe("InboxPage", () => {
expect(toast.success).toHaveBeenCalledTimes(1);
});
+ it("opens quota-specific recovery from an autopilot quota notice", () => {
+ reset();
+ listData.active = [
+ item({
+ id: "autopilot-quota",
+ issue_id: null,
+ type: "autopilot_quota_exceeded",
+ }),
+ ];
+
+ render(<InboxPage />);
+ fireEvent.click(screen.getByTestId("row"));
+ fireEvent.click(screen.getByTestId("autopilot-quota-recovery"));
+
+ expect(showAutopilotQuotaRecoveryPrompt).toHaveBeenCalledTimes(1);
+ expect(showIssueLimitUpgradePrompt).not.toHaveBeenCalled();
+ });
+
it("shows issue-limit recovery when a source-context retry is rejected", async () => {
reset();
retrySourceContextMutateAsync.mockRejectedValue(
@@ -512,6 +550,7 @@ describe("InboxPage", () => {
await act(async () => undefined);
expect(showIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);
+ expect(showAutopilotQuotaRecoveryPrompt).not.toHaveBeenCalled();
expect(toast.error).not.toHaveBeenCalled();
});
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 2ec53e6f34..bbaa352be4 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -92,15 +92,20 @@ import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";
import { useTypeLabels } from "./inbox-detail-label";
import {
getInboxDisplayTitle,
+ isAutopilotQuotaNotice,
isQuickCreateOutcome,
resolveDetailItem,
} from "./inbox-display";
+import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
import { useT } from "../../i18n";
import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";
export function InboxPage() {
const { t } = useT("inbox");
const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();
+ const showAutopilotQuotaRecoveryPrompt = useIssueLimitUpgradePrompt(
+ "autopilot_quota",
+ );
const { searchParams, replace } = useNavigation();
const urlIssue = searchParams.get("issue") ?? "";
const urlView: InboxView =
@@ -708,15 +713,24 @@ export function InboxPage() {
</ErrorBoundary>
) : detailItem ? (
<div className="p-6">
- <h2 className="text-title font-semibold">{getInboxDisplayTitle(detailItem)}</h2>
+ <h2 className="text-title font-semibold">
+ {isAutopilotQuotaNotice(detailItem.type)
+ ? typeLabels[detailItem.type]
+ : getInboxDisplayTitle(detailItem)}
+ </h2>
<p className="mt-1 text-body text-muted-foreground">
{typeLabels[detailItem.type]} · {timeAgo(detailItem.created_at)}
</p>
- {detailItem.body && (
+ {isAutopilotQuotaNotice(detailItem.type) ? (
+ <AutopilotQuotaNotice
+ item={detailItem}
+ onOpenRecovery={showAutopilotQuotaRecoveryPrompt}
+ />
+ ) : detailItem.body ? (
<div className="mt-4 whitespace-pre-wrap text-body leading-relaxed text-foreground">
{detailItem.body}
</div>
- )}
+ ) : null}
{isQuickCreateOutcome(detailItem.type) && detailItem.details?.original_prompt && (
<div className="mt-4 rounded-md border bg-muted/40 p-3">
<p className="text-caption font-medium text-muted-foreground">
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index 0878aecb96..ce4ec0e977 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -50,6 +50,8 @@
"original_input": "Original input",
"retry_with_context": "Retry with context",
"edit_advanced": "Edit as advanced form",
+ "autopilot_quota_exceeded_body": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. Further autopilot runs will not start until the allowance resets {{resetAt}}.",
+ "autopilot_quota_upgrade": "View upgrade options",
"archive": "Archive",
"unarchive": "Unarchive"
},
@@ -72,7 +74,9 @@
"reaction_added": "Reacted",
"quick_create_done": "Created with agent",
"quick_create_failed": "Create with agent failed",
- "quick_create_unconfirmed": "Create with agent unconfirmed"
+ "quick_create_unconfirmed": "Create with agent unconfirmed",
+ "autopilot_paused": "Autopilot paused",
+ "autopilot_quota_exceeded": "Autopilot run limit reached"
},
"labels": {
"set_status_to": "Set status to",
@@ -85,7 +89,8 @@
"removed_due_date": "Removed due date",
"reacted_to_comment": "Reacted {{emoji}} to your comment",
"created_with_agent": "Created with agent: {{identifier}}",
- "failed_with_detail": "Failed: {{detail}}"
+ "failed_with_detail": "Failed: {{detail}}",
+ "autopilot_quota_blocked": "Run blocked because the limit was reached"
},
"toasts": {
"source_context_retry_started": "Retry started with the original context",
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index a78404625b..1d2759529d 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -172,6 +172,19 @@
"portal_action": "Open Billing Portal",
"billing_action": "View Billing"
},
+ "autopilot_quota_limit": {
+ "title": "This workspace has reached its autopilot run limit",
+ "checking_description": "Checking the billing actions available for this workspace…",
+ "upgrade_description": "Upgrade to Pro to restore autopilot runs.",
+ "portal_description": "Open Billing Portal to manage this workspace's subscription and restore autopilot runs.",
+ "contact_description": "Ask a workspace owner or admin to upgrade to Pro.",
+ "billing_description": "Open Billing to see the upgrade options available for this workspace.",
+ "billing_unavailable_description": "Billing actions could not be loaded. Open Billing to try again.",
+ "billing_disabled_description": "Wait for the current allowance to reset, or contact your workspace administrator.",
+ "upgrade_action": "Upgrade to Pro",
+ "portal_action": "Open Billing Portal",
+ "billing_action": "View Billing"
+ },
"toast_link_subissues_all_failed": "Failed to link sub-issues",
"toast_link_subissues_partial": "Failed to link {{failed}} of {{total}} sub-issues",
"toast_link_labels_failed": "Failed to attach labels",
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index c0d99c9d80..7b71fcd1da 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -48,6 +48,8 @@
"original_input": "元の入力",
"retry_with_context": "コンテキストを保持して再試行",
"edit_advanced": "詳細フォームで編集",
+ "autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるまで、以降の自動化は開始されません。",
+ "autopilot_quota_upgrade": "アップグレード方法を見る",
"archive": "アーカイブ",
"unarchive": "アーカイブ解除"
},
@@ -70,7 +72,9 @@
"reaction_added": "リアクションあり",
"quick_create_done": "エージェントで作成",
"quick_create_failed": "エージェントでの作成に失敗",
- "quick_create_unconfirmed": "エージェントでの作成結果は未確認"
+ "quick_create_unconfirmed": "エージェントでの作成結果は未確認",
+ "autopilot_paused": "自動化を一時停止しました",
+ "autopilot_quota_exceeded": "自動化の実行上限に達しました"
},
"labels": {
"set_status_to": "ステータスを変更:",
@@ -83,7 +87,8 @@
"removed_due_date": "期限を削除",
"reacted_to_comment": "あなたのコメントに {{emoji}} のリアクションをしました",
"created_with_agent": "エージェントで作成: {{identifier}}",
- "failed_with_detail": "失敗: {{detail}}"
+ "failed_with_detail": "失敗: {{detail}}",
+ "autopilot_quota_blocked": "上限に達したため実行をブロックしました"
},
"toasts": {
"source_context_retry_started": "元のコンテキストで再試行を開始しました",
diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.json
index f541903dde..2988f30657 100644
--- a/packages/views/locales/ja/modals.json
+++ b/packages/views/locales/ja/modals.json
@@ -170,6 +170,19 @@
"portal_action": "請求ポータルを開く",
"billing_action": "請求設定を表示"
},
+ "autopilot_quota_limit": {
+ "title": "このワークスペースはオートパイロット実行数の上限に達しました",
+ "checking_description": "このワークスペースで利用可能な請求操作を確認しています…",
+ "upgrade_description": "Pro にアップグレードすると、オートパイロット実行を再開できます。",
+ "portal_description": "請求ポータルを開いてワークスペースのサブスクリプションを管理し、オートパイロット実行を再開してください。",
+ "contact_description": "ワークスペースの所有者または管理者に Pro へのアップグレードを依頼してください。",
+ "billing_description": "請求設定を開いて、このワークスペースで利用可能なアップグレードオプションを確認してください。",
+ "billing_unavailable_description": "請求操作を読み込めませんでした。請求設定を開いて再試行してください。",
+ "billing_disabled_description": "現在の実行枠がリセットされるまで待つか、ワークスペースの管理者に連絡してください。",
+ "upgrade_action": "Pro にアップグレード",
+ "portal_action": "請求ポータルを開く",
+ "billing_action": "請求設定を表示"
+ },
"toast_link_subissues_all_failed": "サブタスクをリンクできませんでした",
"toast_link_subissues_partial": "サブタスク {{total}} 件中 {{failed}} 件をリンクできませんでした",
"toast_link_labels_failed": "ラベルを付けられませんでした",
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index 6ace0a1280..3a0c2cb5ff 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -48,6 +48,8 @@
"original_input": "원본 입력",
"retry_with_context": "컨텍스트를 유지하여 재시도",
"edit_advanced": "고급 양식으로 수정",
+ "autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 자동화 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화될 때까지 이후 자동화 실행은 시작되지 않습니다.",
+ "autopilot_quota_upgrade": "업그레이드 옵션 보기",
"archive": "보관",
"unarchive": "보관 해제"
},
@@ -70,7 +72,9 @@
"reaction_added": "반응 추가됨",
"quick_create_done": "에이전트로 생성됨",
"quick_create_failed": "에이전트 생성 실패",
- "quick_create_unconfirmed": "에이전트 생성 결과 미확인"
+ "quick_create_unconfirmed": "에이전트 생성 결과 미확인",
+ "autopilot_paused": "자동화 일시 중지됨",
+ "autopilot_quota_exceeded": "자동화 실행 한도 도달"
},
"labels": {
"set_status_to": "상태 변경:",
@@ -83,7 +87,8 @@
"removed_due_date": "마감일 제거됨",
"reacted_to_comment": "내 댓글에 {{emoji}} 반응을 남겼습니다",
"created_with_agent": "에이전트가 생성: {{identifier}}",
- "failed_with_detail": "실패: {{detail}}"
+ "failed_with_detail": "실패: {{detail}}",
+ "autopilot_quota_blocked": "한도에 도달하여 실행이 차단됨"
},
"toasts": {
"source_context_retry_started": "원본 컨텍스트로 재시도를 시작했습니다",
diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.json
index 57291b125f..d473df5688 100644
--- a/packages/views/locales/ko/modals.json
+++ b/packages/views/locales/ko/modals.json
@@ -170,6 +170,19 @@
"portal_action": "결제 포털 열기",
"billing_action": "결제 설정 보기"
},
+ "autopilot_quota_limit": {
+ "title": "이 워크스페이스가 오토파일럿 실행 한도에 도달했습니다",
+ "checking_description": "이 워크스페이스에서 사용할 수 있는 결제 작업을 확인하는 중입니다…",
+ "upgrade_description": "Pro로 업그레이드하면 오토파일럿 실행을 복구할 수 있습니다.",
+ "portal_description": "결제 포털을 열어 이 워크스페이스의 구독을 관리하고 오토파일럿 실행을 복구하세요.",
+ "contact_description": "워크스페이스 소유자 또는 관리자에게 Pro 업그레이드를 요청하세요.",
+ "billing_description": "결제 설정에서 이 워크스페이스에 사용 가능한 업그레이드 옵션을 확인하세요.",
+ "billing_unavailable_description": "결제 작업을 불러오지 못했습니다. 결제 설정을 열어 다시 시도하세요.",
+ "billing_disabled_description": "현재 실행 할당량이 재설정될 때까지 기다리거나 워크스페이스 관리자에게 문의하세요.",
+ "upgrade_action": "Pro로 업그레이드",
+ "portal_action": "결제 포털 열기",
+ "billing_action": "결제 설정 보기"
+ },
"toast_link_subissues_all_failed": "하위 태스크를 연결하지 못했습니다",
"toast_link_subissues_partial": "하위 태스크 {{total}}개 중 {{failed}}개를 연결하지 못했습니다",
"toast_link_labels_failed": "라벨을 연결하지 못했습니다",
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index 6f46862336..dfecff182e 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -48,6 +48,8 @@
"original_input": "原始输入",
"retry_with_context": "保留上下文重试",
"edit_advanced": "在完整表单中编辑",
+ "autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置前,后续自动化执行将不会启动。",
+ "autopilot_quota_upgrade": "查看升级方案",
"archive": "归档",
"unarchive": "取消归档"
},
@@ -70,7 +72,9 @@
"reaction_added": "添加了表情反应",
"quick_create_done": "通过智能体创建",
"quick_create_failed": "通过智能体创建失败",
- "quick_create_unconfirmed": "通过智能体创建结果未确认"
+ "quick_create_unconfirmed": "通过智能体创建结果未确认",
+ "autopilot_paused": "自动化已暂停",
+ "autopilot_quota_exceeded": "自动化执行次数已用完"
},
"labels": {
"set_status_to": "状态设为",
@@ -83,7 +87,8 @@
"removed_due_date": "移除了截止日期",
"reacted_to_comment": "用 {{emoji}} 回应了你的评论",
"created_with_agent": "通过智能体创建:{{identifier}}",
- "failed_with_detail": "失败:{{detail}}"
+ "failed_with_detail": "失败:{{detail}}",
+ "autopilot_quota_blocked": "执行已被阻止:额度已用完"
},
"toasts": {
"source_context_retry_started": "已使用原始上下文开始重试",
diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.json
index 4e15b7ea96..12872daef6 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -170,6 +170,19 @@
"portal_action": "打开账单门户",
"billing_action": "查看账单"
},
+ "autopilot_quota_limit": {
+ "title": "该工作区的自动化执行次数已达到上限",
+ "checking_description": "正在查询该工作区可用的账单操作…",
+ "upgrade_description": "升级到 Pro 后可恢复自动化执行。",
+ "portal_description": "打开账单门户管理该工作区的订阅,以恢复自动化执行。",
+ "contact_description": "请联系工作区所有者或管理员升级到 Pro。",
+ "billing_description": "请前往账单设置查看该工作区可用的升级选项。",
+ "billing_unavailable_description": "暂时无法加载账单操作,请前往账单设置重试。",
+ "billing_disabled_description": "请等待当前额度重置,或联系工作区管理员。",
+ "upgrade_action": "升级到 Pro",
+ "portal_action": "打开账单门户",
+ "billing_action": "查看账单"
+ },
"toast_link_subissues_all_failed": "关联子任务失败",
"toast_link_subissues_partial": "{{total}} 个子任务中有 {{failed}} 个关联失败",
"toast_link_labels_failed": "关联标签失败",
diff --git a/packages/views/modals/issue-limit-upgrade-dialog.test.tsx b/packages/views/modals/issue-limit-upgrade-dialog.test.tsx
index b0a987b529..db589be4e4 100644
--- a/packages/views/modals/issue-limit-upgrade-dialog.test.tsx
+++ b/packages/views/modals/issue-limit-upgrade-dialog.test.tsx
@@ -160,6 +160,7 @@ describe("IssueLimitUpgradeDialog", () => {
modal: null,
data: null,
issueLimitRecoveryWorkspaceId: null,
+ issueLimitRecoveryReason: "issue_limit",
});
mockSummaryQuery.mockImplementation(async () => {
if (summaryState.pending) return summaryState.pending;
@@ -177,6 +178,7 @@ describe("IssueLimitUpgradeDialog", () => {
modal: null,
data: null,
issueLimitRecoveryWorkspaceId: null,
+ issueLimitRecoveryReason: "issue_limit",
});
});
@@ -197,6 +199,35 @@ describe("IssueLimitUpgradeDialog", () => {
expect(screen.getAllByRole("button", { name: "Close" })).toHaveLength(1);
});
+ it("uses autopilot-specific copy when Inbox opens the shared recovery surface", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ renderPrompt();
+
+ act(() => {
+ useModalStore
+ .getState()
+ .showIssueLimitRecovery("ws-test", "autopilot_quota");
+ });
+
+ expect(
+ await screen.findByRole("dialog", {
+ name: "This workspace has reached its autopilot run limit",
+ }),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText("Upgrade to Pro to restore autopilot runs."),
+ ).toBeInTheDocument();
+
+ act(() => useModalStore.getState().dismissIssueLimitRecovery());
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", {
+ name: "This workspace has reached its autopilot run limit",
+ }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
it("closes only recovery when Escape is pressed above a create dialog", async () => {
summaryState.value = { availableActions: actions({ checkout: true }) };
renderPrompt({ layered: true });
diff --git a/packages/views/modals/issue-limit-upgrade-dialog.tsx b/packages/views/modals/issue-limit-upgrade-dialog.tsx
index b467e7fc4a..ff02681074 100644
--- a/packages/views/modals/issue-limit-upgrade-dialog.tsx
+++ b/packages/views/modals/issue-limit-upgrade-dialog.tsx
@@ -7,10 +7,14 @@ import {
useCreateWorkspaceSubscriptionPortal,
workspaceSubscriptionSummaryOptions,
} from "@multica/core/billing";
+import { resolveBillingRecovery } from "@multica/core/billing/recovery";
import { useFeatureEnabled } from "@multica/core/config";
import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useModalStore } from "@multica/core/modals";
+import {
+ useModalStore,
+ type IssueLimitRecoveryReason,
+} from "@multica/core/modals";
import { useWorkspacePaths } from "@multica/core/paths";
import type { WorkspaceSubscriptionSummary } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
@@ -26,8 +30,8 @@ import { useT } from "../i18n";
import { useNavigation } from "../navigation";
import { openExternal } from "../platform";
-type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
type ModalsT = ReturnType<typeof useT<"modals">>["t"];
+type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
function createPortalIdempotencyKey(wsId: string): string {
const suffix =
@@ -37,7 +41,8 @@ function createPortalIdempotencyKey(wsId: string): string {
}
/**
- * Centered recovery surface shared by manual create, Quick Create, and Inbox.
+ * Centered recovery surface shared by manual create, Quick Create, and quota
+ * notices in Inbox. The modal reason changes copy, never authorization.
* Cloud's complete action set is the only input that decides which billing
* action appears; no local role, plan, subscription, or quota inference does.
*/
@@ -46,6 +51,9 @@ export function IssueLimitUpgradeDialog() {
(state) => state.issueLimitRecoveryWorkspaceId,
);
const dismiss = useModalStore((state) => state.dismissIssueLimitRecovery);
+ const recoveryReason = useModalStore(
+ (state) => state.issueLimitRecoveryReason,
+ );
const { t } = useT("modals");
const wsId = useWorkspaceId();
const visible = recoveryWorkspaceId === wsId;
@@ -119,12 +127,13 @@ export function IssueLimitUpgradeDialog() {
};
const actions = summaryQuery.data?.availableActions;
+ const copy = getRecoveryCopy(t, recoveryReason);
const recovery = resolveRecoveryPresentation({
actions,
billingEnabled,
loading: billingEnabled && !actions && summaryQuery.isFetching,
portalFailed,
- t,
+ copy,
openBilling,
openPortal,
});
@@ -153,7 +162,7 @@ export function IssueLimitUpgradeDialog() {
</div>
<DialogHeader className="mt-5 items-center gap-3 text-center">
<DialogTitle className="max-w-md text-balance text-display-sm font-semibold leading-tight tracking-tight">
- {t(($) => $.create_issue.issue_limit.title)}
+ {copy.title}
</DialogTitle>
<DialogDescription className="max-w-sm text-pretty text-center text-body leading-6">
{recovery.description}
@@ -195,12 +204,96 @@ interface RecoveryPresentation {
};
}
+interface RecoveryCopy {
+ title: string;
+ billingDisabledDescription: string;
+ upgradeDescription: string;
+ portalDescription: string;
+ contactDescription: string;
+ billingDescription: string;
+ billingUnavailableDescription: string;
+ checkingDescription: string;
+ upgradeAction: string;
+ portalAction: string;
+ billingAction: string;
+}
+
+function getRecoveryCopy(
+ t: ModalsT,
+ reason: IssueLimitRecoveryReason,
+): RecoveryCopy {
+ if (reason === "autopilot_quota") {
+ return {
+ title: t(($) => $.create_issue.autopilot_quota_limit.title),
+ billingDisabledDescription: t(
+ ($) =>
+ $.create_issue.autopilot_quota_limit.billing_disabled_description,
+ ),
+ upgradeDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.upgrade_description,
+ ),
+ portalDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.portal_description,
+ ),
+ contactDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.contact_description,
+ ),
+ billingDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.billing_description,
+ ),
+ billingUnavailableDescription: t(
+ ($) =>
+ $.create_issue.autopilot_quota_limit.billing_unavailable_description,
+ ),
+ checkingDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.checking_description,
+ ),
+ upgradeAction: t(
+ ($) => $.create_issue.autopilot_quota_limit.upgrade_action,
+ ),
+ portalAction: t(
+ ($) => $.create_issue.autopilot_quota_limit.portal_action,
+ ),
+ billingAction: t(
+ ($) => $.create_issue.autopilot_quota_limit.billing_action,
+ ),
+ };
+ }
+ return {
+ title: t(($) => $.create_issue.issue_limit.title),
+ billingDisabledDescription: t(
+ ($) => $.create_issue.issue_limit.billing_disabled_description,
+ ),
+ upgradeDescription: t(
+ ($) => $.create_issue.issue_limit.upgrade_description,
+ ),
+ portalDescription: t(
+ ($) => $.create_issue.issue_limit.portal_description,
+ ),
+ contactDescription: t(
+ ($) => $.create_issue.issue_limit.contact_description,
+ ),
+ billingDescription: t(
+ ($) => $.create_issue.issue_limit.billing_description,
+ ),
+ billingUnavailableDescription: t(
+ ($) => $.create_issue.issue_limit.billing_unavailable_description,
+ ),
+ checkingDescription: t(
+ ($) => $.create_issue.issue_limit.checking_description,
+ ),
+ upgradeAction: t(($) => $.create_issue.issue_limit.upgrade_action),
+ portalAction: t(($) => $.create_issue.issue_limit.portal_action),
+ billingAction: t(($) => $.create_issue.issue_limit.billing_action),
+ };
+}
+
function resolveRecoveryPresentation({
actions,
billingEnabled,
loading,
portalFailed,
- t,
+ copy,
openBilling,
openPortal,
}: {
@@ -208,81 +301,63 @@ function resolveRecoveryPresentation({
billingEnabled: boolean;
loading: boolean;
portalFailed: boolean;
- t: ModalsT;
+ copy: RecoveryCopy;
openBilling: () => void;
openPortal: () => Promise<void>;
}): RecoveryPresentation {
- if (!billingEnabled) {
- return {
- description: t(
- ($) => $.create_issue.issue_limit.billing_disabled_description,
- ),
- };
- }
-
- if (portalFailed) {
- return {
- description: t(
- ($) => $.create_issue.issue_limit.billing_unavailable_description,
- ),
- action: {
- label: t(($) => $.create_issue.issue_limit.billing_action),
- onClick: openBilling,
- },
- };
- }
-
- if (actions?.checkout) {
- return {
- description: t(($) => $.create_issue.issue_limit.upgrade_description),
- action: {
- label: t(($) => $.create_issue.issue_limit.upgrade_action),
- onClick: openBilling,
- },
- };
- }
+ const recovery = resolveBillingRecovery({
+ actions,
+ billingEnabled,
+ loading,
+ portalFailed,
+ });
- if (actions?.portal) {
- return {
- description: t(($) => $.create_issue.issue_limit.portal_description),
- action: {
- label: t(($) => $.create_issue.issue_limit.portal_action),
- onClick: () => {
- void openPortal();
+ switch (recovery) {
+ case "billing_disabled":
+ return {
+ description: copy.billingDisabledDescription,
+ };
+ case "checkout":
+ return {
+ description: copy.upgradeDescription,
+ action: {
+ label: copy.upgradeAction,
+ onClick: openBilling,
},
- },
- };
- }
-
- if (actions?.purchaseSeats) {
- return {
- description: t(($) => $.create_issue.issue_limit.billing_description),
- action: {
- label: t(($) => $.create_issue.issue_limit.billing_action),
- onClick: openBilling,
- },
- };
- }
-
- if (actions) {
- return {
- description: t(($) => $.create_issue.issue_limit.contact_description),
- };
- }
-
- if (loading) {
- return {
- description: t(($) => $.create_issue.issue_limit.checking_description),
- };
+ };
+ case "portal":
+ return {
+ description: copy.portalDescription,
+ action: {
+ label: copy.portalAction,
+ onClick: () => {
+ void openPortal();
+ },
+ },
+ };
+ case "billing":
+ return {
+ description: copy.billingDescription,
+ action: {
+ label: copy.billingAction,
+ onClick: openBilling,
+ },
+ };
+ case "contact_admin":
+ return {
+ description: copy.contactDescription,
+ };
+ case "checking":
+ return {
+ description: copy.checkingDescription,
+ };
+ case "billing_unavailable":
+ return {
+ description: copy.billingUnavailableDescription,
+ action: {
+ label: copy.billingAction,
+ onClick: openBilling,
+ },
+ };
}
-
- return {
- description: t(
- ($) => $.create_issue.issue_limit.billing_unavailable_description,
- ),
- action: {
- label: t(($) => $.create_issue.issue_limit.billing_action),
- onClick: openBilling,
- },
- };
}
diff --git a/packages/views/modals/use-issue-limit-upgrade-prompt.ts b/packages/views/modals/use-issue-limit-upgrade-prompt.ts
index 3dd4e4abae..44b67b64e5 100644
--- a/packages/views/modals/use-issue-limit-upgrade-prompt.ts
+++ b/packages/views/modals/use-issue-limit-upgrade-prompt.ts
@@ -2,13 +2,18 @@
import { useCallback } from "react";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useModalStore } from "@multica/core/modals";
+import {
+ useModalStore,
+ type IssueLimitRecoveryReason,
+} from "@multica/core/modals";
-/** Opens the shared issue-limit recovery dialog without closing the current draft. */
-export function useIssueLimitUpgradePrompt(): () => void {
+/** Opens the shared limit-recovery dialog without closing the current surface. */
+export function useIssueLimitUpgradePrompt(
+ reason: IssueLimitRecoveryReason = "issue_limit",
+): () => void {
const wsId = useWorkspaceId();
return useCallback(() => {
- useModalStore.getState().showIssueLimitRecovery(wsId);
- }, [wsId]);
+ useModalStore.getState().showIssueLimitRecovery(wsId, reason);
+ }, [reason, wsId]);
}
diff --git a/server/cmd/server/autopilot_failure_monitor.go b/server/cmd/server/autopilot_failure_monitor.go
index 99c18c297c..8e4883aded 100644
--- a/server/cmd/server/autopilot_failure_monitor.go
+++ b/server/cmd/server/autopilot_failure_monitor.go
@@ -279,44 +279,34 @@ func emitAutopilotPausedNotifications(
}
}
-// pausedRecipient identifies a single inbox_item recipient.
-type pausedRecipient struct {
- Type string // "member" or "agent"
- ID pgtype.UUID
-}
-
func resolveAutopilotPausedRecipients(
ctx context.Context,
queries *db.Queries,
autopilot db.Autopilot,
-) []pausedRecipient {
- if autopilot.CreatedByType == "member" {
- return []pausedRecipient{{Type: "member", ID: autopilot.CreatedByID}}
- }
-
- // Creator is an agent — find the agent's human owner so the alert lands
- // somewhere actionable. If we can't resolve a member, skip notification
- // rather than spam an agent that can't act on it.
- agent, err := queries.GetAgent(ctx, autopilot.CreatedByID)
+) []service.AutopilotNotificationRecipient {
+ recipient, ok, err := service.ResolveAutopilotNotificationRecipient(ctx, queries, autopilot)
if err != nil {
- slog.Debug("autopilot failure monitor: failed to load creator agent",
- "agent_id", util.UUIDToString(autopilot.CreatedByID),
+ slog.Debug("autopilot failure monitor: failed to resolve recipient",
+ "autopilot_id", util.UUIDToString(autopilot.ID),
"error", err,
)
return nil
}
- if !agent.OwnerID.Valid {
- return nil
+ if ok {
+ return []service.AutopilotNotificationRecipient{recipient}
}
- member, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
- UserID: agent.OwnerID,
- WorkspaceID: autopilot.WorkspaceID,
- })
+ recipients, err := service.ListWorkspaceManagerNotificationRecipients(
+ ctx, queries, autopilot.WorkspaceID,
+ )
if err != nil {
+ slog.Debug("autopilot failure monitor: failed to resolve workspace manager fallback recipients",
+ "autopilot_id", util.UUIDToString(autopilot.ID),
+ "error", err,
+ )
return nil
}
- return []pausedRecipient{{Type: "member", ID: member.UserID}}
+ return recipients
}
// autopilotEventPayload builds the minimal payload shape consumed by
diff --git a/server/cmd/server/autopilot_failure_monitor_test.go b/server/cmd/server/autopilot_failure_monitor_test.go
index 8eee7e6d72..7811c3b2ce 100644
--- a/server/cmd/server/autopilot_failure_monitor_test.go
+++ b/server/cmd/server/autopilot_failure_monitor_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"time"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/util"
@@ -229,6 +230,47 @@ func TestAutopilotFailureMonitor_AgentCreatorRoutesToOwner(t *testing.T) {
}
}
+func TestAutopilotFailureMonitor_FormerCreatorFallsBackToWorkspaceManagers(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ cfg := failureMonitorConfig{
+ Interval: time.Hour,
+ Lookback: 7 * 24 * time.Hour,
+ MinRuns: 10,
+ FailRatio: 0.9,
+ }
+ agentID := pickFixtureAgent(t)
+ autopilot := seedAutopilot(
+ t,
+ queries,
+ "Failure monitor: former member creator",
+ "member",
+ parseUUID(uuid.NewString()),
+ agentID,
+ )
+ seedAutopilotRuns(t, autopilot.ID, 11, 10, time.Now().Add(-2*time.Hour))
+ var inboxEvents []events.Event
+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) {
+ inboxEvents = append(inboxEvents, e)
+ })
+
+ tickAutopilotFailureMonitor(context.Background(), queries, bus, cfg)
+
+ if got := reloadAutopilotStatus(t, queries, autopilot.ID); got != "paused" {
+ t.Fatalf("expected paused, got %q", got)
+ }
+ if len(inboxEvents) != 1 {
+ t.Fatalf("paused fallback events = %d, want workspace owner", len(inboxEvents))
+ }
+ item := inboxEvents[0].Payload.(map[string]any)["item"].(map[string]any)
+ if got := item["recipient_id"]; got != testUserID {
+ t.Fatalf("paused fallback recipient = %s, want workspace owner %s", got, testUserID)
+ }
+ if got := item["recipient_type"]; got != "member" {
+ t.Fatalf("paused fallback recipient type = %q, want member", got)
+ }
+}
+
func TestAutopilotFailureMonitor_BelowThresholdNoOp(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index 5d14d8915d..7a104e95fa 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -17,8 +17,10 @@ instead of deployment configuration.
The client reads:
- `schema_version`: only version 1 is accepted.
-- `policy_revision`: the policy protocol generation, currently fixed at `1` by
- Cloud and not deployment configuration.
+- `policy_revision`: the effective-instruction generation, currently fixed at
+ `2` by Cloud and not deployment configuration. Cloud advances it when the
+ meaning or set of actionable instructions changes, including additive
+ instructions; `schema_version` changes only for incompatible wire parsing.
- `subscription_version`: the workspace's monotonic subscription revision. A
response that moves this revision backwards cannot replace a cached policy
while it is still usable for fresh or stale decisions. After the bounded
@@ -32,6 +34,16 @@ The client reads:
- `gates`: effective `off` or `enforce` instructions and parameters. Cloud does
not expose an `observe` rollout mode; `observe` exists only as Multica's local
downgrade of an expired cached `enforce` instruction.
+- `gates.*.notifications`: an optional, additive delivery policy. The autopilot
+ quota consumer recognizes `first_rejection_per_period` and delivers one
+ workspace notice for the first rejected execution in the Cloud-defined quota
+ period. A malformed notification policy is ignored without invalidating an
+ otherwise valid enforcement gate.
+
+Deploy Cloud policy revision 2 before the Multica consumer. The consumer treats
+a missing notification policy as notices-disabled while continuing to enforce
+the quota. The reverse order is safe because older consumers ignore the
+additive notification fields.
Responses tolerate unknown JSON fields for additive compatibility. Unknown
schema/action, malformed fields, missing gates, HTTP failures, and timeouts fail
@@ -77,5 +89,19 @@ dependency; the autopilot consumer owns its policy-neutral accounting and
recovery lifecycle separately. Cloud remains the only place that determines
the effective policy from subscription facts and authoritative limits.
+For an enforcing autopilot policy, the first rejected run in a period that
+finds at least one workspace owner or admin is delivered once to all such
+managers. With no manager the marker stays unset so a later rejection can retry;
+after a successful delivery, later rejections create no more Inbox items.
+
+Quota admission and blocked-count transactions commit before a separate Inbox
+transaction begins. Inbox inserts and notification-state parsing are therefore
+best-effort presentation side effects: failures are logged and the unmarked
+first rejection is retried later, but they cannot roll back a run, replace a
+quota error with a 500, or erase the blocked count. Issue-less Inbox items are
+published only after their own transaction commits. Stored English title/body
+remain complete fallback copy for clients and delivery channels without
+structured localization; in-app quota views localize from `details`.
+
Future consumers should depend on the small `Provider` interface. Tests can use
`server/internal/entitlement/entitlementtest.Stub` without Cloud.
diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.go
index cf5770de74..ce8fb932af 100644
--- a/server/internal/entitlement/client.go
+++ b/server/internal/entitlement/client.go
@@ -219,11 +219,16 @@ type wirePolicy struct {
}
type wireGate struct {
- Action string `json:"action"`
- Limit *int `json:"limit"`
- PeriodStart *time.Time `json:"period_start"`
- PeriodEnd *time.Time `json:"period_end"`
- ResetAt *time.Time `json:"reset_at"`
+ Action string `json:"action"`
+ Limit *int `json:"limit"`
+ PeriodStart *time.Time `json:"period_start"`
+ PeriodEnd *time.Time `json:"period_end"`
+ ResetAt *time.Time `json:"reset_at"`
+ Notifications *wireNotificationPolicy `json:"notifications"`
+}
+
+type wireNotificationPolicy struct {
+ OnRejection string `json:"on_rejection"`
}
type fetchedPolicy struct {
@@ -331,9 +336,22 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {
start, end, reset := *wire.PeriodStart, *wire.PeriodEnd, *wire.ResetAt
gate.PeriodStart, gate.PeriodEnd, gate.ResetAt = &start, &end, &reset
}
+ gate.Notifications = normalizeNotificationPolicy(wire.Notifications)
return gate, nil
}
+// Notification instructions are additive presentation policy. A malformed
+// notification object must never invalidate the enforcement gate and fail open
+// the underlying quota, so it is dropped independently.
+func normalizeNotificationPolicy(wire *wireNotificationPolicy) *NotificationPolicy {
+ if wire == nil || wire.OnRejection != NotificationFirstRejectionPerPeriod {
+ return nil
+ }
+ return &NotificationPolicy{
+ OnRejection: wire.OnRejection,
+ }
+}
+
func decisionFromEntry(entry cacheEntry, name GateName, reason Reason, stale bool) Decision {
gate := cloneGate(entry.policy.gates[name])
if stale && gate.Action == ActionEnforce {
diff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.go
index 38e6458bf0..e8c350a4c8 100644
--- a/server/internal/entitlement/client_test.go
+++ b/server/internal/entitlement/client_test.go
@@ -108,6 +108,46 @@ func TestGateCachesByWorkspaceAndClonesResults(t *testing.T) {
if autopilot.Gate.Action != ActionEnforce || calls.Load() != 1 {
t.Fatalf("autopilot = %+v, calls = %d", autopilot, calls.Load())
}
+ if autopilot.Gate.Notifications == nil ||
+ autopilot.Gate.Notifications.OnRejection != NotificationFirstRejectionPerPeriod {
+ t.Fatalf("autopilot notifications = %+v", autopilot.Gate.Notifications)
+ }
+ autopilot.Gate.Notifications.OnRejection = "mutated"
+ cloned := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)
+ if cloned.Gate.Notifications == nil ||
+ cloned.Gate.Notifications.OnRejection != NotificationFirstRejectionPerPeriod {
+ t.Fatalf("cloned notifications = %+v", cloned.Gate.Notifications)
+ }
+}
+
+func TestNotificationPolicyDoesNotControlQuotaValidity(t *testing.T) {
+ limit := 100
+ start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
+ end := start.AddDate(0, 1, 0)
+ base := wireGate{
+ Action: string(ActionEnforce), Limit: &limit,
+ PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,
+ }
+
+ valid := base
+ valid.Notifications = &wireNotificationPolicy{
+ OnRejection: NotificationFirstRejectionPerPeriod,
+ }
+ gate, err := normalizeGate(GateAutopilotRuns, valid)
+ if err != nil || gate.Notifications == nil ||
+ gate.Notifications.OnRejection != NotificationFirstRejectionPerPeriod {
+ t.Fatalf("valid notification gate = %+v, err = %v", gate, err)
+ }
+
+ malformed := base
+ malformed.Notifications = &wireNotificationPolicy{
+ OnRejection: "future_mode",
+ }
+ gate, err = normalizeGate(GateAutopilotRuns, malformed)
+ if err != nil || gate.Action != ActionEnforce || gate.Notifications != nil {
+ t.Fatalf("malformed notification gate = %+v, err = %v; want enforced quota without notices", gate, err)
+ }
+
}
func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {
@@ -586,6 +626,9 @@ func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, is
string(GateAutopilotRuns): {
Action: string(ActionEnforce), Limit: &autopilotLimit,
PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,
+ Notifications: &wireNotificationPolicy{
+ OnRejection: NotificationFirstRejectionPerPeriod,
+ },
},
},
}
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
index af59c2ec84..d1834de9fc 100644
--- a/server/internal/entitlement/types.go
+++ b/server/internal/entitlement/types.go
@@ -31,6 +31,8 @@ const (
ActionOff Action = "off"
ActionObserve Action = "observe"
ActionEnforce Action = "enforce"
+
+ NotificationFirstRejectionPerPeriod = "first_rejection_per_period"
)
type Reason string
@@ -51,11 +53,16 @@ const (
// Gate is the effective instruction for one generic enforcement point. Limits
// and period boundaries come from Cloud; this package does not derive them.
type Gate struct {
- Action Action
- Limit *int
- PeriodStart *time.Time
- PeriodEnd *time.Time
- ResetAt *time.Time
+ Action Action
+ Limit *int
+ PeriodStart *time.Time
+ PeriodEnd *time.Time
+ ResetAt *time.Time
+ Notifications *NotificationPolicy
+}
+
+type NotificationPolicy struct {
+ OnRejection string
}
// Decision carries enough source information for consumers to audit why a gate
@@ -112,5 +119,10 @@ func cloneGate(in Gate) Gate {
value := *in.ResetAt
out.ResetAt = &value
}
+ if in.Notifications != nil {
+ out.Notifications = &NotificationPolicy{
+ OnRejection: in.Notifications.OnRejection,
+ }
+ }
return out
}
diff --git a/server/internal/service/autopilot_notification_recipient.go b/server/internal/service/autopilot_notification_recipient.go
new file mode 100644
index 0000000000..41a46a1dff
--- /dev/null
+++ b/server/internal/service/autopilot_notification_recipient.go
@@ -0,0 +1,91 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// AutopilotNotificationRecipient is a human recipient of an autopilot system
+// notice.
+type AutopilotNotificationRecipient struct {
+ Type string
+ ID pgtype.UUID
+}
+
+// ListWorkspaceManagerNotificationRecipients returns the current workspace
+// owners and admins for workspace-level notices and responsibility fallbacks.
+func ListWorkspaceManagerNotificationRecipients(
+ ctx context.Context,
+ queries *db.Queries,
+ workspaceID pgtype.UUID,
+) ([]AutopilotNotificationRecipient, error) {
+ userIDs, err := queries.ListWorkspaceManagerUserIDs(ctx, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ recipients := make([]AutopilotNotificationRecipient, 0, len(userIDs))
+ for _, userID := range userIDs {
+ recipients = append(recipients, AutopilotNotificationRecipient{Type: "member", ID: userID})
+ }
+ return recipients, nil
+}
+
+// ResolveAutopilotNotificationRecipient routes a notice to the autopilot's
+// member creator, or to the owning workspace member when an agent created it.
+// A creator that no longer resolves to an actionable human returns ok=false.
+func ResolveAutopilotNotificationRecipient(
+ ctx context.Context,
+ queries *db.Queries,
+ autopilot db.Autopilot,
+) (recipient AutopilotNotificationRecipient, ok bool, err error) {
+ if autopilot.CreatedByType == "member" {
+ if !autopilot.CreatedByID.Valid {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+ member, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: autopilot.CreatedByID,
+ WorkspaceID: autopilot.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+ if err != nil {
+ return AutopilotNotificationRecipient{}, false, fmt.Errorf("load autopilot member creator: %w", err)
+ }
+ return AutopilotNotificationRecipient{
+ Type: "member",
+ ID: member.UserID,
+ }, true, nil
+ }
+ if autopilot.CreatedByType != "agent" {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+
+ agent, err := queries.GetAgent(ctx, autopilot.CreatedByID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+ if err != nil {
+ return AutopilotNotificationRecipient{}, false, fmt.Errorf("load autopilot creator agent: %w", err)
+ }
+ if !agent.OwnerID.Valid || agent.WorkspaceID.Bytes != autopilot.WorkspaceID.Bytes {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+
+ member, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: agent.OwnerID,
+ WorkspaceID: autopilot.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return AutopilotNotificationRecipient{}, false, nil
+ }
+ if err != nil {
+ return AutopilotNotificationRecipient{}, false, fmt.Errorf("load autopilot creator agent owner: %w", err)
+ }
+ return AutopilotNotificationRecipient{Type: "member", ID: member.UserID}, true, nil
+}
diff --git a/server/internal/service/autopilot_notification_recipient_test.go b/server/internal/service/autopilot_notification_recipient_test.go
new file mode 100644
index 0000000000..96d98511fc
--- /dev/null
+++ b/server/internal/service/autopilot_notification_recipient_test.go
@@ -0,0 +1,31 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/entitlement"
+)
+
+func TestResolveAutopilotNotificationRecipientRejectsFormerMember(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionOff, 1)
+ ctx := context.Background()
+ autopilot, err := fixture.queries.GetAutopilot(ctx, fixture.autopilotID)
+ if err != nil {
+ t.Fatalf("load autopilot: %v", err)
+ }
+ if _, err := fixture.pool.Exec(ctx, `
+ DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`,
+ fixture.workspaceID, fixture.publisherID,
+ ); err != nil {
+ t.Fatalf("remove autopilot creator from workspace: %v", err)
+ }
+
+ recipient, ok, err := ResolveAutopilotNotificationRecipient(ctx, fixture.queries, autopilot)
+ if err != nil {
+ t.Fatalf("resolve former member: %v", err)
+ }
+ if ok {
+ t.Fatalf("former member resolved as recipient %+v", recipient)
+ }
+}
diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.go
index 1caa43e86b..8a547989e1 100644
--- a/server/internal/service/autopilot_quota.go
+++ b/server/internal/service/autopilot_quota.go
@@ -59,6 +59,7 @@ type autopilotQuotaPolicy struct {
resetAt time.Time
policyRevision int64
subscriptionVersion int64
+ notifications *entitlement.NotificationPolicy
}
func newAutopilotIdempotencyKey() string { return uuid.NewString() }
@@ -100,6 +101,7 @@ func (s *AutopilotService) quotaPolicy(ctx context.Context, workspaceID pgtype.U
resetAt: gate.ResetAt.UTC(),
policyRevision: decision.PolicyRevision,
subscriptionVersion: decision.SubscriptionVersion,
+ notifications: gate.Notifications,
}, true
}
@@ -170,15 +172,20 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
wouldBlock := period.UsedCount+period.ReservedCount >= policy.limit
if wouldBlock && policy.action == entitlement.ActionEnforce {
- if _, err := qtx.IncrementAutopilotQuotaBlocked(ctx, db.IncrementAutopilotQuotaBlockedParams{
+ period, err = qtx.IncrementAutopilotQuotaBlocked(ctx, db.IncrementAutopilotQuotaBlockedParams{
Source: source, WorkspaceID: workspaceID,
PeriodStart: periodArgs.PeriodStart, PeriodEnd: periodArgs.PeriodEnd,
- }); err != nil {
+ })
+ if err != nil {
return db.AutopilotRun{}, false, fmt.Errorf("record blocked quota admission: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return db.AutopilotRun{}, false, fmt.Errorf("commit blocked quota admission: %w", err)
}
+ // Inbox delivery is presentation-only. It runs after the admission
+ // transaction commits so a malformed notification marker or failed insert
+ // can never turn the quota response into a 500 or roll back blocked counts.
+ s.deliverAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params)
s.recordAutopilotQuotaDecision(policy.action, source, "blocked")
return db.AutopilotRun{}, false, &AutopilotQuotaExceededError{
Used: period.UsedCount, Reserved: period.ReservedCount,
diff --git a/server/internal/service/autopilot_quota_notifications.go b/server/internal/service/autopilot_quota_notifications.go
new file mode 100644
index 0000000000..203741f2ed
--- /dev/null
+++ b/server/internal/service/autopilot_quota_notifications.go
@@ -0,0 +1,197 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strconv"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const autopilotQuotaFirstRejectionNoticeKey = "rejection_first"
+
+type autopilotQuotaNoticeFacts struct {
+ WorkspaceID pgtype.UUID
+ AutopilotID pgtype.UUID
+ Source string
+ Used int64
+ Reserved int64
+ Total int64
+ Limit int64
+ ResetAt time.Time
+}
+
+func (s *AutopilotService) deliverAutopilotQuotaRejectionNotice(
+ ctx context.Context,
+ policy autopilotQuotaPolicy,
+ workspaceID pgtype.UUID,
+ source string,
+ params db.CreateAutopilotRunParams,
+) {
+ if policy.action != entitlement.ActionEnforce || policy.notifications == nil ||
+ policy.notifications.OnRejection != entitlement.NotificationFirstRejectionPerPeriod {
+ return
+ }
+ items, err := s.createAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params)
+ if err != nil {
+ slog.Warn("autopilot quota rejection notice delivery failed; quota rejection remains committed",
+ "workspace_id", util.UUIDToString(workspaceID),
+ "autopilot_id", util.UUIDToString(params.AutopilotID),
+ "source", source,
+ "error", err,
+ )
+ return
+ }
+ s.publishAutopilotQuotaInboxItems(items)
+}
+
+func (s *AutopilotService) createAutopilotQuotaRejectionNotice(
+ ctx context.Context,
+ policy autopilotQuotaPolicy,
+ workspaceID pgtype.UUID,
+ source string,
+ params db.CreateAutopilotRunParams,
+) ([]db.InboxItem, error) {
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin quota rejection notice: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ q := s.Queries.WithTx(tx)
+ period, err := q.EnsureAutopilotQuotaPeriod(ctx, db.EnsureAutopilotQuotaPeriodParams{
+ WorkspaceID: workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},
+ })
+ if err != nil {
+ return nil, fmt.Errorf("lock quota period for rejection notice: %w", err)
+ }
+ if period.RejectionNotifiedAt.Valid {
+ if err := tx.Commit(ctx); err != nil {
+ return nil, fmt.Errorf("commit already-delivered quota rejection notice: %w", err)
+ }
+ return nil, nil
+ }
+
+ items, err := s.createAutopilotQuotaInboxItems(ctx, q, autopilotQuotaNoticeFacts{
+ WorkspaceID: period.WorkspaceID,
+ AutopilotID: params.AutopilotID,
+ Source: source,
+ Used: period.UsedCount,
+ Reserved: period.ReservedCount,
+ Total: period.UsedCount + period.ReservedCount,
+ Limit: policy.limit,
+ ResetAt: policy.resetAt,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(items) == 0 {
+ // Keep the marker unset so a later rejection can notify a newly restored
+ // workspace owner or admin instead of silencing the entire period.
+ if err := tx.Commit(ctx); err != nil {
+ return nil, fmt.Errorf("commit quota rejection notice without recipients: %w", err)
+ }
+ return nil, nil
+ }
+ if _, err := q.MarkAutopilotQuotaRejectionNotified(ctx, db.MarkAutopilotQuotaRejectionNotifiedParams{
+ WorkspaceID: period.WorkspaceID,
+ PeriodStart: period.PeriodStart,
+ PeriodEnd: period.PeriodEnd,
+ }); err != nil {
+ return nil, fmt.Errorf("mark autopilot quota rejection notified: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return nil, fmt.Errorf("commit quota rejection notice: %w", err)
+ }
+ return items, nil
+}
+
+func (s *AutopilotService) createAutopilotQuotaInboxItems(
+ ctx context.Context,
+ q *db.Queries,
+ facts autopilotQuotaNoticeFacts,
+) ([]db.InboxItem, error) {
+ autopilotTitle := ""
+ autopilot, err := q.GetAutopilot(ctx, facts.AutopilotID)
+ if err == nil {
+ autopilotTitle = autopilot.Title
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return nil, fmt.Errorf("load autopilot for quota notice: %w", err)
+ }
+ recipients, err := ListWorkspaceManagerNotificationRecipients(ctx, q, facts.WorkspaceID)
+ if err != nil {
+ return nil, fmt.Errorf("list workspace billing notification recipients: %w", err)
+ }
+ resetAt := facts.ResetAt.UTC().Format("January 2, 2006 at 15:04 UTC")
+
+ body := fmt.Sprintf(
+ "This workspace has reached its limit of %d autopilot runs for the current period. Further autopilot runs will not start until the allowance resets at %s.",
+ facts.Limit, resetAt,
+ )
+ details, err := json.Marshal(map[string]string{
+ "notice_kind": "rejected",
+ "notice_key": autopilotQuotaFirstRejectionNoticeKey,
+ "used": strconv.FormatInt(facts.Used, 10),
+ "reserved": strconv.FormatInt(facts.Reserved, 10),
+ "total": strconv.FormatInt(facts.Total, 10),
+ "limit": strconv.FormatInt(facts.Limit, 10),
+ "reset_at": facts.ResetAt.UTC().Format(time.RFC3339),
+ "source": facts.Source,
+ "autopilot_id": util.UUIDToString(facts.AutopilotID),
+ "autopilot_title": autopilotTitle,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("marshal autopilot quota inbox details: %w", err)
+ }
+
+ items := make([]db.InboxItem, 0, len(recipients))
+ for _, recipient := range recipients {
+ item, err := q.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(), WorkspaceID: facts.WorkspaceID,
+ RecipientType: recipient.Type, RecipientID: recipient.ID,
+ Type: "autopilot_quota_exceeded", Severity: "attention", IssueID: pgtype.UUID{},
+ Title: "Autopilot run 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 nil, fmt.Errorf("create autopilot quota inbox item: %w", err)
+ }
+ items = append(items, item)
+ }
+ return items, nil
+}
+
+func (s *AutopilotService) publishAutopilotQuotaInboxItems(items []db.InboxItem) {
+ if s.Bus == nil {
+ return
+ }
+ for _, item := range items {
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventInboxNew, WorkspaceID: util.UUIDToString(item.WorkspaceID),
+ ActorType: "system",
+ Payload: map[string]any{"item": map[string]any{
+ "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),
+ "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),
+ "type": item.Type, "severity": item.Severity, "issue_id": nil,
+ "issue_status": nil, "issue_priority": nil,
+ "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read,
+ "archived": item.Archived, "created_at": util.TimestampToString(item.CreatedAt),
+ "actor_type": util.TextToPtr(item.ActorType), "actor_id": nil,
+ "details": json.RawMessage(item.Details),
+ }},
+ })
+ }
+}
diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.go
index 321e05b554..8da1ca0acf 100644
--- a/server/internal/service/autopilot_quota_test.go
+++ b/server/internal/service/autopilot_quota_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/entitlement"
@@ -101,6 +102,37 @@ func (f *autopilotQuotaFixture) setPolicy(action entitlement.Action, start, end
})
}
+func (f *autopilotQuotaFixture) setNotificationPolicy(limit int) {
+ f.stub.Set(f.workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, Limit: &limit,
+ PeriodStart: &f.periodStart, PeriodEnd: &f.periodEnd, ResetAt: &f.resetAt,
+ Notifications: &entitlement.NotificationPolicy{
+ OnRejection: entitlement.NotificationFirstRejectionPerPeriod,
+ },
+ },
+ PolicyRevision: 8, SubscriptionVersion: 11,
+ })
+}
+
+func addAutopilotQuotaMember(t *testing.T, f *autopilotQuotaFixture, role string) pgtype.UUID {
+ t.Helper()
+ ctx := context.Background()
+ var userID pgtype.UUID
+ email := fmt.Sprintf("quota-notice-%s-%[email protected]", role, time.Now().UnixNano())
+ if err := f.pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Quota Notice Member', $1) RETURNING id`, email).Scan(&userID); err != nil {
+ t.Fatalf("insert quota notice 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 quota notice 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
+}
+
func TestAutopilotQuotaDisabledDoesNotReadQuotaTables(t *testing.T) {
ctx := context.Background()
workspace := uuid.New()
@@ -217,6 +249,379 @@ func TestAutopilotQuotaEnforcesBoundaryAndFinalizesIdempotently(t *testing.T) {
}
}
+func TestAutopilotQuotaFirstRejectionNotifiesBillingManagersOncePerWorkspacePeriod(t *testing.T) {
+ const attempts = 10
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 2)
+ fixture.setNotificationPolicy(2)
+ adminID := addAutopilotQuotaMember(t, fixture, "admin")
+ ordinaryMemberID := addAutopilotQuotaMember(t, fixture, "member")
+ ctx := context.Background()
+
+ for i := 1; i <= 2; i++ {
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", fmt.Sprintf("fill-quota-%d", i), fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("fill quota %d: %v", i, err)
+ }
+ }
+
+ start := make(chan struct{})
+ errs := make(chan error, attempts)
+ var wg sync.WaitGroup
+ for i := range attempts {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ params := fixture.createRunArgs
+ params.Source = "schedule"
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", fmt.Sprintf("rejection-%d", i), params,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ errs <- fmt.Errorf("rejection %d = %v, want quota error", i, err)
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Error(err)
+ }
+
+ // A different autopilot rejected later in the same billing period must not
+ // select a second set of recipients or create duplicate notices.
+ secondAutopilotID, _ := seedRunOnlyAutopilot(
+ t,
+ fixture.pool,
+ util.UUIDToString(fixture.workspaceID),
+ util.UUIDToString(fixture.agentID),
+ util.UUIDToString(ordinaryMemberID),
+ )
+ secondParams := fixture.createRunArgs
+ secondParams.AutopilotID = util.MustParseUUID(secondAutopilotID)
+ secondParams.Source = "schedule"
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", "second-autopilot-rejection", secondParams,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("second autopilot rejection = %v, want quota error", err)
+ }
+
+ rows, err := fixture.pool.Query(ctx, `
+ SELECT recipient_id FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`, fixture.workspaceID)
+ if err != nil {
+ t.Fatalf("list quota rejection recipients: %v", err)
+ }
+ defer rows.Close()
+ recipients := make(map[string]int)
+ for rows.Next() {
+ var recipientID pgtype.UUID
+ if err := rows.Scan(&recipientID); err != nil {
+ t.Fatalf("scan quota rejection recipient: %v", err)
+ }
+ recipients[util.UUIDToString(recipientID)]++
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate quota rejection recipients: %v", err)
+ }
+ wantRecipients := []pgtype.UUID{fixture.publisherID, adminID}
+ if len(recipients) != len(wantRecipients) {
+ t.Fatalf("quota rejection recipients = %v, want owner and admin", recipients)
+ }
+ for _, recipientID := range wantRecipients {
+ if got := recipients[util.UUIDToString(recipientID)]; got != 1 {
+ t.Fatalf("quota rejection recipient %s notices = %d, want one", util.UUIDToString(recipientID), got)
+ }
+ }
+ if got := recipients[util.UUIDToString(ordinaryMemberID)]; got != 0 {
+ t.Fatalf("ordinary member received %d quota rejection notices, want none", got)
+ }
+
+ period, err := fixture.queries.GetAutopilotQuotaPeriod(ctx, db.GetAutopilotQuotaPeriodParams{
+ WorkspaceID: fixture.workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: fixture.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: fixture.periodEnd, Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("load quota period: %v", err)
+ }
+ if !period.RejectionNotifiedAt.Valid {
+ t.Fatal("first rejection notification marker was not persisted")
+ }
+
+ var title, noticeKey, severity, body string
+ var hasThresholdPercent bool
+ if err := fixture.pool.QueryRow(ctx, `
+ SELECT details->>'autopilot_title', details->>'notice_key',
+ details ? 'threshold_percent', severity, body
+ FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'
+ LIMIT 1`, fixture.workspaceID,
+ ).Scan(&title, &noticeKey, &hasThresholdPercent, &severity, &body); err != nil {
+ t.Fatalf("load first rejection details: %v", err)
+ }
+ if title == "" || noticeKey != autopilotQuotaFirstRejectionNoticeKey || hasThresholdPercent {
+ t.Fatalf("first rejection details = title %q, key %q, threshold field %v", title, noticeKey, hasThresholdPercent)
+ }
+ if severity != "attention" {
+ t.Fatalf("quota rejection severity = %q, want attention", severity)
+ }
+ if strings.Contains(body, title) {
+ t.Fatalf("workspace-level quota rejection body names one autopilot: %q", body)
+ }
+ if strings.Contains(body, fixture.resetAt.UTC().Format(time.RFC3339)) ||
+ !strings.Contains(body, fixture.resetAt.UTC().Format("January 2, 2006 at 15:04 UTC")) {
+ t.Fatalf("quota rejection body reset time is not human-readable: %q", body)
+ }
+
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil {
+ t.Fatalf("quota usage: %v", err)
+ }
+ if got := usage.BlockedCounts["schedule"]; got != attempts+1 {
+ t.Fatalf("blocked schedule count = %d, want %d", got, attempts+1)
+ }
+}
+
+func TestAutopilotQuotaInboxFailurePreservesQuotaRejection(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ fixture.setNotificationPolicy(1)
+ adminID := addAutopilotQuotaMember(t, fixture, "admin")
+ ctx := context.Background()
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "inbox-failure-fill", fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("fill quota: %v", err)
+ }
+
+ suffix := strings.ReplaceAll(uuid.NewString(), "-", "")
+ functionName := pgx.Identifier{"test_fail_quota_notice_" + suffix}.Sanitize()
+ triggerName := pgx.Identifier{"test_fail_quota_notice_trigger_" + suffix}.Sanitize()
+ if _, err := fixture.pool.Exec(ctx, fmt.Sprintf(`
+ CREATE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF NEW.workspace_id = '%s'::uuid
+ AND NEW.type = 'autopilot_quota_exceeded'
+ AND NEW.recipient_id = '%s'::uuid THEN
+ RAISE EXCEPTION 'injected quota notice failure';
+ END IF;
+ RETURN NEW;
+ END;
+ $$;
+ CREATE TRIGGER %s BEFORE INSERT ON inbox_item
+ FOR EACH ROW EXECUTE FUNCTION %s();`,
+ functionName, fixture.workspace.String(), util.UUIDToString(adminID), triggerName, functionName)); err != nil {
+ t.Fatalf("install inbox failure trigger: %v", err)
+ }
+ t.Cleanup(func() {
+ fixture.pool.Exec(context.Background(), fmt.Sprintf("DROP TRIGGER IF EXISTS %s ON inbox_item", triggerName))
+ fixture.pool.Exec(context.Background(), fmt.Sprintf("DROP FUNCTION IF EXISTS %s()", functionName))
+ })
+
+ params := fixture.createRunArgs
+ params.Source = "schedule"
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", "inbox-failure-rejection", params,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("rejection error = %v, want quota exceeded despite inbox failure", err)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil {
+ t.Fatalf("quota usage: %v", err)
+ }
+ if got := usage.BlockedCounts["schedule"]; got != 1 {
+ t.Fatalf("blocked schedule count = %d, want committed count 1", got)
+ }
+ period, err := fixture.queries.GetAutopilotQuotaPeriod(ctx, db.GetAutopilotQuotaPeriodParams{
+ WorkspaceID: fixture.workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: fixture.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: fixture.periodEnd, Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("load quota period after notice failure: %v", err)
+ }
+ if period.RejectionNotifiedAt.Valid {
+ t.Fatal("failed Inbox transaction must not persist the notification marker")
+ }
+ var failedTransactionNotices int
+ if err := fixture.pool.QueryRow(ctx, `
+ SELECT count(*) FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`,
+ fixture.workspaceID,
+ ).Scan(&failedTransactionNotices); err != nil {
+ t.Fatalf("count rolled-back quota notices: %v", err)
+ }
+ if failedTransactionNotices != 0 {
+ t.Fatalf("failed multi-recipient transaction persisted %d notices, want zero", failedTransactionNotices)
+ }
+
+ if _, err := fixture.pool.Exec(ctx, fmt.Sprintf("DROP TRIGGER %s ON inbox_item", triggerName)); err != nil {
+ t.Fatalf("remove inbox failure trigger: %v", err)
+ }
+ _, _, err = fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", "inbox-failure-retry", params,
+ )
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("retry rejection error = %v, want quota exceeded", err)
+ }
+ var notices int
+ if err := fixture.pool.QueryRow(ctx, `
+ SELECT count(*) FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`,
+ fixture.workspaceID,
+ ).Scan(&notices); err != nil {
+ t.Fatalf("count retried quota notices: %v", err)
+ }
+ if notices != 2 {
+ t.Fatalf("retried quota notices = %d, want owner and admin", notices)
+ }
+}
+
+func TestAutopilotQuotaNoticeSurvivesDeletedAutopilot(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ ctx := context.Background()
+ if _, err := fixture.pool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, fixture.autopilotID); err != nil {
+ t.Fatalf("delete autopilot before quota notice: %v", err)
+ }
+
+ items, err := fixture.service.createAutopilotQuotaRejectionNotice(
+ ctx,
+ autopilotQuotaPolicy{
+ action: entitlement.ActionEnforce,
+ limit: 1,
+ periodStart: fixture.periodStart,
+ periodEnd: fixture.periodEnd,
+ resetAt: fixture.resetAt,
+ notifications: &entitlement.NotificationPolicy{
+ OnRejection: entitlement.NotificationFirstRejectionPerPeriod,
+ },
+ },
+ fixture.workspaceID,
+ "schedule",
+ fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("create quota notice after autopilot deletion: %v", err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("quota notices after autopilot deletion = %d, want workspace owner", len(items))
+ }
+ if items[0].Body.String == "" || strings.Contains(items[0].Body.String, "run-only ap") {
+ t.Fatalf("deleted-autopilot notice body = %q, want generic fallback", items[0].Body.String)
+ }
+}
+
+func TestAutopilotQuotaNoticeDoesNotDependOnCreatorAgentOwner(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 0)
+ fixture.setNotificationPolicy(0)
+ ctx := context.Background()
+ if _, err := fixture.pool.Exec(ctx, `UPDATE agent SET owner_id = NULL WHERE id = $1`, fixture.agentID); err != nil {
+ t.Fatalf("remove autopilot creator agent owner: %v", err)
+ }
+ if _, err := fixture.pool.Exec(ctx, `
+ UPDATE autopilot SET created_by_type = 'agent', created_by_id = $2 WHERE id = $1`,
+ fixture.autopilotID, fixture.agentID,
+ ); err != nil {
+ t.Fatalf("make autopilot agent-created: %v", err)
+ }
+
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", "ownerless-agent-rejection", fixture.createRunArgs,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("ownerless-agent rejection = %v, want quota error", err)
+ }
+ var recipientID pgtype.UUID
+ if err := fixture.pool.QueryRow(ctx, `
+ SELECT recipient_id FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`,
+ fixture.workspaceID,
+ ).Scan(&recipientID); err != nil {
+ t.Fatalf("load ownerless-agent quota notice: %v", err)
+ }
+ if recipientID.Bytes != fixture.publisherID.Bytes {
+ t.Fatalf("ownerless-agent notice recipient = %s, want workspace owner %s",
+ util.UUIDToString(recipientID), util.UUIDToString(fixture.publisherID))
+ }
+}
+
+func TestAutopilotQuotaNoticeRetriesAfterWorkspaceManagerIsRestored(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 0)
+ fixture.setNotificationPolicy(0)
+ ctx := context.Background()
+ if _, err := fixture.pool.Exec(ctx, `
+ UPDATE member SET role = 'member' WHERE workspace_id = $1 AND user_id = $2`,
+ fixture.workspaceID, fixture.publisherID,
+ ); err != nil {
+ t.Fatalf("remove final workspace manager role: %v", err)
+ }
+
+ assertRejected := func(key string) {
+ t.Helper()
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "schedule", key, fixture.createRunArgs,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("quota rejection %q = %v, want quota error", key, err)
+ }
+ }
+ loadPeriod := func() db.AutopilotQuotaPeriod {
+ t.Helper()
+ period, err := fixture.queries.GetAutopilotQuotaPeriod(ctx, db.GetAutopilotQuotaPeriodParams{
+ WorkspaceID: fixture.workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: fixture.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: fixture.periodEnd, Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("load quota period: %v", err)
+ }
+ return period
+ }
+ countNotices := func() int {
+ t.Helper()
+ var count int
+ if err := fixture.pool.QueryRow(ctx, `
+ SELECT count(*) FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`,
+ fixture.workspaceID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count quota notices: %v", err)
+ }
+ return count
+ }
+
+ assertRejected("no-workspace-manager")
+ if period := loadPeriod(); period.RejectionNotifiedAt.Valid {
+ t.Fatal("quota notice marker was consumed without a workspace manager")
+ }
+ if got := countNotices(); got != 0 {
+ t.Fatalf("quota notices without a workspace manager = %d, want zero", got)
+ }
+
+ if _, err := fixture.pool.Exec(ctx, `
+ UPDATE member SET role = 'owner' WHERE workspace_id = $1 AND user_id = $2`,
+ fixture.workspaceID, fixture.publisherID,
+ ); err != nil {
+ t.Fatalf("restore workspace owner: %v", err)
+ }
+ assertRejected("restored-workspace-manager")
+ if period := loadPeriod(); !period.RejectionNotifiedAt.Valid {
+ t.Fatal("quota notice marker was not persisted after manager recovery")
+ }
+ if got := countNotices(); got != 1 {
+ t.Fatalf("quota notices after manager recovery = %d, want one", got)
+ }
+}
+
func TestAutopilotQuotaConcurrentAdmissionNeverExceedsLimit(t *testing.T) {
const attempts = 25
const limit = 5
diff --git a/server/migrations/448_autopilot_quota_rejection_notified_at.down.sql b/server/migrations/448_autopilot_quota_rejection_notified_at.down.sql
new file mode 100644
index 0000000000..b3112a41db
--- /dev/null
+++ b/server/migrations/448_autopilot_quota_rejection_notified_at.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE autopilot_quota_period
+ DROP COLUMN rejection_notified_at;
diff --git a/server/migrations/448_autopilot_quota_rejection_notified_at.up.sql b/server/migrations/448_autopilot_quota_rejection_notified_at.up.sql
new file mode 100644
index 0000000000..21a6160c75
--- /dev/null
+++ b/server/migrations/448_autopilot_quota_rejection_notified_at.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE autopilot_quota_period
+ ADD COLUMN rejection_notified_at TIMESTAMPTZ;
diff --git a/server/pkg/db/generated/autopilot_quota.sql.go b/server/pkg/db/generated/autopilot_quota.sql.go
index 3d59b1e82d..70dcea6616 100644
--- a/server/pkg/db/generated/autopilot_quota.sql.go
+++ b/server/pkg/db/generated/autopilot_quota.sql.go
@@ -37,7 +37,7 @@ FROM changed
WHERE p.workspace_id = changed.workspace_id
AND p.period_start = changed.period_start
AND p.period_end = changed.period_end
-RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at
`
// used_count is monotonic within a period: consuming a reserved slot is the
@@ -54,6 +54,7 @@ func (q *Queries) ConsumeAutopilotQuotaReservation(ctx context.Context, reservat
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
@@ -108,7 +109,7 @@ INSERT INTO autopilot_quota_period (workspace_id, period_start, period_end)
VALUES ($1, $2, $3)
ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE
SET updated_at = autopilot_quota_period.updated_at
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
`
type EnsureAutopilotQuotaPeriodParams struct {
@@ -131,12 +132,13 @@ func (q *Queries) EnsureAutopilotQuotaPeriod(ctx context.Context, arg EnsureAuto
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
const getAutopilotQuotaPeriod = `-- name: GetAutopilotQuotaPeriod :one
-SELECT workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at FROM autopilot_quota_period
+SELECT workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at FROM autopilot_quota_period
WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
`
@@ -158,6 +160,7 @@ func (q *Queries) GetAutopilotQuotaPeriod(ctx context.Context, arg GetAutopilotQ
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
@@ -214,7 +217,7 @@ SET blocked_counts = jsonb_set(
WHERE workspace_id = $2
AND period_start = $3
AND period_end = $4
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
`
type IncrementAutopilotQuotaBlockedParams struct {
@@ -241,6 +244,7 @@ func (q *Queries) IncrementAutopilotQuotaBlocked(ctx context.Context, arg Increm
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
@@ -250,7 +254,7 @@ UPDATE autopilot_quota_period
SET reserved_count = reserved_count + 1,
updated_at = now()
WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
`
type IncrementAutopilotQuotaReservedParams struct {
@@ -271,6 +275,7 @@ func (q *Queries) IncrementAutopilotQuotaReserved(ctx context.Context, arg Incre
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
@@ -346,6 +351,39 @@ func (q *Queries) ListRecoverableAutopilotQuotaReservations(ctx context.Context,
return items, nil
}
+const markAutopilotQuotaRejectionNotified = `-- name: MarkAutopilotQuotaRejectionNotified :one
+UPDATE autopilot_quota_period
+SET rejection_notified_at = COALESCE(rejection_notified_at, now()),
+ updated_at = now()
+WHERE workspace_id = $1
+ AND period_start = $2
+ AND period_end = $3
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
+`
+
+type MarkAutopilotQuotaRejectionNotifiedParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+func (q *Queries) MarkAutopilotQuotaRejectionNotified(ctx context.Context, arg MarkAutopilotQuotaRejectionNotifiedParams) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, markAutopilotQuotaRejectionNotified, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.RejectionNotifiedAt,
+ )
+ return i, err
+}
+
const releaseAutopilotQuotaReservation = `-- name: ReleaseAutopilotQuotaReservation :one
WITH locked AS (
SELECT qr.id, qr.workspace_id, qr.period_start, qr.period_end, qr.policy_revision, qr.subscription_version, qr.source, qr.idempotency_key, qr.state, qr.created_at, qr.finalized_at FROM autopilot_quota_reservation qr
@@ -371,7 +409,7 @@ FROM changed
WHERE p.workspace_id = changed.workspace_id
AND p.period_start = changed.period_start
AND p.period_end = changed.period_end
-RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at
`
// Release is intentionally limited to still-reserved work. A consumed
@@ -388,6 +426,7 @@ func (q *Queries) ReleaseAutopilotQuotaReservation(ctx context.Context, reservat
&i.BlockedCounts,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.RejectionNotifiedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/member.sql.go b/server/pkg/db/generated/member.sql.go
index ee18f5e15a..8f13d782cd 100644
--- a/server/pkg/db/generated/member.sql.go
+++ b/server/pkg/db/generated/member.sql.go
@@ -167,6 +167,32 @@ func (q *Queries) ListMembersWithUser(ctx context.Context, workspaceID pgtype.UU
return items, nil
}
+const listWorkspaceManagerUserIDs = `-- name: ListWorkspaceManagerUserIDs :many
+SELECT user_id FROM member
+WHERE workspace_id = $1 AND role IN ('owner', 'admin')
+ORDER BY created_at ASC
+`
+
+func (q *Queries) ListWorkspaceManagerUserIDs(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listWorkspaceManagerUserIDs, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var user_id pgtype.UUID
+ if err := rows.Scan(&user_id); err != nil {
+ return nil, err
+ }
+ items = append(items, user_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const updateMemberRole = `-- name: UpdateMemberRole :one
UPDATE member SET role = $2
WHERE id = $1
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a3ec697ddf..697e258ca2 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -226,14 +226,15 @@ type AutopilotCollaborator struct {
}
type AutopilotQuotaPeriod struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- PeriodStart pgtype.Timestamptz `json:"period_start"`
- PeriodEnd pgtype.Timestamptz `json:"period_end"`
- UsedCount int64 `json:"used_count"`
- ReservedCount int64 `json:"reserved_count"`
- BlockedCounts []byte `json:"blocked_counts"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ UsedCount int64 `json:"used_count"`
+ ReservedCount int64 `json:"reserved_count"`
+ BlockedCounts []byte `json:"blocked_counts"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RejectionNotifiedAt pgtype.Timestamptz `json:"rejection_notified_at"`
}
type AutopilotQuotaReservation struct {
diff --git a/server/pkg/db/queries/autopilot_quota.sql b/server/pkg/db/queries/autopilot_quota.sql
index 30f45d2954..783d32c0e9 100644
--- a/server/pkg/db/queries/autopilot_quota.sql
+++ b/server/pkg/db/queries/autopilot_quota.sql
@@ -47,6 +47,15 @@ WHERE workspace_id = @workspace_id
AND period_end = @period_end
RETURNING *;
+-- name: MarkAutopilotQuotaRejectionNotified :one
+UPDATE autopilot_quota_period
+SET rejection_notified_at = COALESCE(rejection_notified_at, now()),
+ updated_at = now()
+WHERE workspace_id = @workspace_id
+ AND period_start = @period_start
+ AND period_end = @period_end
+RETURNING *;
+
-- name: ConsumeAutopilotQuotaReservation :one
-- used_count is monotonic within a period: consuming a reserved slot is the
-- only write that changes it, and no release path decrements it.
diff --git a/server/pkg/db/queries/member.sql b/server/pkg/db/queries/member.sql
index f93365d3b3..74e1dc70ab 100644
--- a/server/pkg/db/queries/member.sql
+++ b/server/pkg/db/queries/member.sql
@@ -3,6 +3,11 @@ SELECT * FROM member
WHERE workspace_id = $1
ORDER BY created_at ASC;
+-- name: ListWorkspaceManagerUserIDs :many
+SELECT user_id FROM member
+WHERE workspace_id = $1 AND role IN ('owner', 'admin')
+ORDER BY created_at ASC;
+
-- name: GetMember :one
SELECT * FROM member
WHERE id = $1;