Skip to content

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.

feat(frontend): prompt top-up when out of automation credits (#13208)

Ubbe2cad7c498692
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
index 949f5f612a..a590495b08 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
@@ -1,5 +1,6 @@
"use client";
+import { LowCreditBanner } from "@/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner";
import { SidebarProvider } from "@/components/ui/sidebar";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
@@ -55,6 +56,7 @@ export function CopilotPage() {
onFilesDropped={setDroppedFiles}
>
{isMobile && <MobileHeader />}
+ <LowCreditBanner className="px-4 pt-4" />
<NotificationBanner />
<CopilotChatHost
key={sessionId ?? "new"}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/low-credit-banner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/low-credit-banner.test.tsx
new file mode 100644
index 0000000000..0bf65d9084
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/low-credit-banner.test.tsx
@@ -0,0 +1,152 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { render, screen } from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import {
+ getGetV1GetUserCreditsMockHandler,
+ getGetV1GetAutoTopUpMockHandler,
+} from "@/app/api/__generated__/endpoints/credits/credits.msw";
+import { Key } from "@/services/storage/local-storage";
+import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
+import { CopilotPage } from "../CopilotPage";
+
+// Stub the heavy chat subtree so the page mounts without websockets/streams.
+// We only need a stable element to assert the page has rendered, plus the
+// banner that TopUpPromptProvider + LowCreditBanner inject at the top.
+vi.mock("../components/ChatContainer/ChatContainer", () => ({
+ ChatContainer: () => <div data-testid="chat-container" />,
+}));
+vi.mock("../components/ChatSidebar/ChatSidebar", () => ({
+ ChatSidebar: () => <div data-testid="chat-sidebar" />,
+}));
+vi.mock("../components/MobileDrawer/MobileDrawer", () => ({
+ MobileDrawer: () => null,
+}));
+vi.mock("../components/MobileHeader/MobileHeader", () => ({
+ MobileHeader: () => null,
+}));
+vi.mock("../components/NotificationBanner/NotificationBanner", () => ({
+ NotificationBanner: () => null,
+}));
+vi.mock("../components/NotificationDialog/NotificationDialog", () => ({
+ NotificationDialog: () => null,
+}));
+vi.mock("../components/RateLimitResetDialog/RateLimitGate", () => ({
+ RateLimitGate: () => null,
+}));
+vi.mock("../components/FileDropZone/FileDropZone", () => ({
+ FileDropZone: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+}));
+vi.mock("../useIsMobile", () => ({
+ useIsMobile: () => false,
+}));
+vi.mock("../components/ScaleLoader/ScaleLoader", () => ({
+ ScaleLoader: () => <div data-testid="scale-loader" />,
+}));
+vi.mock("../components/ArtifactPanel/ArtifactPanel", () => ({
+ ArtifactPanel: () => null,
+}));
+vi.mock("@/components/ui/sidebar", () => ({
+ SidebarProvider: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+}));
+
+// Keep the chat host off the network — it reads useCopilotPage purely to
+// render ChatContainer (which is stubbed above).
+vi.mock("../useCopilotPage", () => ({
+ useCopilotPage: () => ({
+ sessionId: null,
+ messages: [],
+ status: "ready",
+ error: undefined,
+ stop: vi.fn(),
+ isReconnecting: false,
+ createSession: vi.fn(),
+ onSend: vi.fn(),
+ isLoadingSession: false,
+ isSessionError: false,
+ isCreatingSession: false,
+ isUploadingFiles: false,
+ hasMoreMessages: false,
+ isLoadingMore: false,
+ loadMore: vi.fn(),
+ turnStats: new Map(),
+ rateLimitMessage: null,
+ dismissRateLimit: vi.fn(),
+ sessionDryRun: false,
+ }),
+}));
+
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
+// sessionId is read via nuqs to key the chat-host subtree; stub it.
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ useQueryState: () => [null, vi.fn()],
+}));
+
+// Billing must be on for the provider to derive `isOutOfCredits`; keep the
+// real `Flag` enum so the page's other flag reads (e.g. ARTIFACTS) resolve.
+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
+ const actual =
+ await importActual<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) => flag === actual.Flag.ENABLE_PLATFORM_PAYMENT,
+ };
+});
+
+function setupCredits(credits: number) {
+ server.use(
+ getGetV1GetUserCreditsMockHandler({ credits }),
+ getGetV1GetAutoTopUpMockHandler({ amount: 0, threshold: 0 }),
+ );
+}
+
+function renderCopilotWithTopUpPrompt() {
+ return render(
+ <TopUpPromptProvider>
+ <CopilotPage />
+ </TopUpPromptProvider>,
+ );
+}
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe("Autopilot low-credit banner", () => {
+ test("shows the banner when the user is out of credits", async () => {
+ // Suppress the daily auto-opener so only the banner is under test.
+ localStorage.setItem(
+ Key.TOP_UP_MODAL_LAST_SHOWN,
+ new Date().toDateString(),
+ );
+ setupCredits(0);
+
+ renderCopilotWithTopUpPrompt();
+
+ expect(await screen.findByText(/out of automation credits/i)).toBeDefined();
+ });
+
+ test("hides the banner when the user still has credits", async () => {
+ setupCredits(500);
+
+ renderCopilotWithTopUpPrompt();
+
+ // Let the chat host mount so the page has fully rendered before asserting absence.
+ await screen.findByTestId("chat-container");
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsx
index e35514a629..068dd70f33 100644
--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx
@@ -4,6 +4,7 @@ import { PushNotificationProvider } from "@/services/push-notifications/PushNoti
import { ReactNode } from "react";
import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationBanner";
import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";
+import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
import { PaywallGate } from "./PaywallGate/PaywallGate";
export default function PlatformLayout({ children }: { children: ReactNode }) {
@@ -15,7 +16,9 @@ export default function PlatformLayout({ children }: { children: ReactNode }) {
<Navbar />
<AdminImpersonationBanner />
<section className="flex-1">
- <PaywallGate>{children}</PaywallGate>
+ <TopUpPromptProvider>
+ <PaywallGate>{children}</PaywallGate>
+ </TopUpPromptProvider>
</section>
</main>
</AutoPilotBridgeProvider>
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx
new file mode 100644
index 0000000000..3235eabd5b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { render, screen, fireEvent } from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import {
+ getGetV2ListLibraryAgentsMockHandler,
+ getGetV2ListLibraryAgentsResponseMock,
+ getGetV2ListFavoriteLibraryAgentsMockHandler,
+ getGetV2ListFavoriteLibraryAgentsResponseMock,
+} from "@/app/api/__generated__/endpoints/library/library.msw";
+import { getGetV2ListLibraryFoldersMockHandler } from "@/app/api/__generated__/endpoints/folders/folders.msw";
+import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";
+import {
+ getGetV1GetUserCreditsMockHandler,
+ getGetV1GetAutoTopUpMockHandler,
+} from "@/app/api/__generated__/endpoints/credits/credits.msw";
+import { Key } from "@/services/storage/local-storage";
+import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
+import LibraryPage from "../page";
+
+// Billing must be on for the provider to derive `isOutOfCredits`; keep the real
+// `Flag` enum so other flags the page reads (e.g. AGENT_BRIEFING) resolve.
+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
+ const actual =
+ await importActual<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) => flag === actual.Flag.ENABLE_PLATFORM_PAYMENT,
+ };
+});
+
+function setupLibraryHandlers() {
+ server.use(
+ getGetV2ListLibraryAgentsMockHandler({
+ ...getGetV2ListLibraryAgentsResponseMock(),
+ agents: [],
+ pagination: {
+ total_items: 0,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 20,
+ },
+ }),
+ getGetV2ListFavoriteLibraryAgentsMockHandler({
+ ...getGetV2ListFavoriteLibraryAgentsResponseMock(),
+ agents: [],
+ pagination: {
+ total_items: 0,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 10,
+ },
+ }),
+ getGetV2ListLibraryFoldersMockHandler({
+ folders: [],
+ pagination: {
+ total_items: 0,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 20,
+ },
+ }),
+ getGetV1ListAllExecutionsMockHandler([]),
+ );
+}
+
+function setupCredits(credits: number) {
+ server.use(
+ getGetV1GetUserCreditsMockHandler({ credits }),
+ getGetV1GetAutoTopUpMockHandler({ amount: 0, threshold: 0 }),
+ );
+}
+
+function renderLibraryWithTopUpPrompt() {
+ return render(
+ <TopUpPromptProvider>
+ <LibraryPage />
+ </TopUpPromptProvider>,
+ );
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ setupLibraryHandlers();
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe("Library low-credit banner", () => {
+ test("shows the banner when the user is out of credits", async () => {
+ // Suppress the daily auto-opener so only the banner is under test.
+ localStorage.setItem(
+ Key.TOP_UP_MODAL_LAST_SHOWN,
+ new Date().toDateString(),
+ );
+ setupCredits(0);
+
+ renderLibraryWithTopUpPrompt();
+
+ expect(await screen.findByText(/out of automation credits/i)).toBeDefined();
+ });
+
+ test("the Top up CTA opens the top-up dialog", async () => {
+ localStorage.setItem(
+ Key.TOP_UP_MODAL_LAST_SHOWN,
+ new Date().toDateString(),
+ );
+ setupCredits(0);
+
+ renderLibraryWithTopUpPrompt();
+
+ await screen.findByText(/out of automation credits/i);
+
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+
+ // The dialog body copy mentions Autopilot, which the banner copy does not —
+ // keeps this assertion unambiguous against the banner's own message.
+ expect(
+ await screen.findByText(/keep your agents and Autopilot/i),
+ ).toBeDefined();
+ });
+
+ test("hides the banner when the user still has credits", async () => {
+ setupCredits(500);
+
+ renderLibraryWithTopUpPrompt();
+
+ // Let the header render so the page has fully mounted before asserting absence.
+ await screen.findAllByTestId("import-button");
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
index 86f5b4dd8b..3ee23ea247 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
@@ -21,6 +21,7 @@ import { LibraryEmptyState } from "../LibraryEmptyState/LibraryEmptyState";
import type { LibraryTab, AgentStatusFilter, FleetSummary } from "../../types";
import { useLibraryAgentList } from "./useLibraryAgentList";
import { AgentBriefingPanel } from "../AgentBriefingPanel/AgentBriefingPanel";
+import { LowCreditBanner } from "@/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { useAgentStatusMap, getAgentStatus } from "../../hooks/useAgentStatus";
@@ -176,6 +177,11 @@ export function LibraryAgentList({
)}
<div className="pt-4">
+ {!selectedFolderId && activeTab === "all" && (
+ <div className="mb-4">
+ <LowCreditBanner />
+ </div>
+ )}
{selectedFolderId && (
<div className="mb-4 flex items-center gap-2">
<button
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletRefill.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletRefill.tsx
index 09dc752c2f..1dc8ec6f84 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletRefill.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletRefill.tsx
@@ -11,6 +11,7 @@ import {
useToast,
useToastOnFail,
} from "@/components/molecules/Toast/use-toast";
+import { TopUpForm } from "@/components/layout/TopUpPrompt/TopUpForm/TopUpForm";
import useCredits from "@/hooks/useCredits";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
@@ -18,12 +19,6 @@ import { useCallback, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
-const topUpSchema = z.object({
- amount: z
- .number({ coerce: true, invalid_type_error: "Enter top-up amount" })
- .min(5, "Top-ups start at $5. Please enter a higher amount."),
-});
-
const autoRefillSchema = z
.object({
threshold: z
@@ -46,15 +41,12 @@ export function WalletRefill() {
const { toast } = useToast();
const toastOnFail = useToastOnFail();
- const { requestTopUp, autoTopUpConfig, updateAutoTopUpConfig } = useCredits({
+ const { autoTopUpConfig, updateAutoTopUpConfig } = useCredits({
fetchInitialAutoTopUpConfig: true,
});
const [isLoading, setIsLoading] = useState(false);
- const topUpForm = useForm<z.infer<typeof topUpSchema>>({
- resolver: zodResolver(topUpSchema),
- });
const autoRefillForm = useForm<z.infer<typeof autoRefillSchema>>({
resolver: zodResolver(autoRefillSchema),
});
@@ -73,17 +65,6 @@ export function WalletRefill() {
}
}, [autoTopUpConfig, autoRefillForm]);
- const submitTopUp = useCallback(
- async (data: z.infer<typeof topUpSchema>) => {
- setIsLoading(true);
- await requestTopUp(data.amount * 100).catch(
- toastOnFail("request top-up"),
- );
- setIsLoading(false);
- },
- [requestTopUp, toastOnFail],
- );
-
const submitAutoTopUpConfig = useCallback(
async (data: z.infer<typeof autoRefillSchema>) => {
setIsLoading(true);
@@ -124,32 +105,7 @@ export function WalletRefill() {
<div className="mt-1 justify-start font-sans text-xs font-normal leading-tight text-zinc-500">
Enter an amount (min. $5) and add credits instantly.
</div>
- <Form {...topUpForm}>
- <form
- onSubmit={topUpForm.handleSubmit(submitTopUp)}
- className="my-4"
- >
- <FormField
- control={topUpForm.control}
- name="amount"
- render={({ field }) => (
- <Input
- label="Amount"
- type="amount"
- size="small"
- decimalCount={0}
- id={field.name}
- error={topUpForm.formState.errors.amount?.message}
- amountPrefix="$"
- {...field}
- />
- )}
- />
- <Button type="submit" disabled={isLoading} size="small">
- Top up
- </Button>
- </form>
- </Form>
+ <TopUpForm submitLabel="Top up" size="small" />
</TabsContent>
<TabsContent value="auto-refill" className="flex flex-col">
<div className="justify-start font-sans text-sm font-medium leading-snug text-zinc-900">
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/__tests__/WalletRefill.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/__tests__/WalletRefill.test.tsx
new file mode 100644
index 0000000000..c53a8daceb
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/__tests__/WalletRefill.test.tsx
@@ -0,0 +1,19 @@
+import { describe, expect, test } from "vitest";
+import { render, screen } from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import { getGetV1GetAutoTopUpMockHandler } from "@/app/api/__generated__/endpoints/credits/credits.msw";
+
+import { WalletRefill } from "../WalletRefill";
+
+describe("WalletRefill", () => {
+ test("renders the shared top-up form in the one-time top-up tab", async () => {
+ server.use(getGetV1GetAutoTopUpMockHandler({ amount: 0, threshold: 0 }));
+
+ render(<WalletRefill />);
+
+ // The "top-up" tab is the default, so the extracted TopUpForm (with its
+ // single "Amount" field) must render after the WalletRefill extraction.
+ expect(await screen.findByLabelText("Amount")).toBeDefined();
+ expect(screen.getByRole("button", { name: /top up/i })).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/DailyTopUpAutoOpener.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/DailyTopUpAutoOpener.tsx
new file mode 100644
index 0000000000..a5e556c160
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/DailyTopUpAutoOpener.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { useMountEffect } from "@/hooks/useMountEffect";
+import { Key } from "@/services/storage/local-storage";
+
+import { markShownToday, wasShownToday } from "./helpers";
+import { useTopUpPrompt } from "./useTopUpPrompt";
+
+export function DailyTopUpAutoOpener() {
+ const { openTopUp } = useTopUpPrompt();
+
+ useMountEffect(() => {
+ if (!wasShownToday(Key.TOP_UP_MODAL_LAST_SHOWN)) {
+ markShownToday(Key.TOP_UP_MODAL_LAST_SHOWN);
+ openTopUp();
+ }
+ });
+
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner.tsx
new file mode 100644
index 0000000000..65fc461c1c
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { XIcon } from "@phosphor-icons/react";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
+
+import { useLowCreditBanner } from "./useLowCreditBanner";
+
+interface Props {
+ className?: string;
+}
+
+export function LowCreditBanner({ className }: Props) {
+ const { visible, openTopUp, dismiss } = useLowCreditBanner();
+
+ if (!visible) return null;
+
+ const alert = (
+ <Alert variant="warning" aria-live="polite">
+ <div className="flex flex-wrap items-center gap-3">
+ <AlertDescription className="min-w-[12rem] flex-1">
+ You&apos;re out of automation credits. Top up to keep your agents
+ running.
+ </AlertDescription>
+ <Button
+ variant="primary"
+ size="small"
+ onClick={openTopUp}
+ className="border-orange-600 bg-orange-600 hover:border-orange-700 hover:bg-orange-700"
+ >
+ Top up
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={dismiss}
+ aria-label="Dismiss"
+ title="Dismiss"
+ className="hover:border-[#FFE4BF] hover:bg-[#FFE4BF]"
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ </div>
+ </Alert>
+ );
+
+ return className ? <div className={className}>{alert}</div> : alert;
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/useLowCreditBanner.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/useLowCreditBanner.ts
new file mode 100644
index 0000000000..66c29a71bb
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/LowCreditBanner/useLowCreditBanner.ts
@@ -0,0 +1,20 @@
+import { useState } from "react";
+
+import { Key } from "@/services/storage/local-storage";
+
+import { markShownToday, wasShownToday } from "../helpers";
+import { useTopUpPrompt } from "../useTopUpPrompt";
+
+export function useLowCreditBanner() {
+ const { isOutOfCredits, openTopUp } = useTopUpPrompt();
+ const [dismissed, setDismissed] = useState(() =>
+ wasShownToday(Key.LOW_CREDIT_BANNER_DISMISSED),
+ );
+
+ function dismiss() {
+ markShownToday(Key.LOW_CREDIT_BANNER_DISMISSED);
+ setDismissed(true);
+ }
+
+ return { visible: isOutOfCredits && !dismissed, openTopUp, dismiss };
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx
new file mode 100644
index 0000000000..74955d4f4a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { AlertTriangleIcon } from "lucide-react";
+import Link from "next/link";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+
+import { TopUpForm } from "../TopUpForm/TopUpForm";
+
+interface Props {
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+export function TopUpDialog({ isOpen, onClose }: Props) {
+ function handleOpenChange(open: boolean) {
+ if (!open) onClose();
+ }
+
+ return (
+ <Dialog
+ title={
+ <span className="inline-flex items-center gap-2">
+ <AlertTriangleIcon className="h-[1.125rem] w-[1.125rem] text-orange-600" />
+ You&apos;re out of automation credits
+ </span>
+ }
+ styling={{ maxWidth: "28rem" }}
+ controlled={{ isOpen, set: handleOpenChange }}
+ >
+ <Dialog.Content>
+ <Text variant="large">
+ Top up to keep your agents and Autopilot running. You can also{" "}
+ <Link href="/settings/billing" className="underline">
+ enable auto-refill in billing settings
+ </Link>
+ .
+ </Text>
+ <TopUpForm submitLabel="Top up" />
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx
new file mode 100644
index 0000000000..a3eb97cbbf
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx
@@ -0,0 +1,39 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Form, FormField } from "@/components/molecules/Form/Form";
+import { useTopUpForm } from "./useTopUpForm";
+
+interface Props {
+ submitLabel?: string;
+ size?: "small" | "normal";
+}
+
+export function TopUpForm({ submitLabel = "Top up", size = "normal" }: Props) {
+ const { form, isLoading, submitTopUp } = useTopUpForm();
+ const inputSize = size === "small" ? "small" : "medium";
+ const buttonSize = size === "small" ? "small" : "large";
+
+ return (
+ <Form form={form} onSubmit={submitTopUp} className="my-4">
+ <FormField
+ control={form.control}
+ name="amount"
+ render={({ field }) => (
+ <Input
+ label="Amount"
+ type="amount"
+ size={inputSize}
+ decimalCount={0}
+ id={field.name}
+ error={form.formState.errors.amount?.message}
+ amountPrefix="$"
+ {...field}
+ />
+ )}
+ />
+ <Button type="submit" disabled={isLoading} size={buttonSize}>
+ {isLoading ? "Redirecting…" : submitLabel}
+ </Button>
+ </Form>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx
new file mode 100644
index 0000000000..bdce65975c
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx
@@ -0,0 +1,71 @@
+import { describe, expect, test } from "vitest";
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import { getPostV1RequestCreditTopUpMockHandler } from "@/app/api/__generated__/endpoints/credits/credits.msw";
+
+import { TopUpForm } from "../TopUpForm";
+
+function captureTopUpRequest() {
+ let body: unknown = null;
+ server.use(
+ getPostV1RequestCreditTopUpMockHandler(
+ async (info: { request: Request }) => {
+ body = await info.request.json();
+ },
+ ),
+ );
+ return { getBody: () => body };
+}
+
+describe("TopUpForm", () => {
+ test("submits the entered amount converted to cents", async () => {
+ const { getBody } = captureTopUpRequest();
+
+ render(<TopUpForm />);
+
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "15" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+
+ await waitFor(() => expect(getBody()).toEqual({ credit_amount: 1500 }));
+ });
+
+ test("rejects amounts below the $5 minimum without calling the API", async () => {
+ const { getBody } = captureTopUpRequest();
+
+ render(<TopUpForm />);
+
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "3" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+
+ expect(await screen.findByText(/Top-ups start at \$5/i)).toBeDefined();
+ expect(getBody()).toBeNull();
+ });
+
+ test("disables the submit button while the checkout request is in flight", async () => {
+ // Hold the request open so the in-flight loading state is observable.
+ server.use(
+ getPostV1RequestCreditTopUpMockHandler(
+ () => new Promise((resolve) => setTimeout(resolve, 300)),
+ ),
+ );
+
+ render(<TopUpForm />);
+
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "15" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+
+ const button = await screen.findByRole("button", { name: /redirecting/i });
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts
new file mode 100644
index 0000000000..0f712ccb12
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts
@@ -0,0 +1,36 @@
+import { useToastOnFail } from "@/components/molecules/Toast/use-toast";
+import useCredits from "@/hooks/useCredits";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+const topUpSchema = z.object({
+ amount: z
+ .number({ coerce: true, invalid_type_error: "Enter top-up amount" })
+ .min(5, "Top-ups start at $5. Please enter a higher amount."),
+});
+
+export function useTopUpForm() {
+ const toastOnFail = useToastOnFail();
+ const { requestTopUp } = useCredits();
+
+ const [isLoading, setIsLoading] = useState(false);
+
+ const form = useForm<z.infer<typeof topUpSchema>>({
+ resolver: zodResolver(topUpSchema),
+ });
+
+ async function submitTopUp(data: z.infer<typeof topUpSchema>) {
+ setIsLoading(true);
+ await requestTopUp(data.amount * 100)
+ .catch(toastOnFail("request top-up"))
+ .finally(() => setIsLoading(false));
+ }
+
+ return {
+ form,
+ isLoading,
+ submitTopUp,
+ };
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx
new file mode 100644
index 0000000000..23bc810736
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { ReactNode, useState } from "react";
+
+import useCredits from "@/hooks/useCredits";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+
+import { DailyTopUpAutoOpener } from "./DailyTopUpAutoOpener";
+import { TopUpDialog } from "./TopUpDialog/TopUpDialog";
+import { TopUpPromptContext } from "./useTopUpPrompt";
+
+interface Props {
+ children: ReactNode;
+}
+
+export function TopUpPromptProvider({ children }: Props) {
+ const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
+ const { credits, autoTopUpConfig } = useCredits({
+ fetchInitialCredits: true,
+ fetchInitialAutoTopUpConfig: true,
+ });
+
+ // Backend treats amount === 0 as disabled, so auto-refill only actually
+ // refills when amount > 0; suppress the nudge only then.
+ const autoRefillEnabled = !!autoTopUpConfig && autoTopUpConfig.amount > 0;
+ // Requiring `autoTopUpConfig !== null` serves two purposes. Both fetches
+ // resolve independently, so it avoids a user with auto-refill enabled briefly
+ // looking out-of-credits (config still null) and firing the daily modal
+ // spuriously. It is also fail-closed by design: if GET /credits/auto-top-up
+ // errors, autoTopUpConfig stays null and the prompt stays hidden, rather than
+ // risk nudging a user who actually has auto-refill enabled.
+ const isOutOfCredits =
+ !!isBillingEnabled &&
+ credits !== null &&
+ credits <= 0 &&
+ autoTopUpConfig !== null &&
+ !autoRefillEnabled;
+
+ const [isOpen, setIsOpen] = useState(false);
+
+ function openTopUp() {
+ setIsOpen(true);
+ }
+
+ function closeTopUp() {
+ setIsOpen(false);
+ }
+
+ return (
+ <TopUpPromptContext.Provider
+ value={{ isOutOfCredits, openTopUp, closeTopUp }}
+ >
+ {children}
+ <TopUpDialog isOpen={isOpen} onClose={closeTopUp} />
+ {isOutOfCredits && <DailyTopUpAutoOpener />}
+ </TopUpPromptContext.Provider>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx
new file mode 100644
index 0000000000..1080f243d9
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx
@@ -0,0 +1,243 @@
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import {
+ getGetV1GetUserCreditsMockHandler,
+ getGetV1GetAutoTopUpMockHandler,
+} from "@/app/api/__generated__/endpoints/credits/credits.msw";
+import { Key } from "@/services/storage/local-storage";
+import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
+import { LowCreditBanner } from "@/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner";
+import { useTopUpPrompt } from "@/components/layout/TopUpPrompt/useTopUpPrompt";
+
+// Billing must be on for the provider to derive `isOutOfCredits`; keep the real
+// `Flag` enum and let each test toggle whether the flag resolves true.
+let isBillingEnabled = true;
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
+ const actual =
+ await importActual<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === actual.Flag.ENABLE_PLATFORM_PAYMENT ? isBillingEnabled : false,
+ };
+});
+
+function setupCredits(args: {
+ credits: number;
+ amount: number;
+ threshold: number;
+}) {
+ let creditsRequested = false;
+ let autoTopUpRequested = false;
+ server.use(
+ getGetV1GetUserCreditsMockHandler(() => {
+ creditsRequested = true;
+ return { credits: args.credits };
+ }),
+ getGetV1GetAutoTopUpMockHandler(() => {
+ autoTopUpRequested = true;
+ return { amount: args.amount, threshold: args.threshold };
+ }),
+ );
+ return {
+ waitForCreditsFetch: () =>
+ waitFor(() => {
+ expect(creditsRequested).toBe(true);
+ expect(autoTopUpRequested).toBe(true);
+ }),
+ };
+}
+
+function renderProvider() {
+ return render(
+ <TopUpPromptProvider>
+ <div>ready</div>
+ <LowCreditBanner />
+ </TopUpPromptProvider>,
+ );
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ isBillingEnabled = true;
+});
+
+afterEach(() => {
+ localStorage.clear();
+});
+
+describe("TopUpPromptProvider daily auto-opener", () => {
+ test("auto-opens the top-up dialog once when out of credits", async () => {
+ setupCredits({ credits: 0, amount: 0, threshold: 0 });
+
+ renderProvider();
+
+ // The dialog body copy mentions Autopilot, which the banner copy does not,
+ // so it unambiguously signals the dialog auto-opened.
+ expect(
+ await screen.findByText(/keep your agents and Autopilot/i),
+ ).toBeDefined();
+ });
+
+ test("does not auto-open when the modal was already shown today", async () => {
+ localStorage.setItem(
+ Key.TOP_UP_MODAL_LAST_SHOWN,
+ new Date().toDateString(),
+ );
+ setupCredits({ credits: 0, amount: 0, threshold: 0 });
+
+ renderProvider();
+
+ // The banner is a separate concern and still shows; awaiting it proves the
+ // credit fetch resolved before we assert the dialog is absent.
+ await screen.findByText(/out of automation credits/i);
+
+ expect(screen.queryByText(/keep your agents and Autopilot/i)).toBeNull();
+ });
+});
+
+describe("LowCreditBanner dismissal", () => {
+ test("hides the banner for the day and records the dismissal date", async () => {
+ // Suppress the daily auto-opener so only the banner dismissal is under test.
+ localStorage.setItem(
+ Key.TOP_UP_MODAL_LAST_SHOWN,
+ new Date().toDateString(),
+ );
+ setupCredits({ credits: 0, amount: 0, threshold: 0 });
+
+ renderProvider();
+
+ await screen.findByText(/out of automation credits/i);
+
+ fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));
+
+ await waitFor(() =>
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull(),
+ );
+ expect(localStorage.getItem(Key.LOW_CREDIT_BANNER_DISMISSED)).toBe(
+ new Date().toDateString(),
+ );
+ });
+});
+
+describe("useTopUpPrompt without a provider", () => {
+ test("falls back to an inert value instead of throwing", () => {
+ function Consumer() {
+ const { isOutOfCredits, openTopUp, closeTopUp } = useTopUpPrompt();
+ return (
+ <button
+ onClick={() => {
+ openTopUp();
+ closeTopUp();
+ }}
+ >
+ {isOutOfCredits ? "out of credits" : "has credits"}
+ </button>
+ );
+ }
+
+ render(<Consumer />);
+
+ const button = screen.getByRole("button");
+ expect(button.textContent).toBe("has credits");
+ // The inert openTopUp/closeTopUp must be safe no-ops.
+ fireEvent.click(button);
+ expect(button.textContent).toBe("has credits");
+ });
+});
+
+describe("TopUpPromptProvider out-of-credits suppression", () => {
+ test("suppresses dialog and banner when auto-refill is enabled", async () => {
+ const { waitForCreditsFetch } = setupCredits({
+ credits: 0,
+ amount: 1000,
+ threshold: 500,
+ });
+
+ renderProvider();
+
+ // What actually keeps the banner/dialog out here is the invariant: with
+ // auto-refill enabled, `isOutOfCredits` is permanently false, so nothing can
+ // appear regardless of fetch timing. `waitForCreditsFetch` only gates on
+ // both backend reads (credits + auto-top-up) being intercepted (not on
+ // state being applied to the tree), kept as belt-and-suspenders so the
+ // assertions don't run on a bare initial mount.
+ await screen.findByText("ready");
+ await waitForCreditsFetch();
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ expect(screen.queryByText(/keep your agents and Autopilot/i)).toBeNull();
+ });
+
+ test("renders nothing when the billing flag is off", async () => {
+ isBillingEnabled = false;
+ const { waitForCreditsFetch } = setupCredits({
+ credits: 0,
+ amount: 0,
+ threshold: 0,
+ });
+
+ renderProvider();
+
+ // With the billing flag off, `isOutOfCredits` is permanently false — the
+ // invariant that keeps banner/dialog out, independent of fetch timing.
+ // `waitForCreditsFetch` only confirms both backend reads were intercepted
+ // (not that state was applied), kept as belt-and-suspenders.
+ await screen.findByText("ready");
+ await waitForCreditsFetch();
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ expect(screen.queryByText(/keep your agents and Autopilot/i)).toBeNull();
+ });
+
+ test("renders nothing when the user still has a positive balance", async () => {
+ const { waitForCreditsFetch } = setupCredits({
+ credits: 500,
+ amount: 0,
+ threshold: 0,
+ });
+
+ renderProvider();
+
+ await screen.findByText("ready");
+ await waitForCreditsFetch();
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ expect(screen.queryByText(/keep your agents and Autopilot/i)).toBeNull();
+ });
+
+ test("suppresses the prompt when the credits fetch fails", async () => {
+ // Simulates a transient backend error on GET /credits. The client used to
+ // silently treat this as a `$0` balance, which fired the out-of-credits
+ // prompt on any API failure. Returning `null` from `getUserCredit` on
+ // error keeps the provider's `credits !== null` guard short-circuiting.
+ let autoTopUpRequested = false;
+ server.use(
+ http.get("*/api/v1/credits", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ getGetV1GetAutoTopUpMockHandler(() => {
+ autoTopUpRequested = true;
+ return { amount: 0, threshold: 0 };
+ }),
+ );
+
+ renderProvider();
+
+ await screen.findByText("ready");
+ await waitFor(() => expect(autoTopUpRequested).toBe(true));
+
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull();
+ expect(screen.queryByText(/keep your agents and Autopilot/i)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..6d720a0cfc
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/helpers.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it, beforeEach } from "vitest";
+import { storage, Key } from "@/services/storage/local-storage";
+import { wasShownToday, markShownToday } from "../helpers";
+
+describe("TopUpPrompt date helpers", () => {
+ beforeEach(() => storage.clean(Key.TOP_UP_MODAL_LAST_SHOWN));
+
+ it("returns false when never shown", () => {
+ expect(wasShownToday(Key.TOP_UP_MODAL_LAST_SHOWN)).toBe(false);
+ });
+
+ it("returns true after marking today", () => {
+ markShownToday(Key.TOP_UP_MODAL_LAST_SHOWN);
+ expect(wasShownToday(Key.TOP_UP_MODAL_LAST_SHOWN)).toBe(true);
+ });
+
+ it("returns false for a stale (yesterday) stamp", () => {
+ const yesterday = new Date(Date.now() - 86_400_000).toDateString();
+ storage.set(Key.TOP_UP_MODAL_LAST_SHOWN, yesterday);
+ expect(wasShownToday(Key.TOP_UP_MODAL_LAST_SHOWN)).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/helpers.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/helpers.ts
new file mode 100644
index 0000000000..7006d66b94
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/helpers.ts
@@ -0,0 +1,9 @@
+import { storage, Key } from "@/services/storage/local-storage";
+
+export function wasShownToday(key: Key): boolean {
+ return storage.get(key) === new Date().toDateString();
+}
+
+export function markShownToday(key: Key): void {
+ storage.set(key, new Date().toDateString());
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/useTopUpPrompt.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/useTopUpPrompt.ts
new file mode 100644
index 0000000000..fcc9247f39
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/useTopUpPrompt.ts
@@ -0,0 +1,24 @@
+import { createContext, useContext } from "react";
+
+interface TopUpPromptContextValue {
+ isOutOfCredits: boolean;
+ openTopUp: () => void;
+ closeTopUp: () => void;
+}
+
+export const TopUpPromptContext = createContext<TopUpPromptContextValue | null>(
+ null,
+);
+
+// The prompt is an optional enhancement, so consumers rendered without a
+// provider (e.g. a page tested outside the platform layout) fall back to an
+// inert value rather than crashing the host page.
+const inertPrompt: TopUpPromptContextValue = {
+ isOutOfCredits: false,
+ openTopUp: () => {},
+ closeTopUp: () => {},
+};
+
+export function useTopUpPrompt() {
+ return useContext(TopUpPromptContext) ?? inertPrompt;
+}
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 98178a5c19..9cabb5a888 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -137,7 +137,7 @@ export default class BackendAPI {
/////////////// CREDITS ////////////////
////////////////////////////////////////
- async getUserCredit(): Promise<{ credits: number }> {
+ async getUserCredit(): Promise<{ credits: number | null }> {
try {
const response = await this._get("/credits");
return response ?? { credits: 0 };
@@ -145,7 +145,10 @@ export default class BackendAPI {
if (!(error instanceof LogoutInterruptError)) {
Sentry.captureException(error);
}
- return { credits: 0 };
+ // Return null (rather than 0) so callers can distinguish a real $0
+ // balance from a failed fetch — used by TopUpPromptProvider to avoid
+ // nudging users to top up on transient API errors.
+ return { credits: null };
}
}
diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.ts
index 29762fa680..5d732bd9d2 100644
--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts
+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts
@@ -21,6 +21,8 @@ export enum Key {
COPILOT_COMPLETED_SESSIONS = "copilot-completed-sessions",
PUSH_SUBSCRIPTION_REGISTERED = "push-subscription-registered",
COPILOT_DRY_RUN = "copilot-dry-run",
+ TOP_UP_MODAL_LAST_SHOWN = "top-up-modal-last-shown",
+ LOW_CREDIT_BANNER_DISMISSED = "low-credit-banner-dismissed",
}
function get(key: Key) {