Skip to content

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

Go

fix(billing): prompt upgrade before quick create (MUL-6746) (#7625)

LinYushend13e76a557e9
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 299b37be32..94be394836 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -1,6 +1,7 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { toast } from "sonner";
+import { ApiError } from "@multica/core/api";
import type { InboxItem } from "@multica/core/types";
import { useInboxFilterStore } from "@multica/core/inbox/filter-store";
import { InboxPage } from "./inbox-page";
@@ -67,6 +68,11 @@ const markUnreadMutate = vi.fn();
const archiveMutate = vi.fn();
const unarchiveMutate = vi.fn();
const retrySourceContextMutateAsync = vi.fn();
+const showIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());
+
+vi.mock("../../modals/use-issue-limit-upgrade-prompt", () => ({
+ useIssueLimitUpgradePrompt: () => showIssueLimitUpgradePrompt,
+}));
vi.mock("@multica/core/inbox/mutations", () => {
const mutation = () => ({ mutate: vi.fn() });
@@ -220,6 +226,7 @@ function reset() {
unarchiveMutate.mockClear();
retrySourceContextMutateAsync.mockReset();
retrySourceContextMutateAsync.mockResolvedValue({});
+ showIssueLimitUpgradePrompt.mockClear();
modalState.modal = null;
vi.mocked(toast.success).mockClear();
vi.mocked(toast.error).mockClear();
@@ -476,6 +483,38 @@ describe("InboxPage", () => {
expect(toast.success).toHaveBeenCalledTimes(1);
});
+ it("shows issue-limit recovery when a source-context retry is rejected", async () => {
+ reset();
+ retrySourceContextMutateAsync.mockRejectedValue(
+ new ApiError(
+ "workspace has reached its issue limit",
+ 402,
+ "Payment Required",
+ { code: "issue_limit_reached" },
+ ),
+ );
+ listData.active = [
+ item({
+ id: "source-context-limit",
+ issue_id: null,
+ type: "quick_create_failed",
+ details: {
+ task_id: "task-1",
+ source_context_id: "context-1",
+ original_prompt: "make a child",
+ },
+ }),
+ ];
+
+ render(<InboxPage />);
+ fireEvent.click(screen.getByTestId("row"));
+ fireEvent.click(screen.getByTestId("retry-source-context"));
+
+ await act(async () => undefined);
+ expect(showIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
it("marks the opened notification read", () => {
reset();
listData.active = [
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index ca99c7855e..2ec53e6f34 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -96,9 +96,11 @@ import {
resolveDetailItem,
} from "./inbox-display";
import { useT } from "../../i18n";
+import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";
export function InboxPage() {
const { t } = useT("inbox");
+ const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();
const { searchParams, replace } = useNavigation();
const urlIssue = searchParams.get("issue") ?? "";
const urlView: InboxView =
@@ -736,6 +738,13 @@ export function InboxPage() {
await retrySourceContextMutation.mutateAsync(detailItem.details!.task_id!);
toast.success(t(($) => $.toasts.source_context_retry_started));
} catch (error) {
+ if (
+ error instanceof ApiError &&
+ errorCode(error) === "issue_limit_reached"
+ ) {
+ showIssueLimitUpgradePrompt();
+ return;
+ }
toast.error(
error instanceof ApiError &&
errorCode(error) === "source_context_retry_unavailable"
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index 3f28978448..b2636248e7 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -159,7 +159,19 @@
"toast_failed": "Failed to create issue",
"toast_duplicate_title": "Duplicate issue",
"toast_duplicate_view": "View existing issue",
- "toast_issue_limit_reached": "This workspace has reached its issue limit",
+ "issue_limit": {
+ "title": "This workspace has reached its issue limit",
+ "checking_description": "Checking the billing actions available for this workspace…",
+ "upgrade_description": "Upgrade to Pro to keep creating issues.",
+ "portal_description": "Open Billing Portal to manage this workspace's subscription and restore issue creation.",
+ "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": "Delete an existing issue to free space, 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/modals.json b/packages/views/locales/ja/modals.json
index 834e4e7c3e..f541903dde 100644
--- a/packages/views/locales/ja/modals.json
+++ b/packages/views/locales/ja/modals.json
@@ -157,7 +157,19 @@
"toast_failed": "タスクを作成できませんでした",
"toast_duplicate_title": "重複タスク",
"toast_duplicate_view": "既存のタスクを表示",
- "toast_issue_limit_reached": "このワークスペースはタスク数の上限に達しました",
+ "issue_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/modals.json b/packages/views/locales/ko/modals.json
index ab079cfd4f..57291b125f 100644
--- a/packages/views/locales/ko/modals.json
+++ b/packages/views/locales/ko/modals.json
@@ -157,7 +157,19 @@
"toast_failed": "태스크를 만들지 못했습니다",
"toast_duplicate_title": "중복 태스크",
"toast_duplicate_view": "기존 태스크 보기",
- "toast_issue_limit_reached": "이 워크스페이스가 태스크 수 한도에 도달했습니다",
+ "issue_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/modals.json b/packages/views/locales/zh-Hans/modals.json
index 7d92da51cb..70a31d2b5d 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -157,7 +157,19 @@
"toast_failed": "创建任务失败",
"toast_duplicate_title": "已存在同名任务",
"toast_duplicate_view": "查看已有任务",
- "toast_issue_limit_reached": "该工作区的任务总数已达到上限",
+ "issue_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/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index bc1a5cedbb..55a5171e91 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -46,6 +46,7 @@ const mockSetKeepOpen = vi.hoisted(() => vi.fn());
const mockToastCustom = vi.hoisted(() => vi.fn());
const mockToastDismiss = vi.hoisted(() => vi.fn());
const mockToastError = vi.hoisted(() => vi.fn());
+const mockShowIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());
// Uploads flow through the module-level coordinator, which calls
// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2). Tests drive uploads by
// mocking that call; it resolves a plain server Attachment row.
@@ -203,6 +204,10 @@ vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-test",
}));
+vi.mock("./use-issue-limit-upgrade-prompt", () => ({
+ useIssueLimitUpgradePrompt: () => mockShowIssueLimitUpgradePrompt,
+}));
+
vi.mock("@multica/core/issues/queries", () => ({
issueDetailOptions: (wsId: string, id: string) => ({
queryKey: ["issues", wsId, "detail", id],
@@ -1145,6 +1150,29 @@ describe("CreateIssueModal", () => {
expect(mockToastCustom).not.toHaveBeenCalled();
});
+ it("offers the Cloud-authorized upgrade recovery when manual create reaches the issue limit", async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ mockCreateIssue.mockRejectedValue(
+ new ApiError("workspace has reached its issue limit", 402, "Payment Required", {
+ code: "issue_limit_reached",
+ limit: 1000,
+ policy_revision: 1,
+ }),
+ );
+
+ renderModal(<CreateIssueModal onClose={onClose} />);
+ await user.type(screen.getByPlaceholderText("Issue title"), "One more issue");
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+
+ await waitFor(() => {
+ expect(mockShowIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);
+ });
+ expect(mockToastError).not.toHaveBeenCalled();
+ expect(mockClearDraft).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
// Non-409 errors with a real message: surface the backend reason rather
// than the generic i18n fallback. This is the whole point of the issue.
it("surfaces err.message verbatim for non-duplicate errors", async () => {
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 1f04e4f1a9..060d0a394e 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -98,6 +98,7 @@ import {
import { IssuePickerModal } from "./issue-picker-modal";
import { useT } from "../i18n";
import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";
+import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";
// ---------------------------------------------------------------------------
// ManualCreatePanel — manual-mode body of the create-issue dialog. Renders
@@ -232,6 +233,9 @@ export function ManualCreatePanel({
: undefined;
const onSourceContextExpandedChange = data?.source_context_on_expanded_change as ((expanded: boolean) => void) | undefined;
const sourceContextFailureMessage = useSourceContextFailureMessage();
+ const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt({
+ onNavigate: onClose,
+ });
const draft = useIssueDraftStore((s) => s.draft);
const setManual = useIssueDraftStore((s) => s.setManual);
@@ -677,7 +681,7 @@ export function ManualCreatePanel({
return false;
}
if (sourceCode === "issue_limit_reached") {
- toast.error(t(($) => $.create_issue.toast_issue_limit_reached));
+ showIssueLimitUpgradePrompt();
return false;
}
// Duplicate-issue is the only structured 409 the create endpoint
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 7e4cef71db..0d4dd3f1d8 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -18,6 +18,7 @@ const mockSetQuickCreateFieldVisible = vi.hoisted(() => vi.fn());
const mockSetKeepOpen = vi.hoisted(() => vi.fn());
const mockSetLastMode = vi.hoisted(() => vi.fn());
const mockToastSuccess = vi.hoisted(() => vi.fn());
+const mockShowIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());
// Uploads flow through the module-level coordinator, which calls
// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2).
const mockApiUploadFile = vi.hoisted(() => vi.fn());
@@ -154,21 +155,39 @@ vi.mock("@tanstack/react-query", () => ({
},
}));
+const { ApiError } = vi.hoisted(() => {
+ class ApiErrorImpl extends Error {
+ readonly status: number;
+ readonly statusText: string;
+ readonly body?: unknown;
+ constructor(message: string, status: number, statusText: string, body?: unknown) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.statusText = statusText;
+ this.body = body;
+ }
+ }
+ return { ApiError: ApiErrorImpl };
+});
+
vi.mock("@multica/core/api", () => ({
api: {
createCommentSubIssue: mockCreateCommentSubIssue,
quickCreateIssue: mockQuickCreateIssue,
uploadFile: mockApiUploadFile,
},
- ApiError: class ApiError extends Error {
- body?: unknown;
- },
+ ApiError,
}));
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-test",
}));
+vi.mock("./use-issue-limit-upgrade-prompt", () => ({
+ useIssueLimitUpgradePrompt: () => mockShowIssueLimitUpgradePrompt,
+}));
+
vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => ({ name: "Test Workspace" }),
useWorkspacePaths: () => ({
@@ -610,6 +629,28 @@ describe("AgentCreatePanel", () => {
expect(onClose).toHaveBeenCalled();
});
+ it("shows the upgrade recovery immediately when quick create is rejected by the issue preflight", async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ mockQuickCreateIssue.mockRejectedValue(
+ new ApiError("workspace has reached its issue limit", 402, "Payment Required", {
+ code: "issue_limit_reached",
+ limit: 1000,
+ policy_revision: 1,
+ }),
+ );
+
+ renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });
+ await user.click(screen.getByRole("button", { name: /^Create$/i }));
+
+ await waitFor(() => {
+ expect(mockShowIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);
+ });
+ expect(mockToastSuccess).not.toHaveBeenCalled();
+ expect(mockClearDraft).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
it("reveals optional fields from the overflow and submits their values", async () => {
const user = userEvent.setup();
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index c42d4f5c2b..eccf5bbfbe 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -84,6 +84,7 @@ import { FileUploadButton } from "@multica/ui/components/common/file-upload-butt
import { useT } from "../i18n";
import { matchesPinyin } from "../editor/extensions/pinyin-match";
import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";
+import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";
type ActorSelection =
| { type: "agent"; id: string }
@@ -135,6 +136,9 @@ export function AgentCreatePanel({
: undefined;
const onSourceContextExpandedChange = data?.source_context_on_expanded_change as ((expanded: boolean) => void) | undefined;
const sourceContextFailureMessage = useSourceContextFailureMessage();
+ const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt({
+ onNavigate: onClose,
+ });
const userId = useAuthStore((s) => s.user?.id);
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
@@ -465,6 +469,10 @@ export function AgentCreatePanel({
current_version?: string;
min_version?: string;
};
+ if (body.code === "issue_limit_reached") {
+ showIssueLimitUpgradePrompt();
+ return false;
+ }
if (body.code === "agent_unavailable") {
setError(body.reason || t(($) => $.create_issue.agent.error_agent_unavailable_fallback));
return false;
diff --git a/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx b/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx
new file mode 100644
index 0000000000..24655fe3aa
--- /dev/null
+++ b/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx
@@ -0,0 +1,274 @@
+import type { ReactNode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../locales/en/common.json";
+import enModals from "../locales/en/modals.json";
+
+interface AvailableActions {
+ checkout: boolean;
+ portal: boolean;
+ purchaseSeats: boolean;
+}
+
+const mockPush = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+const mockToastDismiss = vi.hoisted(() => vi.fn());
+const mockCreatePortal = vi.hoisted(() => vi.fn());
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+const mockSummaryQuery = vi.hoisted(() => vi.fn());
+const featureState = vi.hoisted(() => ({ billingEnabled: true }));
+const summaryState = vi.hoisted(() => ({
+ value: null as null | { availableActions: AvailableActions },
+ error: null as Error | null,
+ pending: null as Promise<{ availableActions: AvailableActions } | null> | null,
+}));
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-test",
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ settings: () => "/ws-test/settings",
+ }),
+}));
+
+vi.mock("@multica/core/config", () => ({
+ useFeatureEnabled: () => featureState.billingEnabled,
+}));
+
+vi.mock("../navigation/context", () => ({
+ useNavigation: () => ({ push: mockPush }),
+}));
+
+vi.mock("../platform", () => ({
+ openExternal: mockOpenExternal,
+}));
+
+vi.mock("@multica/core/billing", () => ({
+ workspaceSubscriptionSummaryOptions: (wsId: string) => ({
+ queryKey: ["workspace-subscriptions", wsId, "summary"],
+ queryFn: mockSummaryQuery,
+ }),
+ useCreateWorkspaceSubscriptionPortal: () => ({
+ mutateAsync: mockCreatePortal,
+ }),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ error: mockToastError,
+ dismiss: mockToastDismiss,
+ },
+}));
+
+import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";
+
+const TEST_RESOURCES = {
+ en: { common: enCommon, modals: enModals },
+};
+
+const actions = (
+ overrides: Partial<AvailableActions> = {},
+): AvailableActions => ({
+ checkout: false,
+ portal: false,
+ purchaseSeats: false,
+ ...overrides,
+});
+
+function renderPrompt(onNavigate = vi.fn()) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: 1 } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ </I18nProvider>
+ );
+ const hook = renderHook(
+ () => useIssueLimitUpgradePrompt({ onNavigate }),
+ { wrapper },
+ );
+ return { ...hook, client, onNavigate };
+}
+
+function latestToastOptions() {
+ return mockToastError.mock.calls.at(-1)?.[1];
+}
+
+describe("useIssueLimitUpgradePrompt", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ featureState.billingEnabled = true;
+ summaryState.value = null;
+ summaryState.error = null;
+ summaryState.pending = null;
+ mockSummaryQuery.mockImplementation(async () => {
+ if (summaryState.pending) return summaryState.pending;
+ if (summaryState.error) throw summaryState.error;
+ return summaryState.value;
+ });
+ mockCreatePortal.mockResolvedValue({
+ url: "https://billing.example/portal",
+ });
+ });
+
+ it("shows a persistent recovery surface immediately while Cloud is pending", async () => {
+ let resolveSummary!: (
+ value: { availableActions: AvailableActions } | null,
+ ) => void;
+ summaryState.pending = new Promise((resolve) => {
+ resolveSummary = resolve;
+ });
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+
+ expect(mockToastError).toHaveBeenCalledWith(
+ "This workspace has reached its issue limit",
+ expect.objectContaining({
+ description: "Checking the billing actions available for this workspace…",
+ duration: Infinity,
+ closeButton: true,
+ onDismiss: expect.any(Function),
+ onAutoClose: expect.any(Function),
+ }),
+ );
+
+ await act(async () => {
+ resolveSummary({ availableActions: actions({ checkout: true }) });
+ await summaryState.pending;
+ });
+ await waitFor(() =>
+ expect(latestToastOptions()?.action?.label).toBe("Upgrade to Pro"),
+ );
+ });
+
+ it("does not restore the prompt after it is manually dismissed", async () => {
+ let resolveSummary!: (
+ value: { availableActions: AvailableActions } | null,
+ ) => void;
+ summaryState.pending = new Promise((resolve) => {
+ resolveSummary = resolve;
+ });
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+ act(() => latestToastOptions()?.onDismiss?.());
+
+ await act(async () => {
+ resolveSummary({ availableActions: actions({ checkout: true }) });
+ await summaryState.pending;
+ await Promise.resolve();
+ });
+
+ expect(mockToastError).toHaveBeenCalledTimes(1);
+ });
+
+ it("offers Upgrade to Pro only when Cloud authorizes checkout", async () => {
+ summaryState.value = {
+ availableActions: actions({ checkout: true }),
+ };
+ const { result, onNavigate } = renderPrompt();
+
+ act(() => result.current());
+ await waitFor(() =>
+ expect(latestToastOptions()?.action?.label).toBe("Upgrade to Pro"),
+ );
+
+ latestToastOptions()?.action?.onClick();
+ expect(mockToastDismiss).toHaveBeenCalledWith(
+ "issue-limit-recovery:ws-test",
+ );
+ expect(onNavigate).toHaveBeenCalledTimes(1);
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/settings?tab=billing");
+ });
+
+ it("opens Billing Portal for a past-due manager authorized for portal", async () => {
+ summaryState.value = {
+ availableActions: actions({ portal: true }),
+ };
+ const { result, onNavigate } = renderPrompt();
+
+ act(() => result.current());
+ await waitFor(() =>
+ expect(latestToastOptions()?.action?.label).toBe("Open Billing Portal"),
+ );
+
+ await act(async () => {
+ latestToastOptions()?.action?.onClick();
+ });
+ await waitFor(() => expect(mockCreatePortal).toHaveBeenCalledTimes(1));
+ expect(mockCreatePortal.mock.calls[0]?.[0]).toMatch(
+ /^issue-limit-portal-ws-test-/,
+ );
+ expect(mockToastDismiss).toHaveBeenCalledWith(
+ "issue-limit-recovery:ws-test",
+ );
+ expect(onNavigate).toHaveBeenCalledTimes(1);
+ expect(mockOpenExternal).toHaveBeenCalledWith(
+ "https://billing.example/portal",
+ { webTarget: "same-tab" },
+ );
+ });
+
+ it("asks for an administrator only when Cloud authorizes no management action", async () => {
+ summaryState.value = { availableActions: actions() };
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+ await waitFor(() =>
+ expect(latestToastOptions()?.description).toBe(
+ "Ask a workspace owner or admin to upgrade to Pro.",
+ ),
+ );
+ expect(latestToastOptions()).not.toHaveProperty("action");
+ });
+
+ it("keeps another Cloud-authorized management action reachable in Billing", async () => {
+ summaryState.value = {
+ availableActions: actions({ purchaseSeats: true }),
+ };
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+ await waitFor(() =>
+ expect(latestToastOptions()?.action?.label).toBe("View Billing"),
+ );
+ });
+
+ it("uses one background attempt and keeps Billing as the recovery path", async () => {
+ summaryState.error = new Error("cloud unavailable");
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+ expect(latestToastOptions()?.description).toBe(
+ "Checking the billing actions available for this workspace…",
+ );
+ await waitFor(() =>
+ expect(latestToastOptions()?.action?.label).toBe("View Billing"),
+ );
+ expect(mockSummaryQuery).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not expose a dead Billing link when the Billing surface is disabled", () => {
+ featureState.billingEnabled = false;
+ const { result } = renderPrompt();
+
+ act(() => result.current());
+
+ expect(latestToastOptions()).toEqual(
+ expect.objectContaining({
+ description:
+ "Delete an existing issue to free space, or contact your workspace administrator.",
+ duration: Infinity,
+ closeButton: true,
+ }),
+ );
+ expect(latestToastOptions()).not.toHaveProperty("action");
+ expect(mockSummaryQuery).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/modals/use-issue-limit-upgrade-prompt.ts b/packages/views/modals/use-issue-limit-upgrade-prompt.ts
new file mode 100644
index 0000000000..2c56c82c1f
--- /dev/null
+++ b/packages/views/modals/use-issue-limit-upgrade-prompt.ts
@@ -0,0 +1,212 @@
+"use client";
+
+import { useCallback, useRef } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ useCreateWorkspaceSubscriptionPortal,
+ workspaceSubscriptionSummaryOptions,
+} from "@multica/core/billing";
+import { useFeatureEnabled } from "@multica/core/config";
+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { WorkspaceSubscriptionSummary } from "@multica/core/types";
+import { useT } from "../i18n";
+import { useNavigation } from "../navigation";
+import { openExternal } from "../platform";
+
+interface IssueLimitUpgradePromptOptions {
+ onNavigate?: () => void;
+}
+
+type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
+
+function createPortalIdempotencyKey(wsId: string): string {
+ const suffix =
+ globalThis.crypto?.randomUUID?.() ??
+ `${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ return `issue-limit-portal-${wsId}-${suffix}`.slice(0, 255);
+}
+
+/**
+ * Immediately shows a persistent issue-limit recovery surface, then enriches
+ * it with the complete action set authorized by Cloud for the current caller.
+ * No local role, plan, subscription, or quota inference controls an action.
+ */
+export function useIssueLimitUpgradePrompt(
+ options: IssueLimitUpgradePromptOptions = {},
+): () => void {
+ const { onNavigate } = options;
+ const { t } = useT("modals");
+ const queryClient = useQueryClient();
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const billingEnabled = useFeatureEnabled(
+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
+ false,
+ );
+ const createPortal = useCreateWorkspaceSubscriptionPortal(wsId).mutateAsync;
+ const portalIntentKeyRef = useRef<string | null>(null);
+ const dismissedRef = useRef(false);
+
+ return useCallback(() => {
+ dismissedRef.current = false;
+ const toastId = `issue-limit-recovery:${wsId}`;
+ const title = t(($) => $.create_issue.issue_limit.title);
+ const markDismissed = () => {
+ dismissedRef.current = true;
+ };
+ const persistentOptions = {
+ id: toastId,
+ duration: Infinity,
+ closeButton: true,
+ onDismiss: markDismissed,
+ onAutoClose: markDismissed,
+ };
+ const dismissPrompt = () => {
+ markDismissed();
+ toast.dismiss(toastId);
+ };
+ const openBilling = () => {
+ dismissPrompt();
+ onNavigate?.();
+ navigation.push(`${paths.settings()}?tab=billing`);
+ };
+ const showBillingFallback = () => {
+ if (dismissedRef.current) return;
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(
+ ($) => $.create_issue.issue_limit.billing_unavailable_description,
+ ),
+ action: {
+ label: t(($) => $.create_issue.issue_limit.billing_action),
+ onClick: openBilling,
+ },
+ });
+ };
+ const openPortal = async () => {
+ const key =
+ portalIntentKeyRef.current ?? createPortalIdempotencyKey(wsId);
+ portalIntentKeyRef.current = key;
+ try {
+ const response = await createPortal(key);
+ if (!response?.url) {
+ showBillingFallback();
+ return;
+ }
+ portalIntentKeyRef.current = null;
+ dismissPrompt();
+ onNavigate?.();
+ openExternal(response.url, { webTarget: "same-tab" });
+ } catch {
+ showBillingFallback();
+ }
+ };
+ const showAuthorizedActions = (actions: BillingActions) => {
+ if (dismissedRef.current) return;
+ if (actions.checkout) {
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(
+ ($) => $.create_issue.issue_limit.upgrade_description,
+ ),
+ action: {
+ label: t(($) => $.create_issue.issue_limit.upgrade_action),
+ onClick: openBilling,
+ },
+ });
+ return;
+ }
+
+ if (actions.portal) {
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(($) => $.create_issue.issue_limit.portal_description),
+ action: {
+ label: t(($) => $.create_issue.issue_limit.portal_action),
+ onClick: () => {
+ void openPortal();
+ },
+ },
+ });
+ return;
+ }
+
+ if (actions.purchaseSeats) {
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(
+ ($) => $.create_issue.issue_limit.billing_description,
+ ),
+ action: {
+ label: t(($) => $.create_issue.issue_limit.billing_action),
+ onClick: openBilling,
+ },
+ });
+ return;
+ }
+
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(($) => $.create_issue.issue_limit.contact_description),
+ });
+ };
+
+ if (!billingEnabled) {
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(
+ ($) => $.create_issue.issue_limit.billing_disabled_description,
+ ),
+ });
+ return;
+ }
+
+ const summaryOptions = workspaceSubscriptionSummaryOptions(wsId);
+ const cachedSummary = queryClient.getQueryData<
+ WorkspaceSubscriptionSummary | null
+ >(summaryOptions.queryKey);
+ if (cachedSummary) {
+ showAuthorizedActions(cachedSummary.availableActions);
+ } else {
+ toast.error(title, {
+ ...persistentOptions,
+ description: t(
+ ($) => $.create_issue.issue_limit.checking_description,
+ ),
+ });
+ }
+
+ // A quota rejection is a strong signal that cached billing state may be
+ // stale. Refresh once in the background; the recovery surface above never
+ // waits for Cloud or inherits the application's retry budget.
+ void queryClient
+ .fetchQuery({
+ ...summaryOptions,
+ staleTime: 0,
+ retry: false,
+ })
+ .then((summary) => {
+ if (summary) {
+ showAuthorizedActions(summary.availableActions);
+ } else if (!cachedSummary) {
+ showBillingFallback();
+ }
+ })
+ .catch(() => {
+ if (!cachedSummary) showBillingFallback();
+ });
+ }, [
+ billingEnabled,
+ createPortal,
+ navigation,
+ onNavigate,
+ paths,
+ queryClient,
+ t,
+ wsId,
+ ]);
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 79cf90b67f..f1ca5febff 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -429,6 +429,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
opts.BusinessMetrics.RecordEntitlementConfigError()
} else if entitlementClient.Enabled() {
h.Entitlements = entitlementClient
+ h.TaskService.Entitlements = entitlementClient
h.IssueService.Entitlements = entitlementClient
h.AutopilotService.Entitlements = entitlementClient
h.AutopilotService.QuotaMetrics = opts.BusinessMetrics
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 82abf95cdf..36fbd36605 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -59,6 +59,8 @@ type mockStorage struct {
files map[string][]byte
presignCalls []string
presignDispositions []string
+ getReaderCalls int
+ uploadStreamCalls int
}
func (m *mockStorage) Upload(_ context.Context, key string, data []byte, _ string, _ string) (string, error) {
@@ -72,6 +74,9 @@ func (m *mockStorage) Upload(_ context.Context, key string, data []byte, _ strin
}
func (m *mockStorage) UploadStream(ctx context.Context, key string, reader io.Reader, _ int64, contentType string, filename string) (string, error) {
+ m.mu.Lock()
+ m.uploadStreamCalls++
+ m.mu.Unlock()
data, err := io.ReadAll(reader)
if err != nil {
return "", err
@@ -117,11 +122,17 @@ func (m *mockStorageNoCdn) CdnDomain() string { return "" }
func (m *mockStorage) GetReader(_ context.Context, key string) (io.ReadCloser, error) {
m.mu.Lock()
defer m.mu.Unlock()
+ m.getReaderCalls++
if data, ok := m.files[key]; ok {
return io.NopCloser(bytes.NewReader(data)), nil
}
return nil, fmt.Errorf("mockStorage GetReader: key not found: %q", key)
}
+func (m *mockStorage) streamCopyCalls() (getReader, uploadStream int) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.getReaderCalls, m.uploadStreamCalls
+}
func (m *mockStorage) PresignGet(_ context.Context, key string, _ time.Duration) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 62d7b8c05d..e9790341a0 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2608,6 +2608,9 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
task, err := h.TaskService.EnqueueQuickCreateTask(r.Context(), wsUUID, requesterUUID, agentUUID, squadUUID, prompt, priority, dueDate, projectUUID, parentIssueUUID, attachmentIDs)
if err != nil {
+ if writeIssueLimitReached(w, err) {
+ return
+ }
slog.Warn("quick-create enqueue failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to enqueue quick-create task")
return
diff --git a/server/internal/handler/quick_create_parent_test.go b/server/internal/handler/quick_create_parent_test.go
index 8b580e88f1..65464136d6 100644
--- a/server/internal/handler/quick_create_parent_test.go
+++ b/server/internal/handler/quick_create_parent_test.go
@@ -7,6 +7,9 @@ import (
"net/http/httptest"
"testing"
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/pkg/agent"
)
@@ -181,6 +184,54 @@ func TestQuickCreateIssueParentTrustBoundary(t *testing.T) {
}
})
+ t.Run("full workspace is rejected before enqueue", func(t *testing.T) {
+ before := countQuickCreateTasks(t)
+ var issueCount int
+ if err := testPool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`,
+ testWorkspaceID,
+ ).Scan(&issueCount); err != nil {
+ t.Fatalf("count workspace issues: %v", err)
+ }
+ if issueCount <= 0 {
+ t.Fatal("full-workspace test requires at least one seeded issue")
+ }
+ stub := entitlementtest.New()
+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},
+ PolicyRevision: 23,
+ })
+ priorProvider := testHandler.TaskService.Entitlements
+ testHandler.TaskService.Entitlements = stub
+ t.Cleanup(func() {
+ testHandler.TaskService.Entitlements = priorProvider
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/quick-create", map[string]any{
+ "agent_id": agentID,
+ "prompt": "This task must not be queued when the workspace is full",
+ })
+ testHandler.QuickCreateIssue(w, req)
+ if w.Code != http.StatusPaymentRequired {
+ t.Fatalf("expected 402, got %d: %s", w.Code, w.Body.String())
+ }
+ var body struct {
+ Code string `json:"code"`
+ Limit int `json:"limit"`
+ PolicyRevision int `json:"policy_revision"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode issue-limit response: %v", err)
+ }
+ if body.Code != "issue_limit_reached" || body.Limit != issueCount || body.PolicyRevision != 23 {
+ t.Fatalf("unexpected issue-limit response: %+v", body)
+ }
+ if got := countQuickCreateTasks(t); got != before {
+ t.Fatalf("full workspace must not enqueue a task: expected %d, got %d", before, got)
+ }
+ })
+
t.Run("foreign workspace parent is rejected", func(t *testing.T) {
before := countQuickCreateTasks(t)
w := httptest.NewRecorder()
diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.go
index 18ca775a79..392297b71f 100644
--- a/server/internal/handler/source_context.go
+++ b/server/internal/handler/source_context.go
@@ -492,6 +492,17 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusBadRequest, "mode must be manual or agent")
return
}
+ // Reject a full workspace before cloning source attachments. This early
+ // check avoids expensive work; the TaskService enqueue preflight and final
+ // transactional issue admission remain necessary because this is not a
+ // capacity reservation.
+ if err := service.CheckIssueCreateCapacity(r.Context(), h.Queries, h.Entitlements, wsUUID); err != nil {
+ if !writeIssueLimitReached(w, err) {
+ slog.Warn("source context issue-capacity preflight failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to check issue capacity")
+ }
+ return
+ }
contextID := dbid.NewV7()
capture, objectKeys, err := h.cloneSourceContext(r.Context(), wsUUID, userUUID, contextID, build)
diff --git a/server/internal/handler/source_context_integration_test.go b/server/internal/handler/source_context_integration_test.go
index 653780e458..42b7ec4e16 100644
--- a/server/internal/handler/source_context_integration_test.go
+++ b/server/internal/handler/source_context_integration_test.go
@@ -11,9 +11,14 @@ import (
"testing"
"time"
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
"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/protocol"
)
@@ -32,6 +37,119 @@ func TestWriteSourceContextErrorHidesInternalDetails(t *testing.T) {
}
}
+func TestRetrySourceContextQuickCreateReturnsIssueLimitRecovery(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent
+ WHERE workspace_id = $1 AND runtime_id IS NOT NULL AND archived_at IS NULL
+ ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("load retry test agent: %v", err)
+ }
+ contextID := uuid.NewString()
+ payload, err := json.Marshal(service.QuickCreateContext{
+ Type: service.QuickCreateContextType,
+ Prompt: "retry source context at issue limit",
+ RequesterID: testUserID,
+ WorkspaceID: testWorkspaceID,
+ SourceContextID: contextID,
+ })
+ if err != nil {
+ t.Fatalf("marshal retry context: %v", err)
+ }
+ number := int(time.Now().UnixNano()%100000) + 9_200_000
+ var sourceIssueID, taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)
+ VALUES ($1, 'retry limit source', 'member', $2, $3)
+ RETURNING id
+ `, testWorkspaceID, testUserID, number).Scan(&sourceIssueID); err != nil {
+ t.Fatalf("insert retry source issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_source_context WHERE id = $1`, contextID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE rerun_of_task_id = $1 OR id = $1`, taskID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, sourceIssueID)
+ })
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, status, priority, context,
+ originator_user_id, accountable_user_id
+ )
+ SELECT $1, runtime_id, 'failed', 0, $2, $3, $3
+ FROM agent WHERE id = $1
+ RETURNING id
+ `, agentID, payload, testUserID).Scan(&taskID); err != nil {
+ t.Fatalf("insert failed source-context task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue_source_context (
+ id, workspace_id, origin_task_id, source_issue_id, anchor_comment_id,
+ captured_by_user_id, snapshot_version, snapshot, capture_digest, state
+ ) VALUES ($1, $2, $3, $4, gen_random_uuid(), $5, 1, '{}'::jsonb, 'digest', 'pending')
+ `, contextID, testWorkspaceID, taskID, sourceIssueID, testUserID); err != nil {
+ t.Fatalf("insert pending source context: %v", err)
+ }
+ var issueCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&issueCount); err != nil {
+ t.Fatalf("count issues before retry: %v", err)
+ }
+ stub := entitlementtest.New()
+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},
+ PolicyRevision: 43,
+ })
+ priorProvider := testHandler.TaskService.Entitlements
+ testHandler.TaskService.Entitlements = stub
+ t.Cleanup(func() {
+ testHandler.TaskService.Entitlements = priorProvider
+ })
+
+ recorder := httptest.NewRecorder()
+ request := withURLParam(newRequest(http.MethodPost, "/api/tasks/"+taskID+"/retry-source-context", nil), "taskId", taskID)
+ member, err := testHandler.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: util.MustParseUUID(testUserID),
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load retry caller membership: %v", err)
+ }
+ request = request.WithContext(middleware.SetMemberContext(request.Context(), testWorkspaceID, member))
+ testHandler.RetrySourceContextQuickCreate(recorder, request)
+ if recorder.Code != http.StatusPaymentRequired {
+ t.Fatalf("source-context retry at limit = %d: %s", recorder.Code, recorder.Body.String())
+ }
+ var body struct {
+ Code string `json:"code"`
+ Limit int `json:"limit"`
+ PolicyRevision int `json:"policy_revision"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode retry issue-limit response: %v", err)
+ }
+ if body.Code != "issue_limit_reached" || body.Limit != issueCount || body.PolicyRevision != 43 {
+ t.Fatalf("retry issue-limit response = %+v", body)
+ }
+ var children int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE rerun_of_task_id = $1`, taskID).Scan(&children); err != nil {
+ t.Fatalf("count retry children: %v", err)
+ }
+ if children != 0 {
+ t.Fatalf("retry child count = %d, want 0", children)
+ }
+ var originTaskID string
+ if err := testPool.QueryRow(ctx, `SELECT origin_task_id FROM issue_source_context WHERE id = $1`, contextID).Scan(&originTaskID); err != nil {
+ t.Fatalf("load pending context after rejection: %v", err)
+ }
+ if originTaskID != taskID {
+ t.Fatalf("pending context moved to %s, want original task %s", originTaskID, taskID)
+ }
+}
+
func TestCommentSourceContextLifecycle(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -212,6 +330,82 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
t.Fatalf("restore earlier thread comment: %v", err)
}
+ t.Run("full workspace skips source attachment copies and enqueue", func(t *testing.T) {
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent
+ WHERE workspace_id = $1 AND runtime_id = $2 AND archived_at IS NULL
+ ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID, testRuntimeID).Scan(&agentID); err != nil {
+ t.Fatalf("load source-context test agent: %v", err)
+ }
+ var originalMetadata string
+ if err := testPool.QueryRow(ctx, `SELECT metadata::text FROM agent_runtime WHERE id = $1`, testRuntimeID).Scan(&originalMetadata); err != nil {
+ t.Fatalf("load original runtime metadata: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_runtime
+ SET metadata = '{"cli_version":"0.4.3","capabilities":["source_context_quick_create_v1"]}'::jsonb
+ WHERE id = $1
+ `, testRuntimeID); err != nil {
+ t.Fatalf("enable source-context capability: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `UPDATE agent_runtime SET metadata = $1::jsonb WHERE id = $2`, originalMetadata, testRuntimeID)
+ })
+
+ var issueCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&issueCount); err != nil {
+ t.Fatalf("count issues before source-context limit check: %v", err)
+ }
+ stub := entitlementtest.New()
+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},
+ PolicyRevision: 41,
+ })
+ priorHandlerProvider := testHandler.Entitlements
+ priorTaskProvider := testHandler.TaskService.Entitlements
+ testHandler.Entitlements = stub
+ testHandler.TaskService.Entitlements = stub
+ t.Cleanup(func() {
+ testHandler.Entitlements = priorHandlerProvider
+ testHandler.TaskService.Entitlements = priorTaskProvider
+ })
+
+ beforeReads, beforeUploads := store.streamCopyCalls()
+ prompt := "source context must not enqueue while the workspace is full"
+ fullRecorder := httptest.NewRecorder()
+ fullRequest := withURLParam(newRequest(http.MethodPost, "/api/comments/"+selectedID+"/sub-issues", map[string]any{
+ "mode": "agent",
+ "capture_token": preview.CaptureToken,
+ "quick_create": map[string]any{
+ "agent_id": agentID,
+ "prompt": prompt,
+ },
+ }), "commentId", selectedID)
+ testHandler.CreateCommentSubIssue(fullRecorder, fullRequest)
+ if fullRecorder.Code != http.StatusPaymentRequired {
+ t.Fatalf("full source-context create = %d: %s", fullRecorder.Code, fullRecorder.Body.String())
+ }
+ var body struct {
+ Code string `json:"code"`
+ }
+ if err := json.Unmarshal(fullRecorder.Body.Bytes(), &body); err != nil || body.Code != "issue_limit_reached" {
+ t.Fatalf("full source-context response = %+v, err=%v", body, err)
+ }
+ afterReads, afterUploads := store.streamCopyCalls()
+ if afterReads != beforeReads || afterUploads != beforeUploads {
+ t.Fatalf("source attachments copied before rejection: reads %d->%d uploads %d->%d", beforeReads, afterReads, beforeUploads, afterUploads)
+ }
+ var queued int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE context->>'prompt' = $1`, prompt).Scan(&queued); err != nil {
+ t.Fatalf("count full source-context tasks: %v", err)
+ }
+ if queued != 0 {
+ t.Fatalf("full source-context task count = %d, want 0", queued)
+ }
+ })
+
// A damaged cross-issue parent chain is rejected instead of truncated.
var foreignIssueID, foreignRootID string
if err := testPool.QueryRow(ctx, `
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
index b379d221ef..5686375c80 100644
--- a/server/internal/handler/task_lifecycle.go
+++ b/server/internal/handler/task_lifecycle.go
@@ -248,6 +248,9 @@ func (h *Handler) RetrySourceContextQuickCreate(w http.ResponseWriter, r *http.R
return h.canInvokeAgent(r.Context(), agent, "member", userID, userID, uuidToString(workspaceID))
}
task, err := h.TaskService.RetrySourceContextQuickCreate(r.Context(), workspaceID, requesterID, taskID, canInvoke)
+ if writeIssueLimitReached(w, err) {
+ return
+ }
if errors.Is(err, service.ErrRerunInvokeNotAllowed) {
h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
return
diff --git a/server/internal/integrations/slack/slash_command.go b/server/internal/integrations/slack/slash_command.go
index 43cd40a181..d2451075a4 100644
--- a/server/internal/integrations/slack/slash_command.go
+++ b/server/internal/integrations/slack/slash_command.go
@@ -12,6 +12,7 @@ import (
"github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -50,6 +51,7 @@ const (
slashQueuedText = "✅ On it — I'm turning that into an issue. You'll get a Multica notification when it's ready."
slashNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you."
slashLinkAccountFallback = "Link your Slack account to Multica first, then try `/issue` again."
+ slashIssueLimitText = "⚠️ This workspace has reached its issue limit. Open Multica to view the available recovery options."
slashInternalErrorText = "⚠️ Something went wrong creating the issue. Please try again."
slashDisabledText = "This Slack app isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."
slashNewStartedText = "✅ Started a new Multica chat."
@@ -282,6 +284,10 @@ func (p *SlashCommandProcessor) process(ctx context.Context, cmd slack.SlashComm
pgtype.UUID{}, // no parent issue
nil, // no attachments
); err != nil {
+ var limitErr *service.IssueLimitReachedError
+ if errors.As(err, &limitErr) {
+ return slashIssueLimitText
+ }
p.logger.WarnContext(ctx, "slack slash command: enqueue quick-create failed",
"app_id", cmd.APIAppID, "error", err)
return slashInternalErrorText
diff --git a/server/internal/integrations/slack/slash_command_test.go b/server/internal/integrations/slack/slash_command_test.go
index 4003acc315..e198f98e50 100644
--- a/server/internal/integrations/slack/slash_command_test.go
+++ b/server/internal/integrations/slack/slash_command_test.go
@@ -1,6 +1,7 @@
package slack
import (
+ "bytes"
"context"
"errors"
"log/slog"
@@ -12,6 +13,7 @@ import (
"github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -296,6 +298,29 @@ func TestSlashHandle_EnqueueFailureIsInternalError(t *testing.T) {
}
}
+func TestSlashHandle_IssueLimitReachedIsActionable(t *testing.T) {
+ q := &fakeSlashQueries{
+ inst: activeSlashInstallation(),
+ binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)},
+ }
+ tasks := &fakeQuickCreate{err: &service.IssueLimitReachedError{Limit: 100, PolicyRevision: 7}}
+ p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})
+ var logs bytes.Buffer
+ p.logger = slog.New(slog.NewTextHandler(&logs, nil))
+
+ p.Handle(context.Background(), issueSlashCmd())
+
+ if tasks.calls != 1 {
+ t.Fatalf("expected the enqueue to be attempted once, got %d", tasks.calls)
+ }
+ if *captured != slashIssueLimitText {
+ t.Fatalf("expected issue-limit reply, got %q", *captured)
+ }
+ if logs.Len() != 0 {
+ t.Fatalf("expected issue-limit rejection not to emit a warning, got %q", logs.String())
+ }
+}
+
func TestSlashHandle_IgnoresOtherCommands(t *testing.T) {
tasks := &fakeQuickCreate{}
p, _, count := newTestSlashProcessor(&fakeSlashQueries{inst: activeSlashInstallation()}, tasks, &fakeBindingMinter{})
diff --git a/server/internal/service/issue_limit.go b/server/internal/service/issue_limit.go
index 1153638cf2..dc5368e0bf 100644
--- a/server/internal/service/issue_limit.go
+++ b/server/internal/service/issue_limit.go
@@ -59,6 +59,26 @@ func ResolveIssueCountPolicy(ctx context.Context, provider entitlement.Provider,
return policy
}
+// CheckIssueCreateCapacity performs a read-only admission preflight for flows
+// that do work before the issue transaction starts, such as agent quick create.
+// It is deliberately not a reservation: callers must still use
+// AllocateIssueNumber in the final create transaction to serialize concurrent
+// admissions against the workspace row.
+func CheckIssueCreateCapacity(ctx context.Context, q *db.Queries, provider entitlement.Provider, workspaceID pgtype.UUID) error {
+ policy := ResolveIssueCountPolicy(ctx, provider, workspaceID)
+ if policy.Action != entitlement.ActionEnforce {
+ return nil
+ }
+ used, err := CountIssueUsage(ctx, q, workspaceID, policy)
+ if err != nil {
+ return err
+ }
+ if used >= policy.Limit {
+ return &IssueLimitReachedError{Limit: policy.Limit, PolicyRevision: policy.PolicyRevision}
+ }
+ return nil
+}
+
// AllocateIssueNumber serializes creates on the workspace row, then checks the
// current number of issue rows inside the same transaction. The caller must
// roll the transaction back on IssueLimitReachedError; that also rolls back
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 24875cafe7..c50c0d48fd 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -19,6 +19,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/chattitle"
+ "github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/issuestatus"
@@ -43,6 +44,9 @@ type TaskService struct {
Analytics analytics.Client
Metrics *obsmetrics.BusinessMetrics
Wakeup TaskWakeupNotifier
+ // Entitlements supplies Cloud's workspace-scoped issue-count instruction.
+ // Nil keeps self-hosted and isolated test services unlimited.
+ Entitlements entitlement.Provider
// SourceContextStorage is used only by the bounded 30-day cleanup pass for
// terminal quick-create captures. Nil disables it where storage is absent.
SourceContextStorage SourceContextObjectStore
@@ -1522,6 +1526,9 @@ func (s *TaskService) EnqueueQuickCreateTaskWithSourceContext(ctx context.Contex
}
func (s *TaskService) enqueueQuickCreateTask(ctx context.Context, workspaceID, requesterID pgtype.UUID, agentID, squadID pgtype.UUID, prompt, priority, dueDate string, projectID, parentIssueID pgtype.UUID, attachmentIDs []pgtype.UUID, capture *SourceContextCapture) (db.AgentTaskQueue, error) {
+ if err := CheckIssueCreateCapacity(ctx, s.Queries, s.Entitlements, workspaceID); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("preflight quick-create issue capacity: %w", err)
+ }
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
@@ -1692,6 +1699,9 @@ func (s *TaskService) RetrySourceContextQuickCreate(ctx context.Context, workspa
if canInvoke != nil && !canInvoke(agent) {
return nil, ErrRerunInvokeNotAllowed
}
+ if err := CheckIssueCreateCapacity(ctx, s.Queries, s.Entitlements, workspaceID); err != nil {
+ return nil, fmt.Errorf("preflight quick-create issue capacity: %w", err)
+ }
overlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)
tx, err := s.TxStarter.Begin(ctx)