Skip to content

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

Go

feat(billing): redesign issue-limit recovery dialog (#7635)

LinYushen3d37828e9265
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index 2aac6e5c5f..5a08e3977a 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -17,13 +17,21 @@ type ModalType =
interface ModalStore {
modal: ModalType;
data: Record<string, unknown> | null;
+ issueLimitRecoveryWorkspaceId: string | null;
open: (modal: NonNullable<ModalType>, data?: Record<string, unknown> | null) => void;
close: () => void;
+ showIssueLimitRecovery: (workspaceId: string) => void;
+ dismissIssueLimitRecovery: () => void;
}
export const useModalStore = create<ModalStore>((set) => ({
modal: null,
data: null,
+ issueLimitRecoveryWorkspaceId: null,
open: (modal, data = null) => set({ modal, data }),
close: () => set({ modal: null, data: null }),
+ showIssueLimitRecovery: (workspaceId) =>
+ set({ issueLimitRecoveryWorkspaceId: workspaceId }),
+ dismissIssueLimitRecovery: () =>
+ set({ issueLimitRecoveryWorkspaceId: null }),
}));
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 060d0a394e..dceca0b11c 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -233,9 +233,7 @@ 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 showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();
const draft = useIssueDraftStore((s) => s.draft);
const setManual = useIssueDraftStore((s) => s.setManual);
diff --git a/packages/views/modals/issue-limit-upgrade-dialog.test.tsx b/packages/views/modals/issue-limit-upgrade-dialog.test.tsx
new file mode 100644
index 0000000000..b0a987b529
--- /dev/null
+++ b/packages/views/modals/issue-limit-upgrade-dialog.test.tsx
@@ -0,0 +1,389 @@
+import { useState } from "react";
+import {
+ act,
+ cleanup,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { useModalStore } from "@multica/core/modals";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+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 mockCreatePortal = vi.hoisted(() => vi.fn());
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+const mockSummaryQuery = vi.hoisted(() => vi.fn());
+const featureState = vi.hoisted(() => ({ billingEnabled: true }));
+const workspaceState = vi.hoisted(() => ({ id: "ws-test" }));
+const summaryState = vi.hoisted(() => ({
+ value: null as null | { availableActions: AvailableActions },
+ error: null as Error | null,
+ pending: null as Promise<{ availableActions: AvailableActions } | null> | null,
+}));
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => workspaceState.id,
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ settings: () => `/${workspaceState.id}/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,
+ }),
+}));
+
+import { IssueLimitUpgradeDialog } from "./issue-limit-upgrade-dialog";
+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 PromptHarness() {
+ const showPrompt = useIssueLimitUpgradePrompt();
+ return (
+ <>
+ <button type="button" onClick={showPrompt}>
+ Show recovery
+ </button>
+ <IssueLimitUpgradeDialog />
+ </>
+ );
+}
+
+function LayeredPromptHarness() {
+ const [createOpen, setCreateOpen] = useState(true);
+ const showPrompt = useIssueLimitUpgradePrompt();
+
+ return (
+ <>
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
+ <DialogContent showCloseButton={false}>
+ <DialogTitle>Create an issue</DialogTitle>
+ <DialogDescription>Your draft remains here.</DialogDescription>
+ <button type="button" onClick={showPrompt}>
+ Show recovery
+ </button>
+ </DialogContent>
+ </Dialog>
+ <IssueLimitUpgradeDialog />
+ </>
+ );
+}
+
+function promptTree(client: QueryClient, layered = false) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={client}>
+ {layered ? <LayeredPromptHarness /> : <PromptHarness />}
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+}
+
+function renderPrompt({ layered = false }: { layered?: boolean } = {}) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: 1 } },
+ });
+ const view = render(promptTree(client, layered));
+ return { client, ...view };
+}
+
+async function openPrompt() {
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Show recovery" }));
+ return user;
+}
+
+function queryRecoveryDialog() {
+ return screen.queryByRole("dialog", {
+ name: "This workspace has reached its issue limit",
+ });
+}
+
+describe("IssueLimitUpgradeDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ featureState.billingEnabled = true;
+ workspaceState.id = "ws-test";
+ summaryState.value = null;
+ summaryState.error = null;
+ summaryState.pending = null;
+ useModalStore.setState({
+ modal: null,
+ data: null,
+ issueLimitRecoveryWorkspaceId: 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",
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ useModalStore.setState({
+ modal: null,
+ data: null,
+ issueLimitRecoveryWorkspaceId: null,
+ });
+ });
+
+ it("opens immediately as a centered recovery dialog with one close action", async () => {
+ summaryState.pending = new Promise<{
+ availableActions: AvailableActions;
+ } | null>(() => undefined);
+ renderPrompt();
+
+ await openPrompt();
+
+ expect(queryRecoveryDialog()).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "Checking the billing actions available for this workspace…",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getAllByRole("button", { name: "Close" })).toHaveLength(1);
+ });
+
+ it("closes only recovery when Escape is pressed above a create dialog", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ renderPrompt({ layered: true });
+ const user = await openPrompt();
+
+ await user.keyboard("{Escape}");
+
+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());
+ expect(
+ screen.getByRole("dialog", { name: "Create an issue" }),
+ ).toBeInTheDocument();
+ });
+
+ it("closes only recovery when its backdrop is pressed", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ renderPrompt({ layered: true });
+ const user = await openPrompt();
+ const overlays = document.querySelectorAll<HTMLElement>(
+ '[data-slot="dialog-overlay"]',
+ );
+
+ expect(overlays).toHaveLength(2);
+ await user.click(overlays[overlays.length - 1]!);
+
+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());
+ expect(
+ screen.getByRole("dialog", { name: "Create an issue" }),
+ ).toBeInTheDocument();
+ });
+
+ it("stays dismissed when the Cloud response arrives later", async () => {
+ let resolveSummary!: (
+ value: { availableActions: AvailableActions } | null,
+ ) => void;
+ summaryState.pending = new Promise((resolve) => {
+ resolveSummary = resolve;
+ });
+ renderPrompt();
+ const user = await openPrompt();
+
+ await user.click(screen.getByRole("button", { name: "Close" }));
+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());
+
+ await act(async () => {
+ resolveSummary({ availableActions: actions({ checkout: true }) });
+ await summaryState.pending;
+ });
+
+ expect(queryRecoveryDialog()).not.toBeInTheDocument();
+ });
+
+ it("keeps the create modal open when recovery is merely dismissed", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ useModalStore.getState().open("create-issue");
+ renderPrompt();
+ const user = await openPrompt();
+
+ await user.click(screen.getByRole("button", { name: "Close" }));
+
+ expect(useModalStore.getState().modal).toBe("create-issue");
+ });
+
+ it("dismisses recovery instead of carrying it into another workspace", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ const { client, rerender } = renderPrompt();
+ await openPrompt();
+
+ workspaceState.id = "ws-other";
+ rerender(promptTree(client));
+
+ await waitFor(() => {
+ expect(
+ useModalStore.getState().issueLimitRecoveryWorkspaceId,
+ ).toBeNull();
+ });
+ expect(queryRecoveryDialog()).not.toBeInTheDocument();
+ });
+
+ it("offers Upgrade to Pro only when Cloud authorizes checkout", async () => {
+ summaryState.value = { availableActions: actions({ checkout: true }) };
+ useModalStore.getState().open("create-issue");
+ renderPrompt();
+ const user = await openPrompt();
+
+ await user.click(
+ await screen.findByRole("button", { name: "Upgrade to Pro" }),
+ );
+
+ expect(useModalStore.getState().modal).toBeNull();
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/settings?tab=billing");
+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());
+ });
+
+ it("opens Billing Portal for a past-due manager authorized for portal", async () => {
+ summaryState.value = { availableActions: actions({ portal: true }) };
+ useModalStore.getState().open("quick-create-issue");
+ renderPrompt();
+ const user = await openPrompt();
+
+ await user.click(
+ await screen.findByRole("button", { name: "Open Billing Portal" }),
+ );
+
+ await waitFor(() => expect(mockCreatePortal).toHaveBeenCalledTimes(1));
+ expect(mockCreatePortal.mock.calls[0]?.[0]).toMatch(
+ /^issue-limit-portal-ws-test-/,
+ );
+ await waitFor(() => {
+ expect(mockOpenExternal).toHaveBeenCalledWith(
+ "https://billing.example/portal",
+ { webTarget: "same-tab" },
+ );
+ });
+ expect(useModalStore.getState().modal).toBeNull();
+ });
+
+ it("keeps a Billing recovery action when Portal cannot be opened", async () => {
+ summaryState.value = { availableActions: actions({ portal: true }) };
+ useModalStore.getState().open("create-issue");
+ mockCreatePortal.mockRejectedValue(new Error("portal unavailable"));
+ renderPrompt();
+ const user = await openPrompt();
+
+ await user.click(
+ await screen.findByRole("button", { name: "Open Billing Portal" }),
+ );
+
+ expect(
+ await screen.findByRole("button", { name: "View Billing" }),
+ ).toBeInTheDocument();
+ expect(useModalStore.getState().modal).toBe("create-issue");
+ expect(queryRecoveryDialog()).toBeInTheDocument();
+ });
+
+ it("asks for an administrator only when Cloud authorizes no management action", async () => {
+ summaryState.value = { availableActions: actions() };
+ renderPrompt();
+ await openPrompt();
+
+ expect(
+ await screen.findByText(
+ "Ask a workspace owner or admin to upgrade to Pro.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", {
+ name: /Upgrade|Billing Portal|View Billing/,
+ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps another Cloud-authorized management action reachable in Billing", async () => {
+ summaryState.value = {
+ availableActions: actions({ purchaseSeats: true }),
+ };
+ renderPrompt();
+ await openPrompt();
+
+ expect(
+ await screen.findByRole("button", { name: "View Billing" }),
+ ).toBeInTheDocument();
+ });
+
+ it("uses one background attempt and keeps Billing as the recovery path", async () => {
+ summaryState.error = new Error("cloud unavailable");
+ renderPrompt();
+ await openPrompt();
+
+ expect(
+ await screen.findByRole("button", { name: "View Billing" }),
+ ).toBeInTheDocument();
+ expect(mockSummaryQuery).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not expose a dead Billing link when the Billing surface is disabled", async () => {
+ featureState.billingEnabled = false;
+ renderPrompt();
+ await openPrompt();
+
+ expect(
+ screen.getByText(
+ "Delete an existing issue to free space, or contact your workspace administrator.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "View Billing" }),
+ ).not.toBeInTheDocument();
+ expect(mockSummaryQuery).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/modals/issue-limit-upgrade-dialog.tsx b/packages/views/modals/issue-limit-upgrade-dialog.tsx
new file mode 100644
index 0000000000..b467e7fc4a
--- /dev/null
+++ b/packages/views/modals/issue-limit-upgrade-dialog.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Gauge, Loader2 } from "lucide-react";
+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 { useModalStore } 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";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { useT } from "../i18n";
+import { useNavigation } from "../navigation";
+import { openExternal } from "../platform";
+
+type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
+type ModalsT = ReturnType<typeof useT<"modals">>["t"];
+
+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);
+}
+
+/**
+ * Centered recovery surface shared by manual create, Quick Create, and Inbox.
+ * Cloud's complete action set is the only input that decides which billing
+ * action appears; no local role, plan, subscription, or quota inference does.
+ */
+export function IssueLimitUpgradeDialog() {
+ const recoveryWorkspaceId = useModalStore(
+ (state) => state.issueLimitRecoveryWorkspaceId,
+ );
+ const dismiss = useModalStore((state) => state.dismissIssueLimitRecovery);
+ const { t } = useT("modals");
+ const wsId = useWorkspaceId();
+ const visible = recoveryWorkspaceId === wsId;
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const billingEnabled = useFeatureEnabled(
+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
+ false,
+ );
+ const summaryQuery = useQuery({
+ ...workspaceSubscriptionSummaryOptions(wsId),
+ enabled: visible && billingEnabled,
+ staleTime: 0,
+ retry: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ });
+ const createPortal = useCreateWorkspaceSubscriptionPortal(wsId).mutateAsync;
+ const portalIntentKeyRef = useRef<string | null>(null);
+ const [openingPortal, setOpeningPortal] = useState(false);
+ const [portalFailed, setPortalFailed] = useState(false);
+
+ useEffect(() => {
+ if (recoveryWorkspaceId !== null && recoveryWorkspaceId !== wsId) {
+ dismiss();
+ }
+ }, [dismiss, recoveryWorkspaceId, wsId]);
+
+ useEffect(() => {
+ portalIntentKeyRef.current = null;
+ setOpeningPortal(false);
+ setPortalFailed(false);
+ }, [visible, wsId]);
+
+ const closeForBillingAction = () => {
+ dismiss();
+
+ // Recovery can also open from Inbox. Only close an underlying issue-create
+ // modal when following its billing action; leave every other modal alone.
+ const modalStore = useModalStore.getState();
+ if (
+ modalStore.modal === "create-issue" ||
+ modalStore.modal === "quick-create-issue"
+ ) {
+ modalStore.close();
+ }
+ };
+ const openBilling = () => {
+ closeForBillingAction();
+ navigation.push(`${paths.settings()}?tab=billing`);
+ };
+ const openPortal = async () => {
+ const key =
+ portalIntentKeyRef.current ?? createPortalIdempotencyKey(wsId);
+ portalIntentKeyRef.current = key;
+ setOpeningPortal(true);
+ try {
+ const response = await createPortal(key);
+ if (!response?.url) {
+ setPortalFailed(true);
+ return;
+ }
+ portalIntentKeyRef.current = null;
+ closeForBillingAction();
+ openExternal(response.url, { webTarget: "same-tab" });
+ } catch {
+ setPortalFailed(true);
+ } finally {
+ setOpeningPortal(false);
+ }
+ };
+
+ const actions = summaryQuery.data?.availableActions;
+ const recovery = resolveRecoveryPresentation({
+ actions,
+ billingEnabled,
+ loading: billingEnabled && !actions && summaryQuery.isFetching,
+ portalFailed,
+ t,
+ openBilling,
+ openPortal,
+ });
+
+ return (
+ <Dialog
+ open={visible}
+ modal
+ onOpenChange={(open) => {
+ if (!open) dismiss();
+ }}
+ >
+ <DialogContent
+ className="gap-0 overflow-hidden p-0 sm:max-w-lg"
+ showCloseButton={false}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ event.stopPropagation();
+ dismiss();
+ }}
+ >
+ <div className="px-6 pb-7 pt-8 text-center sm:px-10 sm:pb-8 sm:pt-10">
+ <div className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/15">
+ <Gauge className="size-7" aria-hidden="true" />
+ </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)}
+ </DialogTitle>
+ <DialogDescription className="max-w-sm text-pretty text-center text-body leading-6">
+ {recovery.description}
+ </DialogDescription>
+ </DialogHeader>
+ </div>
+
+ <DialogFooter className="m-0 px-6 py-4 sm:justify-center sm:px-10">
+ <Button
+ variant={recovery.action ? "outline" : "default"}
+ size="lg"
+ className="sm:min-w-28"
+ onClick={dismiss}
+ >
+ {t(($) => $.common.close)}
+ </Button>
+ {recovery.action && (
+ <Button
+ size="lg"
+ className="sm:min-w-40"
+ disabled={openingPortal}
+ onClick={recovery.action.onClick}
+ >
+ {openingPortal && <Loader2 className="animate-spin" />}
+ {recovery.action.label}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+interface RecoveryPresentation {
+ description: string;
+ action?: {
+ label: string;
+ onClick: () => void;
+ };
+}
+
+function resolveRecoveryPresentation({
+ actions,
+ billingEnabled,
+ loading,
+ portalFailed,
+ t,
+ openBilling,
+ openPortal,
+}: {
+ actions: BillingActions | undefined;
+ billingEnabled: boolean;
+ loading: boolean;
+ portalFailed: boolean;
+ t: ModalsT;
+ 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,
+ },
+ };
+ }
+
+ if (actions?.portal) {
+ return {
+ description: t(($) => $.create_issue.issue_limit.portal_description),
+ action: {
+ label: t(($) => $.create_issue.issue_limit.portal_action),
+ onClick: () => {
+ void openPortal();
+ },
+ },
+ };
+ }
+
+ 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),
+ };
+ }
+
+ 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/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index eccf5bbfbe..bdcb9758c0 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -136,9 +136,7 @@ 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 showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();
const userId = useAuthStore((s) => s.user?.id);
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsx
index 226b4eea05..8b8935d344 100644
--- a/packages/views/modals/registry.tsx
+++ b/packages/views/modals/registry.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { ReactNode } from "react";
import { useModalStore } from "@multica/core/modals";
import { CreateIssueDialog } from "./create-issue-dialog";
import { CreateProjectModal } from "./create-project";
@@ -9,34 +10,62 @@ import { SetParentIssueModal } from "./set-parent-issue";
import { AddChildIssueModal } from "./add-child-issue";
import { DeleteIssueConfirmModal } from "./delete-issue-confirm";
import { RunConfirmModal } from "./run-confirm";
+import { IssueLimitUpgradeDialog } from "./issue-limit-upgrade-dialog";
export function ModalRegistry() {
const modal = useModalStore((s) => s.modal);
const data = useModalStore((s) => s.data);
const close = useModalStore((s) => s.close);
+ let activeModal: ReactNode = null;
switch (modal) {
// Both modal types open the same shell so the in-modal mode switch is
// instant — only the inner panel swaps, the Dialog Root stays mounted.
case "create-issue":
- return <CreateIssueDialog onClose={close} initialMode="manual" data={data} />;
+ activeModal = (
+ <CreateIssueDialog
+ onClose={close}
+ initialMode="manual"
+ data={data}
+ />
+ );
+ break;
case "quick-create-issue":
- return <CreateIssueDialog onClose={close} initialMode="agent" data={data} />;
+ activeModal = (
+ <CreateIssueDialog
+ onClose={close}
+ initialMode="agent"
+ data={data}
+ />
+ );
+ break;
case "create-project":
- return <CreateProjectModal onClose={close} />;
+ activeModal = <CreateProjectModal onClose={close} />;
+ break;
case "create-squad":
- return <CreateSquadModal onClose={close} />;
+ activeModal = <CreateSquadModal onClose={close} />;
+ break;
case "feedback":
- return <FeedbackModal onClose={close} data={data} />;
+ activeModal = <FeedbackModal onClose={close} data={data} />;
+ break;
case "issue-set-parent":
- return <SetParentIssueModal onClose={close} data={data} />;
+ activeModal = <SetParentIssueModal onClose={close} data={data} />;
+ break;
case "issue-add-child":
- return <AddChildIssueModal onClose={close} data={data} />;
+ activeModal = <AddChildIssueModal onClose={close} data={data} />;
+ break;
case "issue-delete-confirm":
- return <DeleteIssueConfirmModal onClose={close} data={data} />;
+ activeModal = <DeleteIssueConfirmModal onClose={close} data={data} />;
+ break;
case "issue-run-confirm":
- return <RunConfirmModal onClose={close} data={data} />;
- default:
- return null;
+ activeModal = <RunConfirmModal onClose={close} data={data} />;
+ break;
}
+
+ return (
+ <>
+ {activeModal}
+ <IssueLimitUpgradeDialog />
+ </>
+ );
}
diff --git a/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx b/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx
deleted file mode 100644
index 24655fe3aa..0000000000
--- a/packages/views/modals/use-issue-limit-upgrade-prompt.test.tsx
+++ /dev/null
@@ -1,274 +0,0 @@
-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
index 2c56c82c1f..3dd4e4abae 100644
--- a/packages/views/modals/use-issue-limit-upgrade-prompt.ts
+++ b/packages/views/modals/use-issue-limit-upgrade-prompt.ts
@@ -1,212 +1,14 @@
"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 { useCallback } from "react";
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";
+import { useModalStore } from "@multica/core/modals";
-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();
+/** Opens the shared issue-limit recovery dialog without closing the current draft. */
+export function useIssueLimitUpgradePrompt(): () => void {
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,
- ]);
+ useModalStore.getState().showIssueLimitRecovery(wsId);
+ }, [wsId]);
}