AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
Update daily limit popup to new design (SECRT-2294) (#12973)
Nicholas Tindlee2e37c66886b
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsxindex dcefd33aea..ac954923f5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx@@ -3,8 +3,6 @@import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";import { toast } from "@/components/molecules/Toast/use-toast";-import useCredits from "@/hooks/useCredits";-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { useEffect } from "react";import { RateLimitResetDialog } from "./RateLimitResetDialog";@@ -14,10 +12,8 @@ interface Props {}/**- * Renders the rate-limit dialog when the user has an actionable reset path- * (positive reset_cost). Otherwise falls back to a toast so the user still- * gets feedback. Encapsulates all the usage/credits/flag state that's only- * needed once a rate limit is hit.+ * Renders the rate-limit dialog when the user hits their daily limit.+ * Falls back to a toast when the usage query fails.*/export function RateLimitGate({ rateLimitMessage, onDismiss }: Props) {const {@@ -27,58 +23,30 @@ export function RateLimitGate({ rateLimitMessage, onDismiss }: Props) {} = useGetV2GetCopilotUsage({query: {select: (res) => res.data as CoPilotUsagePublic,- // Only fetch once a rate limit has been hit — avoids a 30s background- // poll for the 99% of sessions that never hit their quota.enabled: !!rateLimitMessage,refetchInterval: 30_000,staleTime: 10_000,},});- const resetCost = usage?.reset_cost;- const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);- const { credits, fetchCredits } = useCredits({ fetchInitialCredits: true });- const hasInsufficientCredits =- credits !== null && resetCost != null && credits < resetCost;- // Fall back to a toast when the credit-based reset isn't a real option:- // billing is off (no way to top up), the usage query failed, or reset_cost- // is non-positive. Without billing the dialog's "Add credits" CTA is dead,- // so showing it would just dangle a useless reset offer.useEffect(() => {if (!rateLimitMessage) return;- const creditResetUnavailable =- !isBillingEnabled || usageError || (hasUsage && (resetCost ?? 0) <= 0);- if (!creditResetUnavailable) return;+ if (!usageError) return;toast({title: "Usage limit reached",description: rateLimitMessage,variant: "destructive",});onDismiss();- }, [- rateLimitMessage,- resetCost,- hasUsage,- usageError,- onDismiss,- isBillingEnabled,- ]);+ }, [rateLimitMessage, usageError, onDismiss]);- const canShowDialog =- isBillingEnabled && !!rateLimitMessage && hasUsage && (resetCost ?? 0) > 0;+ const isOpen = !!rateLimitMessage && hasUsage;return (<RateLimitResetDialog- isOpen={canShowDialog}+ isOpen={isOpen}onClose={onDismiss}- resetCost={resetCost ?? 0}- resetMessage={rateLimitMessage ?? ""}- isWeeklyExhausted={- hasUsage && !!usage.weekly && usage.weekly.percent_used >= 100- }- hasInsufficientCredits={hasInsufficientCredits}- isBillingEnabled={isBillingEnabled}- onCreditChange={fetchCredits}+ resetsAt={usage?.daily?.resets_at ?? usage?.weekly?.resets_at ?? null}/>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsxindex 22e892655a..7ef04c468e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx@@ -4,56 +4,21 @@ import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";import { useRouter } from "next/navigation";-import { useEffect, useRef } from "react";-import { useResetRateLimit } from "../../hooks/useResetRateLimit";-import { formatCents } from "../usageHelpers";--export { formatCents };+import { formatResetTime } from "../usageHelpers";interface Props {isOpen: boolean;onClose: () => void;- resetCost: number;- resetMessage: string;- isWeeklyExhausted?: boolean;- hasInsufficientCredits?: boolean;- isBillingEnabled?: boolean;- onCreditChange?: () => void;+ resetsAt?: string | Date | null;}-export function RateLimitResetDialog({- isOpen,- onClose,- resetCost,- resetMessage,- isWeeklyExhausted = false,- hasInsufficientCredits = false,- isBillingEnabled = false,- onCreditChange,-}: Props) {- const { resetUsage, isPending } = useResetRateLimit({- onSuccess: onClose,- onCreditChange,- });+export function RateLimitResetDialog({ isOpen, onClose, resetsAt }: Props) {const router = useRouter();-- // Stable ref for the callback so the effect only re-fires when- // `isOpen` changes, not when the function reference changes.- const onCreditChangeRef = useRef(onCreditChange);- onCreditChangeRef.current = onCreditChange;-- // Refresh the credit balance each time the dialog opens so we never- // block a valid reset due to a stale client-side balance.- useEffect(() => {- if (isOpen) onCreditChangeRef.current?.();- }, [isOpen]);-- // Whether to hide the reset button entirely- const cannotReset = isWeeklyExhausted || hasInsufficientCredits;+ const resetTimeLabel = resetsAt ? formatResetTime(resetsAt) : null;return (<Dialog- title="Usage limit reached"+ title="Daily AutoPilot limit reached"styling={{ maxWidth: "28rem", minWidth: "auto" }}controlled={{isOpen,@@ -63,54 +28,27 @@ export function RateLimitResetDialog({}}><Dialog.Content>- <div className="flex flex-col gap-3">- <Text variant="body">{resetMessage}</Text>- {isWeeklyExhausted ? (- <Text variant="body">- Your weekly limit is also reached, so resetting the daily limit- won't help. Please wait for your limits to reset.- </Text>- ) : hasInsufficientCredits ? (- <Text variant="body">- You don't have enough credits to reset your daily limit.- {isBillingEnabled- ? " Add credits to continue working."- : " Please wait for your limits to reset."}- </Text>- ) : (- <Text variant="body">- You can spend{" "}- <Text variant="body-medium" as="span">- {formatCents(resetCost)}- </Text>{" "}- in credits to reset your daily limit and continue working.- </Text>- )}- </div>+ <Text variant="body">+ You've reached your daily usage limit.+ {resetTimeLabel && resetTimeLabel !== "now"+ ? ` Resets ${resetTimeLabel}.`+ : ""}{" "}+ You can still browse, edit agents, and view results — or upgrade+ your plan.+ </Text><Dialog.Footer className="!justify-center">- <Button variant="secondary" onClick={onClose} disabled={isPending}>- {cannotReset ? "OK" : "Wait for reset"}+ <Button variant="secondary" onClick={onClose}>+ Wait for reset+ </Button>+ <Button+ variant="primary"+ onClick={() => {+ onClose();+ router.push("/settings/billing");+ }}+ >+ Go to billing</Button>- {hasInsufficientCredits && isBillingEnabled && (- <Button- variant="primary"- onClick={() => {- onClose();- router.push("/profile/credits");- }}- >- Add credits- </Button>- )}- {!cannotReset && (- <Button- variant="primary"- onClick={() => resetUsage()}- loading={isPending}- >- Reset for {formatCents(resetCost)}- </Button>- )}</Dialog.Footer></Dialog.Content></Dialog>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsxindex fc2a752588..e70ba89835 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx@@ -19,20 +19,14 @@ vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({mockUseGetV2GetCopilotUsage(...args),}));-vi.mock("@/hooks/useCredits", () => ({- default: () => ({ credits: 1000, fetchCredits: vi.fn() }),-}));--const mockUseGetFlag = vi.fn(() => true);-vi.mock("@/services/feature-flags/use-get-flag", () => ({- Flag: { ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT" },- useGetFlag: () => mockUseGetFlag(),-}));-// Capture props the dialog was rendered with so we can assert on them.const dialogSpy = vi.fn();vi.mock("../RateLimitResetDialog", () => ({- RateLimitResetDialog: (props: { isOpen: boolean }) => {+ RateLimitResetDialog: (props: {+ isOpen: boolean;+ onClose: () => void;+ resetsAt?: string | Date | null;+ }) => {dialogSpy(props);return <div data-testid="reset-dialog" data-open={String(props.isOpen)} />;},@@ -45,8 +39,6 @@ afterEach(() => {mockToast.mockReset();mockUseGetV2GetCopilotUsage.mockReset();dialogSpy.mockReset();- mockUseGetFlag.mockReset();- mockUseGetFlag.mockReturnValue(true);});describe("RateLimitGate", () => {@@ -86,9 +78,10 @@ describe("RateLimitGate", () => {expect(config?.query?.enabled).toBe(true);});- it("opens the reset dialog when usage has a positive reset cost", () => {+ it("opens the reset dialog when usage data is available", () => {+ const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { reset_cost: 50, weekly: { percent_used: 100 } },+ data: { daily: { percent_used: 100, resets_at: future }, weekly: null },isSuccess: true,isError: false,});@@ -127,58 +120,111 @@ describe("RateLimitGate", () => {expect(toastArg.variant).toBe("destructive");expect(onDismiss).toHaveBeenCalledTimes(1);- // Dialog stays closed when the fallback fired.const lastProps = dialogSpy.mock.calls.at(-1)?.[0];expect(lastProps.isOpen).toBe(false);});- it("falls back to a toast when reset cost is non-positive (credit reset unavailable)", () => {- const onDismiss = vi.fn();+ it("does not fire the fallback toast when no rate-limit message is present", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: true,+ });++ render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);++ expect(mockToast).not.toHaveBeenCalled();+ });++ it("keeps the dialog closed while the usage query is still loading", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { reset_cost: 0, weekly: { percent_used: 100 } },+ data: undefined,+ isSuccess: false,+ isError: false,+ });++ render(+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ );++ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.isOpen).toBe(false);+ expect(mockToast).not.toHaveBeenCalled();+ });++ it("forwards daily resets_at timestamp to the dialog", () => {+ const future = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: { daily: { percent_used: 100, resets_at: future }, weekly: null },isSuccess: true,isError: false,});render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={onDismiss} />,+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,);- expect(mockToast).toHaveBeenCalledTimes(1);- expect(onDismiss).toHaveBeenCalledTimes(1);+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.resetsAt).toBe(future);+ });++ it("falls back to weekly resets_at when daily is missing", () => {+ const weeklyFuture = new Date(+ Date.now() + 3 * 24 * 60 * 60 * 1000,+ ).toISOString();+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: {+ daily: null,+ weekly: { percent_used: 100, resets_at: weeklyFuture },+ },+ isSuccess: true,+ isError: false,+ });++ render(+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ );const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(false);+ expect(lastProps.isOpen).toBe(true);+ expect(lastProps.resetsAt).toBe(weeklyFuture);});- it("falls back to a toast when ENABLE_PLATFORM_PAYMENT is off, even with a positive reset cost", () => {- mockUseGetFlag.mockReturnValue(false);- const onDismiss = vi.fn();+ it("passes null resetsAt when neither daily nor weekly data exists", () => {mockUseGetV2GetCopilotUsage.mockReturnValue({- data: { reset_cost: 50, weekly: { percent_used: 10 } },+ data: { daily: null, weekly: null },isSuccess: true,isError: false,});render(- <RateLimitGate rateLimitMessage="limit reached" onDismiss={onDismiss} />,+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,);- expect(mockToast).toHaveBeenCalledTimes(1);- expect(onDismiss).toHaveBeenCalledTimes(1);const lastProps = dialogSpy.mock.calls.at(-1)?.[0];- expect(lastProps.isOpen).toBe(false);+ expect(lastProps.isOpen).toBe(true);+ expect(lastProps.resetsAt).toBeNull();});- it("does not fire the fallback toast when no rate-limit message is present", () => {+ it("prefers daily resets_at over weekly when both are present", () => {+ const dailyFuture = new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString();+ const weeklyFuture = new Date(+ Date.now() + 3 * 24 * 60 * 60 * 1000,+ ).toISOString();mockUseGetV2GetCopilotUsage.mockReturnValue({- data: undefined,- isSuccess: false,- isError: true,+ data: {+ daily: { percent_used: 100, resets_at: dailyFuture },+ weekly: { percent_used: 80, resets_at: weeklyFuture },+ },+ isSuccess: true,+ isError: false,});- render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);+ render(+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ );- expect(mockToast).not.toHaveBeenCalled();+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.resetsAt).toBe(dailyFuture);});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsxnew file mode 100644index 0000000000..7eda60dbe5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitResetDialog.test.tsx@@ -0,0 +1,102 @@+import {+ cleanup,+ render,+ screen,+ fireEvent,+} from "@/tests/integrations/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++const mockPush = vi.fn();+vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: mockPush,+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/copilot",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({}),+}));++import { RateLimitResetDialog } from "../RateLimitResetDialog";++afterEach(() => {+ cleanup();+ mockPush.mockReset();+});++describe("RateLimitResetDialog", () => {+ it("renders the dialog title and body when open", () => {+ render(+ <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+ );++ expect(screen.getByText("Daily AutoPilot limit reached")).toBeDefined();+ expect(+ screen.getByText(/You've reached your daily usage limit/),+ ).toBeDefined();+ });++ it("shows the reset time when resetsAt is provided", () => {+ const future = new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString();+ render(+ <RateLimitResetDialog+ isOpen={true}+ onClose={vi.fn()}+ resetsAt={future}+ />,+ );++ expect(screen.getByText(/Resets in/)).toBeDefined();+ });++ it("omits the reset time when resetsAt is null", () => {+ render(+ <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+ );++ const bodyText = screen.getByText(/You've reached your daily usage limit/);+ expect(bodyText.textContent).not.toContain("Resets in");+ });++ it("renders Wait for reset and Go to billing buttons", () => {+ render(+ <RateLimitResetDialog isOpen={true} onClose={vi.fn()} resetsAt={null} />,+ );++ expect(screen.getByText("Wait for reset")).toBeDefined();+ expect(screen.getByText("Go to billing")).toBeDefined();+ });++ it("calls onClose when Wait for reset is clicked", () => {+ const onClose = vi.fn();+ render(+ <RateLimitResetDialog isOpen={true} onClose={onClose} resetsAt={null} />,+ );++ fireEvent.click(screen.getByText("Wait for reset"));+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("navigates to /settings/billing when Go to billing is clicked", () => {+ const onClose = vi.fn();+ render(+ <RateLimitResetDialog isOpen={true} onClose={onClose} resetsAt={null} />,+ );++ fireEvent.click(screen.getByText("Go to billing"));+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(mockPush).toHaveBeenCalledWith("/settings/billing");+ });++ it("does not render dialog content when closed", () => {+ render(+ <RateLimitResetDialog isOpen={false} onClose={vi.fn()} resetsAt={null} />,+ );++ expect(screen.queryByText("Daily AutoPilot limit reached")).toBeNull();+ });+});