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): compact wallet popover for the new layout (#13699)

Abhimanyu Yadav9d3019630183
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx
index ecb0f1844d..4160fd9cc2 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/Wallet.tsx
@@ -5,356 +5,128 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/__legacy__/ui/popover";
-import { ScrollArea } from "@/components/__legacy__/ui/scroll-area";
import { Text } from "@/components/atoms/Text/Text";
-import useCredits from "@/hooks/useCredits";
-import {
- OnboardingStep,
- WebSocketNotification,
-} from "@/lib/autogpt-server-api";
+import { TopUpDialog } from "@/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog";
import { cn } from "@/lib/utils";
-import { useOnboarding } from "@/providers/onboarding/onboarding-provider";
-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { WalletIcon } from "@phosphor-icons/react";
-import { PopoverClose } from "@radix-ui/react-popover";
-import { X } from "lucide-react";
-import confetti, { type Options as ConfettiOptions } from "canvas-confetti";
-import { AGPT_CONFETTI_COLORS } from "@/components/molecules/Confetti/Confetti";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { WalletRefill } from "./components/WalletRefill";
-import { TaskGroups } from "./components/WalletTaskGroups";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-
-export interface Task {
- id: OnboardingStep;
- name: string;
- amount: number;
- details: string;
- video?: string;
- progress?: {
- current: number;
- target: number;
- };
-}
-export interface TaskGroup {
- name: string;
- details: string;
- tasks: Task[];
-}
+import { WalletCompactPanel } from "./components/WalletCompactPanel";
+import { WalletFullPanel } from "./components/WalletFullPanel";
+import { useWallet } from "./useWallet";
interface Props {
compact?: boolean;
}
export function Wallet({ compact = false }: Props) {
- const { state, updateState } = useOnboarding();
- const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
-
- const groups = useMemo<TaskGroup[]>(() => {
- return [
- {
- name: "First Wins",
- details: "Kickstart your journey with quick wins.",
- tasks: [
- {
- id: "VISIT_COPILOT",
- name: "Complete onboarding",
- amount: 3,
- details: "",
- },
- {
- id: "MARKETPLACE_ADD_AGENT",
- name: "Get an agent from the marketplace",
- amount: 1,
- details:
- "Search for an agent in the Marketplace and add it to your Library",
- video: "/onboarding/marketplace-add.mp4",
- },
- {
- id: "MARKETPLACE_RUN_AGENT",
- name: "Open the Library page and run an agent",
- amount: 1,
- details: "Go to the Library, open an agent you want, and run it",
- video: "/onboarding/agent-run.mp4",
- },
- ],
- },
- {
- name: "Consistency Challenge",
- details: "Build your rhythm and make agents part of your routine.",
- tasks: [
- {
- id: "SCHEDULE_AGENT",
- name: "Schedule your first agent",
- amount: 1,
- details: "Schedule an agent to run on a recurring basis",
- video: "/onboarding/agent-schedule.mp4",
- },
- {
- id: "RUN_3_DAYS",
- name: "Run agents 3 days in a row",
- amount: 1,
- details:
- "Run any agents from the Library or Builder for 3 days in a row",
- progress: {
- current: state?.consecutiveRunDays || 0,
- target: 3,
- },
- },
- ],
- },
- {
- name: "The Pro Playground",
- details: "Master powerful features to supercharge your workflow.",
- tasks: [
- {
- id: "TRIGGER_WEBHOOK",
- name: "Trigger an agent via webhook",
- amount: 1,
- details:
- "In the Builder, go to Settings and copy the Webhook URL. Use it to trigger your agent from another app.",
- },
- {
- id: "RUN_14_DAYS",
- name: "Run agents 14 days in a row",
- amount: 1,
- details:
- "Run any agents from the Library or Builder for 14 days in a row",
- progress: {
- current: state?.consecutiveRunDays || 0,
- target: 14,
- },
- },
- {
- id: "RUN_AGENTS_100",
- name: "Complete 100 agent runs",
- amount: 1,
- details: "Let your agents run and complete 100 tasks in total",
- progress: {
- current: state?.agentRuns || 0,
- target: 100,
- },
- },
- ],
- },
- ];
- }, [state]);
-
- const api = useBackendAPI();
- const { credits, formatCredits, fetchCredits } = useCredits({
- fetchInitialCredits: true,
- });
-
- const [prevCredits, setPrevCredits] = useState<number | null>(credits);
- const [flash, setFlash] = useState(false);
- const [walletOpen, setWalletOpen] = useState(false);
-
- const totalCount = useMemo(() => {
- return groups.reduce((acc, group) => acc + group.tasks.length, 0);
- }, [groups]);
-
- // Total completed task count across all groups
- const [completedCount, setCompletedCount] = useState<number | null>(null);
-
- const walletRef = useRef<HTMLButtonElement | null>(null);
-
- useEffect(() => {
- if (!state) {
- return;
- }
- const completed = groups.reduce(
- (acc, group) =>
- acc +
- group.tasks.filter((task) => state?.completedSteps?.includes(task.id))
- .length,
- 0,
- );
- setCompletedCount(completed);
- }, [groups, state?.completedSteps]);
-
- const onWalletOpen = useCallback(async () => {
- if (!state?.walletShown) {
- updateState({ walletShown: true });
- }
- // Refresh credits when the wallet is opened
- fetchCredits();
- }, [state?.walletShown, updateState, fetchCredits]);
-
- // React to onboarding notifications emitted by the provider
- const handleNotification = useCallback(
- (notification: WebSocketNotification) => {
- if (
- notification.type !== "onboarding" ||
- notification.event !== "step_completed"
- ) {
- return;
- }
-
- // Always refresh credits when any onboarding step completes
- fetchCredits();
-
- // Only trigger confetti for tasks that are in displayed groups
- if (!walletRef.current) {
- return;
- }
- const taskIds = groups
- .flatMap((group) => group.tasks)
- .map((task) => task.id);
- if (!taskIds.includes(notification.step as OnboardingStep)) {
- return;
- }
-
- const rect = walletRef.current.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) {
- return;
- }
-
- const origin = {
- x: (rect.left + rect.width / 2) / window.innerWidth,
- y: (rect.top + rect.height / 2) / window.innerHeight,
- };
- const shared: ConfettiOptions = {
- particleCount: 50,
- spread: 70,
- shapes: ["square"],
- scalar: 1.2,
- startVelocity: 20,
- gravity: 0.6,
- decay: 0.92,
- ticks: 100,
- colors: AGPT_CONFETTI_COLORS,
- origin,
- };
- confetti({ ...shared, angle: 45 });
- confetti({ ...shared, angle: 135 });
- },
- [fetchCredits, groups],
- );
-
- // WebSocket setup for onboarding notifications
- useEffect(() => {
- const detachMessage = api.onWebSocketMessage(
- "notification",
- handleNotification,
- );
-
- api.connectWebSocket();
-
- return () => {
- detachMessage();
- };
- }, [api, handleNotification]);
-
- // Wallet flash on credits change
- useEffect(() => {
- if (credits === prevCredits) {
- return;
- }
- setPrevCredits(credits);
- if (prevCredits === null) {
- return;
- }
- setFlash(true);
- setTimeout(() => {
- setFlash(false);
- }, 300);
- }, [credits, prevCredits]);
+ const {
+ state,
+ groups,
+ credits,
+ formatCredits,
+ flash,
+ walletOpen,
+ setWalletOpen,
+ onWalletOpen,
+ walletRef,
+ completedCount,
+ totalCount,
+ topUpOpen,
+ onAddCredits,
+ onTopUpClose,
+ } = useWallet();
// Do not render until we have both credits and onboarding data
if (credits === null || !state) return null;
return (
- <Popover open={walletOpen} onOpenChange={(open) => setWalletOpen(open)}>
- <PopoverTrigger asChild>
- <div className="relative inline-block">
- <button
- ref={walletRef}
- className={cn(
- "group relative flex flex-nowrap items-center gap-2 rounded-md px-3 py-2 text-sm",
- compact
- ? "h-8 rounded-lg px-2 py-0 transition-colors hover:bg-zinc-100"
- : "bg-zinc-50",
- )}
- onClick={onWalletOpen}
- >
- <WalletIcon
- size={20}
- className={cn("inline-block", !compact && "xl:hidden")}
- />
- <div>
- {!compact && (
- <span className="mr-1 hidden xl:inline-block">
- Earn credits{" "}
- </span>
+ <>
+ <Popover open={walletOpen} onOpenChange={(open) => setWalletOpen(open)}>
+ <PopoverTrigger asChild>
+ <div className="relative inline-block">
+ <button
+ ref={walletRef}
+ className={cn(
+ "group relative flex flex-nowrap items-center gap-2 rounded-md px-3 py-2 text-sm",
+ compact
+ ? "h-8 rounded-lg px-2 py-0 transition-colors hover:bg-zinc-100"
+ : "bg-zinc-50",
)}
- <span
- className={cn(
- compact ? "text-xs font-medium" : "text-sm font-semibold",
+ onClick={onWalletOpen}
+ >
+ <WalletIcon
+ size={20}
+ className={cn("inline-block", !compact && "xl:hidden")}
+ />
+ <div>
+ {!compact && (
+ <span className="mr-1 hidden xl:inline-block">
+ Earn credits{" "}
+ </span>
)}
- >
- {formatCredits(credits)}
- </span>
- {!compact &&
- completedCount !== null &&
- completedCount < totalCount && (
- <span className="absolute right-1 top-1 h-2 w-2 rounded-full bg-violet-600"></span>
+ <span
+ className={cn(
+ compact ? "text-xs font-medium" : "text-sm font-semibold",
+ )}
+ >
+ {formatCredits(credits)}
+ </span>
+ {!compact &&
+ completedCount !== null &&
+ completedCount < totalCount && (
+ <span className="absolute right-1 top-1 h-2 w-2 rounded-full bg-violet-600"></span>
+ )}
+ {!compact && (
+ <div className="absolute bottom-[-2.5rem] left-1/2 z-50 hidden -translate-x-1/2 transform whitespace-nowrap rounded-small bg-white px-4 py-2 shadow-md group-hover:block">
+ <Text variant="body-medium">
+ {completedCount} of {totalCount} rewards claimed
+ </Text>
+ </div>
)}
- {!compact && (
- <div className="absolute bottom-[-2.5rem] left-1/2 z-50 hidden -translate-x-1/2 transform whitespace-nowrap rounded-small bg-white px-4 py-2 shadow-md group-hover:block">
- <Text variant="body-medium">
- {completedCount} of {totalCount} rewards claimed
- </Text>
- </div>
+ </div>
+ </button>
+ <div
+ className={cn(
+ "pointer-events-none absolute inset-0 bg-violet-400 duration-2000 ease-in-out",
+ compact ? "rounded-lg" : "rounded-md",
+ flash ? "opacity-50 duration-0" : "opacity-0",
)}
- </div>
- </button>
- <div
- className={cn(
- "pointer-events-none absolute inset-0 bg-violet-400 duration-2000 ease-in-out",
- compact ? "rounded-lg" : "rounded-md",
- flash ? "opacity-50 duration-0" : "opacity-0",
- )}
- />
- </div>
- </PopoverTrigger>
- <PopoverContent
- side="bottom"
- align="end"
- collisionPadding={16}
- className={cn("relative -top-12 z-50 w-[28.5rem] px-4 py-4")}
- >
- {/* Header */}
- <div className="mx-1 flex items-start justify-between gap-3 border-b border-zinc-200 pb-3">
- <div className="flex min-w-0 flex-col gap-1">
- <span className="font-poppins text-base font-semibold text-zinc-900">
- Automation Credits
- </span>
- <span className="font-sans text-xs text-zinc-500">
- Platform-only credits for automations. This is separate from your
- subscription and is not usable for plan fees.
- </span>
- </div>
- <div className="flex shrink-0 items-center text-sm text-violet-700">
- <div className="rounded-lg bg-violet-100 px-3 py-2">
- Earn credits{" "}
- <span className="font-semibold">{formatCredits(credits)}</span>
- </div>
- <PopoverClose aria-label="Close wallet">
- <X className="ml-2 h-5 w-5 text-zinc-800 hover:text-foreground" />
- </PopoverClose>
+ />
</div>
- </div>
- <ScrollArea className="max-h-[85vh] overflow-y-auto">
- {/* Top ups */}
- {isPaymentEnabled && <WalletRefill />}
- {/* Tasks */}
- <p className="mx-1 my-3 font-sans text-xs font-normal text-zinc-400">
- Complete the following tasks to earn more credits!
- </p>
- <TaskGroups groups={groups} />
- </ScrollArea>
- </PopoverContent>
- </Popover>
+ </PopoverTrigger>
+ <PopoverContent
+ side={compact ? "top" : "bottom"}
+ align={compact ? "start" : "end"}
+ collisionPadding={16}
+ className={cn(
+ "z-50",
+ compact
+ ? "w-[22rem] rounded-2xlarge p-2"
+ : "relative -top-12 w-[28.5rem] px-4 py-4",
+ )}
+ >
+ {compact ? (
+ <WalletCompactPanel
+ groups={groups}
+ completedSteps={state.completedSteps}
+ formattedCredits={formatCredits(credits)}
+ onAddCredits={onAddCredits}
+ />
+ ) : (
+ <WalletFullPanel
+ groups={groups}
+ formattedCredits={formatCredits(credits)}
+ />
+ )}
+ </PopoverContent>
+ </Popover>
+ {compact && (
+ <TopUpDialog
+ isOpen={topUpOpen}
+ onClose={onTopUpClose}
+ variant="add-credits"
+ />
+ )}
+ </>
);
}
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx
new file mode 100644
index 0000000000..1471de3074
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx
@@ -0,0 +1,262 @@
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import {
+ UserOnboarding,
+ WebSocketNotification,
+} from "@/lib/autogpt-server-api";
+import userEvent from "@testing-library/user-event";
+import { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { Wallet } from "../Wallet";
+
+const confettiMock = vi.hoisted(() => vi.fn());
+const fetchCreditsMock = vi.hoisted(() => vi.fn());
+const updateStateMock = vi.hoisted(() => vi.fn());
+const connectWebSocketMock = vi.hoisted(() => vi.fn());
+const detachMessageMock = vi.hoisted(() => vi.fn());
+const onWebSocketMessageMock = vi.hoisted(() => vi.fn());
+
+const creditsState = vi.hoisted(() => ({ credits: 979 as number | null }));
+const onboardingState = vi.hoisted(() => ({
+ state: null as UserOnboarding | null,
+}));
+
+vi.mock("canvas-confetti", () => ({ default: confettiMock }));
+
+vi.mock("@/hooks/useCredits", () => ({
+ default: () => ({
+ credits: creditsState.credits,
+ fetchCredits: fetchCreditsMock,
+ formatCredits: (credit: number | null) =>
+ credit === null ? "-" : `$${(credit / 100).toFixed(2)}`,
+ requestTopUp: vi.fn(),
+ refundTopUp: vi.fn(),
+ autoTopUpConfig: null,
+ fetchAutoTopUpConfig: vi.fn(),
+ updateAutoTopUpConfig: vi.fn(),
+ transactionHistory: { transactions: [], next_transaction_time: null },
+ fetchTransactionHistory: vi.fn(),
+ refundRequests: [],
+ fetchRefundRequests: vi.fn(),
+ }),
+}));
+
+// The real provider opens its own "notification" subscription and drives
+// onboarding redirects — neither is under test here, so stub it out entirely.
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => children,
+ useOnboarding: () => ({
+ state: onboardingState.state,
+ updateState: updateStateMock,
+ step: 1,
+ setStep: vi.fn(),
+ completeStep: vi.fn(),
+ }),
+}));
+
+// The identity has to be stable: the real context hands out one client, and
+// the websocket effect is keyed on it.
+const backendAPI = vi.hoisted(() => ({}) as Record<string, unknown>);
+
+vi.mock("@/lib/autogpt-server-api/context", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@/lib/autogpt-server-api/context")>();
+ return { ...actual, useBackendAPI: () => backendAPI };
+});
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return { ...actual, useGetFlag: vi.fn(() => true) };
+});
+
+function buildOnboarding(
+ overrides: Partial<UserOnboarding> = {},
+): UserOnboarding {
+ return {
+ completedSteps: ["VISIT_COPILOT"],
+ walletShown: false,
+ notified: [],
+ rewardedFor: [],
+ usageReason: null,
+ integrations: [],
+ otherIntegrations: null,
+ selectedStoreListingVersionId: null,
+ agentInput: null,
+ onboardingAgentExecutionId: null,
+ lastRunAt: null,
+ consecutiveRunDays: 0,
+ agentRuns: 0,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ onWebSocketMessageMock.mockReturnValue(detachMessageMock);
+ backendAPI.onWebSocketMessage = onWebSocketMessageMock;
+ backendAPI.connectWebSocket = connectWebSocketMock;
+ creditsState.credits = 979;
+ onboardingState.state = buildOnboarding();
+
+ // happy-dom has no layout, so the wallet button measures 0×0 and the
+ // confetti burst would bail out before firing.
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue({
+ ...new DOMRect(),
+ top: 10,
+ left: 20,
+ width: 100,
+ height: 40,
+ });
+});
+
+describe("Wallet", () => {
+ it("renders nothing until credits and onboarding state are both available", () => {
+ creditsState.credits = null;
+ const { container } = render(<Wallet />);
+
+ expect(container.innerHTML).toBe("");
+ });
+
+ it("shows the balance and the unclaimed-reward dot in the classic navbar", () => {
+ render(<Wallet />);
+
+ expect(screen.getByText("$9.79")).toBeDefined();
+ expect(screen.getByText("Earn credits")).toBeDefined();
+ expect(screen.getByText(/1 of 8 rewards claimed/)).toBeDefined();
+ });
+
+ it("hides the reward dot and tooltip in compact mode", () => {
+ render(<Wallet compact />);
+
+ expect(screen.getByText("$9.79")).toBeDefined();
+ expect(screen.queryByText(/rewards claimed/)).toBeNull();
+ });
+
+ it("opens the full panel and marks the wallet as shown", async () => {
+ render(<Wallet />);
+
+ await userEvent.click(screen.getByRole("button"));
+
+ expect(await screen.findByText("Automation Credits")).toBeDefined();
+ expect(screen.getByText(/Complete the following tasks/)).toBeDefined();
+ expect(updateStateMock).toHaveBeenCalledWith({ walletShown: true });
+ expect(fetchCreditsMock).toHaveBeenCalled();
+ });
+
+ it("opens the compact panel and swaps it for the add-credits dialog", async () => {
+ render(<Wallet compact />);
+
+ await userEvent.click(screen.getByRole("button"));
+
+ expect(await screen.findByText("Automation credits")).toBeDefined();
+
+ await userEvent.click(screen.getByRole("button", { name: "Add credits" }));
+
+ expect(await screen.findByText("Add automation credits")).toBeDefined();
+ expect(screen.queryByText("Earn credits")).toBeNull();
+
+ await userEvent.keyboard("{Escape}");
+
+ await waitFor(() => {
+ expect(screen.queryByText("Add automation credits")).toBeNull();
+ });
+ });
+
+ it("flashes the balance when the credit total changes", () => {
+ const { container, rerender } = render(<Wallet />);
+ const overlay = container.querySelector(".bg-violet-400");
+
+ expect(overlay?.className).toContain("opacity-0");
+
+ creditsState.credits = 1479;
+ rerender(<Wallet />);
+
+ expect(container.querySelector(".bg-violet-400")?.className).toContain(
+ "opacity-50",
+ );
+ expect(screen.getByText("$14.79")).toBeDefined();
+ });
+
+ it("does not mark the wallet as shown again once it has been seen", async () => {
+ onboardingState.state = buildOnboarding({ walletShown: true });
+ render(<Wallet />);
+
+ await userEvent.click(screen.getByRole("button"));
+
+ expect(updateStateMock).not.toHaveBeenCalledWith({ walletShown: true });
+ });
+});
+
+describe("Wallet onboarding notifications", () => {
+ function emit(notification: WebSocketNotification) {
+ const handler = onWebSocketMessageMock.mock.calls.at(-1)?.[1] as (
+ n: WebSocketNotification,
+ ) => void;
+ handler(notification);
+ }
+
+ it("subscribes once and keeps the connection across onboarding updates", async () => {
+ const { rerender } = render(<Wallet />);
+
+ expect(onWebSocketMessageMock).toHaveBeenCalledTimes(1);
+ expect(connectWebSocketMock).toHaveBeenCalledTimes(1);
+
+ onboardingState.state = buildOnboarding({
+ completedSteps: ["VISIT_COPILOT", "SCHEDULE_AGENT"],
+ });
+ rerender(<Wallet />);
+
+ await waitFor(() => {
+ expect(screen.getByText(/2 of 8 rewards claimed/)).toBeDefined();
+ });
+ expect(onWebSocketMessageMock).toHaveBeenCalledTimes(1);
+ expect(connectWebSocketMock).toHaveBeenCalledTimes(1);
+ expect(detachMessageMock).not.toHaveBeenCalled();
+ });
+
+ it("refreshes credits and fires confetti when a tracked step completes", () => {
+ render(<Wallet />);
+ fetchCreditsMock.mockClear();
+
+ emit({ type: "onboarding", event: "step_completed", step: "RUN_3_DAYS" });
+
+ expect(fetchCreditsMock).toHaveBeenCalledTimes(1);
+ expect(confettiMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("ignores notifications that are not completed onboarding steps", () => {
+ render(<Wallet />);
+ fetchCreditsMock.mockClear();
+
+ emit({ type: "onboarding", event: "increment_runs", step: null });
+ emit({ type: "execution", event: "step_completed" });
+
+ expect(fetchCreditsMock).not.toHaveBeenCalled();
+ expect(confettiMock).not.toHaveBeenCalled();
+ });
+
+ it("refreshes credits without confetti for steps outside the task groups", () => {
+ render(<Wallet />);
+ fetchCreditsMock.mockClear();
+
+ emit({
+ type: "onboarding",
+ event: "step_completed",
+ step: "CONGRATS",
+ });
+
+ expect(fetchCreditsMock).toHaveBeenCalledTimes(1);
+ expect(confettiMock).not.toHaveBeenCalled();
+ });
+
+ it("detaches the listener on unmount", () => {
+ const { unmount } = render(<Wallet />);
+
+ unmount();
+
+ expect(detachMessageMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx
new file mode 100644
index 0000000000..3e3c76aa96
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx
@@ -0,0 +1,171 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { OnboardingStep } from "@/lib/autogpt-server-api";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+
+import { WalletCompactPanel } from "../components/WalletCompactPanel";
+import { getEarnRows, getTaskGroups, TaskGroup } from "../helpers";
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return { ...actual, useGetFlag: vi.fn(() => true) };
+});
+
+const groups: TaskGroup[] = [
+ {
+ name: "First Wins",
+ details: "",
+ tasks: [
+ {
+ id: "VISIT_COPILOT",
+ name: "Complete onboarding",
+ amount: 3,
+ details: "",
+ },
+ {
+ id: "MARKETPLACE_ADD_AGENT",
+ name: "Get an agent from the marketplace",
+ amount: 1,
+ details: "",
+ },
+ ],
+ },
+ {
+ name: "Consistency Challenge",
+ details: "",
+ tasks: [
+ {
+ id: "SCHEDULE_AGENT",
+ name: "Schedule your first agent",
+ amount: 1,
+ details: "",
+ },
+ {
+ id: "RUN_3_DAYS",
+ name: "Run agents 3 days in a row",
+ amount: 2,
+ details: "",
+ },
+ ],
+ },
+];
+
+const completedSteps: OnboardingStep[] = [
+ "VISIT_COPILOT",
+ "MARKETPLACE_ADD_AGENT",
+];
+
+describe("getEarnRows", () => {
+ it("collapses a fully completed group into a single Done row", () => {
+ const rows = getEarnRows(groups, completedSteps);
+
+ expect(rows).toEqual([
+ {
+ key: "First Wins",
+ label: "First Wins · 2 of 2",
+ done: true,
+ amount: 0,
+ },
+ {
+ key: "SCHEDULE_AGENT",
+ label: "Schedule your first agent",
+ done: false,
+ amount: 1,
+ },
+ {
+ key: "RUN_3_DAYS",
+ label: "Run agents 3 days in a row",
+ done: false,
+ amount: 2,
+ },
+ ]);
+ });
+
+ it("lists every task of a group that is still in progress", () => {
+ const rows = getEarnRows(groups, ["SCHEDULE_AGENT"]);
+
+ expect(rows.map((row) => row.key)).toEqual([
+ "VISIT_COPILOT",
+ "MARKETPLACE_ADD_AGENT",
+ "SCHEDULE_AGENT",
+ "RUN_3_DAYS",
+ ]);
+ expect(rows.find((row) => row.key === "SCHEDULE_AGENT")?.done).toBe(true);
+ });
+
+ it("treats a missing completedSteps list as nothing claimed", () => {
+ const rows = getEarnRows(groups, undefined);
+
+ expect(rows.map((row) => row.key)).toEqual([
+ "VISIT_COPILOT",
+ "MARKETPLACE_ADD_AGENT",
+ "SCHEDULE_AGENT",
+ "RUN_3_DAYS",
+ ]);
+ expect(rows.every((row) => !row.done)).toBe(true);
+ });
+
+ it("keeps every real onboarding task reachable", () => {
+ const realGroups = getTaskGroups(null);
+ const rows = getEarnRows(realGroups, []);
+
+ expect(rows).toHaveLength(
+ realGroups.reduce((total, group) => total + group.tasks.length, 0),
+ );
+ });
+});
+
+describe("WalletCompactPanel", () => {
+ it("shows the balance, the earn list and the completed group as Done", () => {
+ render(
+ <WalletCompactPanel
+ groups={groups}
+ completedSteps={completedSteps}
+ formattedCredits="$9.79"
+ onAddCredits={() => {}}
+ />,
+ );
+
+ expect(screen.getByText("Automation credits")).toBeDefined();
+ expect(screen.getByText("$9.79")).toBeDefined();
+ expect(screen.getByText("Earn credits")).toBeDefined();
+ expect(screen.getByText("First Wins · 2 of 2")).toBeDefined();
+ expect(screen.getByText("Done")).toBeDefined();
+ expect(screen.getByText("Schedule your first agent")).toBeDefined();
+ expect(screen.getByText("$2.00")).toBeDefined();
+ });
+
+ it("collapses the earn credits list when the accordion is toggled", async () => {
+ render(
+ <WalletCompactPanel
+ groups={groups}
+ completedSteps={completedSteps}
+ formattedCredits="$9.79"
+ onAddCredits={() => {}}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: /Earn credits/ }));
+
+ expect(screen.queryByText("Schedule your first agent")).toBeNull();
+ });
+
+ it("calls onAddCredits when the Add credits row is clicked", async () => {
+ const onAddCredits = vi.fn();
+ render(
+ <WalletCompactPanel
+ groups={groups}
+ completedSteps={completedSteps}
+ formattedCredits="$9.79"
+ onAddCredits={onAddCredits}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Add credits" }));
+
+ expect(onAddCredits).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx
new file mode 100644
index 0000000000..d3fda6ca6d
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { Collapsible } from "@/components/molecules/Collapsible/Collapsible";
+import { OnboardingStep } from "@/lib/autogpt-server-api";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import {
+ CircleIcon,
+ CreditCardIcon,
+ SealCheckIcon,
+} from "@phosphor-icons/react";
+
+import { getEarnRows, TaskGroup } from "../helpers";
+
+interface Props {
+ groups: TaskGroup[];
+ completedSteps: OnboardingStep[] | undefined;
+ formattedCredits: string;
+ onAddCredits: () => void;
+}
+
+export function WalletCompactPanel({
+ groups,
+ completedSteps,
+ formattedCredits,
+ onAddCredits,
+}: Props) {
+ const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
+ const rows = getEarnRows(groups, completedSteps);
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between gap-3 px-3 py-2">
+ <Text variant="body-medium">Automation credits</Text>
+ <span className="font-sans text-base font-semibold text-zinc-900">
+ {formattedCredits}
+ </span>
+ </div>
+
+ {isPaymentEnabled && (
+ <button
+ type="button"
+ onClick={onAddCredits}
+ className="flex items-center justify-center gap-3 rounded-large bg-zinc-100 px-3 py-2.5 text-center transition-colors hover:bg-zinc-200"
+ >
+ <CreditCardIcon size={20} className="text-zinc-700" />
+ <Text variant="body-medium">Add credits</Text>
+ </button>
+ )}
+
+ <Collapsible
+ defaultOpen
+ triggerClassName="px-3 pb-1.5 pt-2"
+ trigger={<Text variant="body-medium">Earn credits</Text>}
+ >
+ <div className="max-h-[20rem] overflow-y-auto">
+ {rows.map((row) => (
+ <div
+ key={row.key}
+ className="flex items-start justify-between gap-3 px-3 py-1.5"
+ >
+ <div className="flex min-w-0 items-start gap-2.5">
+ <span className="mt-0.5 shrink-0">
+ {row.done ? (
+ <SealCheckIcon
+ size={18}
+ weight="fill"
+ className="text-[#00a656]"
+ aria-label="completed"
+ />
+ ) : (
+ <CircleIcon
+ size={16}
+ weight="regular"
+ className="text-zinc-400"
+ aria-label="pending"
+ />
+ )}
+ </span>
+ <Text variant="body">{row.label}</Text>
+ </div>
+ <span className="shrink-0 font-sans text-sm text-zinc-500">
+ {row.done ? "Done" : `$${row.amount.toFixed(2)}`}
+ </span>
+ </div>
+ ))}
+ </div>
+ </Collapsible>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletFullPanel.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletFullPanel.tsx
new file mode 100644
index 0000000000..2f91189a27
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletFullPanel.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import { XIcon } from "@phosphor-icons/react";
+import { PopoverClose } from "@radix-ui/react-popover";
+
+import { TaskGroup } from "../helpers";
+import { WalletRefill } from "./WalletRefill";
+import { TaskGroups } from "./WalletTaskGroups";
+
+interface Props {
+ groups: TaskGroup[];
+ formattedCredits: string;
+}
+
+export function WalletFullPanel({ groups, formattedCredits }: Props) {
+ const isPaymentEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
+
+ return (
+ <>
+ {/* Header */}
+ <div className="mx-1 flex items-start justify-between gap-3 border-b border-zinc-200 pb-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="font-poppins text-base font-semibold text-zinc-900">
+ Automation Credits
+ </span>
+ <span className="font-sans text-xs text-zinc-500">
+ Platform-only credits for automations. This is separate from your
+ subscription and is not usable for plan fees.
+ </span>
+ </div>
+ <div className="flex shrink-0 items-center text-sm text-violet-700">
+ <div className="rounded-lg bg-violet-100 px-3 py-2">
+ Earn credits{" "}
+ <span className="font-semibold">{formattedCredits}</span>
+ </div>
+ <PopoverClose aria-label="Close wallet">
+ <XIcon className="ml-2 h-5 w-5 text-zinc-800 hover:text-foreground" />
+ </PopoverClose>
+ </div>
+ </div>
+ <ScrollArea className="max-h-[85vh] overflow-y-auto">
+ {/* Top ups */}
+ {isPaymentEnabled && <WalletRefill />}
+ {/* Tasks */}
+ <p className="mx-1 my-3 font-sans text-xs font-normal text-zinc-400">
+ Complete the following tasks to earn more credits!
+ </p>
+ <TaskGroups groups={groups} />
+ </ScrollArea>
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletTaskGroups.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletTaskGroups.tsx
index 418f86af02..5c88c9efd4 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletTaskGroups.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletTaskGroups.tsx
@@ -4,7 +4,7 @@ import { BadgeQuestionMark, Check, ChevronDown } from "lucide-react";
import confetti, { type Options as ConfettiOptions } from "canvas-confetti";
import { AGPT_CONFETTI_COLORS } from "@/components/molecules/Confetti/Confetti";
import { useCallback, useEffect, useRef, useState } from "react";
-import { Task, TaskGroup } from "../Wallet";
+import { Task, TaskGroup } from "../helpers";
interface Props {
groups: TaskGroup[];
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts
new file mode 100644
index 0000000000..b18353addd
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts
@@ -0,0 +1,154 @@
+import { OnboardingStep, UserOnboarding } from "@/lib/autogpt-server-api";
+
+export interface Task {
+ id: OnboardingStep;
+ name: string;
+ amount: number;
+ details: string;
+ video?: string;
+ progress?: {
+ current: number;
+ target: number;
+ };
+}
+
+export interface TaskGroup {
+ name: string;
+ details: string;
+ tasks: Task[];
+}
+
+export function getTaskGroups(state: UserOnboarding | null): TaskGroup[] {
+ return [
+ {
+ name: "First Wins",
+ details: "Kickstart your journey with quick wins.",
+ tasks: [
+ {
+ id: "VISIT_COPILOT",
+ name: "Complete onboarding",
+ amount: 3,
+ details: "",
+ },
+ {
+ id: "MARKETPLACE_ADD_AGENT",
+ name: "Get an agent from the marketplace",
+ amount: 1,
+ details:
+ "Search for an agent in the Marketplace and add it to your Library",
+ video: "/onboarding/marketplace-add.mp4",
+ },
+ {
+ id: "MARKETPLACE_RUN_AGENT",
+ name: "Open the Library page and run an agent",
+ amount: 1,
+ details: "Go to the Library, open an agent you want, and run it",
+ video: "/onboarding/agent-run.mp4",
+ },
+ ],
+ },
+ {
+ name: "Consistency Challenge",
+ details: "Build your rhythm and make agents part of your routine.",
+ tasks: [
+ {
+ id: "SCHEDULE_AGENT",
+ name: "Schedule your first agent",
+ amount: 1,
+ details: "Schedule an agent to run on a recurring basis",
+ video: "/onboarding/agent-schedule.mp4",
+ },
+ {
+ id: "RUN_3_DAYS",
+ name: "Run agents 3 days in a row",
+ amount: 1,
+ details:
+ "Run any agents from the Library or Builder for 3 days in a row",
+ progress: {
+ current: state?.consecutiveRunDays || 0,
+ target: 3,
+ },
+ },
+ ],
+ },
+ {
+ name: "The Pro Playground",
+ details: "Master powerful features to supercharge your workflow.",
+ tasks: [
+ {
+ id: "TRIGGER_WEBHOOK",
+ name: "Trigger an agent via webhook",
+ amount: 1,
+ details:
+ "In the Builder, go to Settings and copy the Webhook URL. Use it to trigger your agent from another app.",
+ },
+ {
+ id: "RUN_14_DAYS",
+ name: "Run agents 14 days in a row",
+ amount: 1,
+ details:
+ "Run any agents from the Library or Builder for 14 days in a row",
+ progress: {
+ current: state?.consecutiveRunDays || 0,
+ target: 14,
+ },
+ },
+ {
+ id: "RUN_AGENTS_100",
+ name: "Complete 100 agent runs",
+ amount: 1,
+ details: "Let your agents run and complete 100 tasks in total",
+ progress: {
+ current: state?.agentRuns || 0,
+ target: 100,
+ },
+ },
+ ],
+ },
+ ];
+}
+
+export interface EarnRow {
+ key: string;
+ label: string;
+ done: boolean;
+ amount: number;
+}
+
+/**
+ * Flattens the task groups into a single list for the compact panel: a fully
+ * completed group collapses to one "Done" row, while any group still in
+ * progress contributes one row per task.
+ */
+export function getEarnRows(
+ groups: TaskGroup[],
+ // The onboarding payload is typed as always carrying `completedSteps`, but
+ // the rest of the wallet already guards against it being absent — do the same
+ // here so a thin backend response degrades to "nothing claimed" and not a
+ // TypeError.
+ completedSteps: OnboardingStep[] | undefined,
+): EarnRow[] {
+ const claimed = completedSteps ?? [];
+
+ return groups.flatMap((group): EarnRow[] => {
+ const completed = group.tasks.filter((task) => claimed.includes(task.id));
+
+ if (completed.length === group.tasks.length) {
+ return [
+ {
+ key: group.name,
+ label: `${group.name} · ${completed.length} of ${group.tasks.length}`,
+ done: true,
+ amount: 0,
+ },
+ ];
+ }
+
+ return group.tasks.map((task) => ({
+ key: task.id,
+ label: task.name,
+ done: claimed.includes(task.id),
+ amount: task.amount,
+ }));
+ });
+}
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/useWallet.ts b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/useWallet.ts
new file mode 100644
index 0000000000..e33cd2e645
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/useWallet.ts
@@ -0,0 +1,164 @@
+"use client";
+
+import { AGPT_CONFETTI_COLORS } from "@/components/molecules/Confetti/Confetti";
+import useCredits from "@/hooks/useCredits";
+import {
+ OnboardingStep,
+ WebSocketNotification,
+} from "@/lib/autogpt-server-api";
+import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { useOnboarding } from "@/providers/onboarding/onboarding-provider";
+import confetti, { type Options as ConfettiOptions } from "canvas-confetti";
+import { useEffect, useRef, useState } from "react";
+import { getTaskGroups } from "./helpers";
+
+export function useWallet() {
+ const { state, updateState } = useOnboarding();
+ const api = useBackendAPI();
+ const { credits, formatCredits, fetchCredits } = useCredits({
+ fetchInitialCredits: true,
+ });
+
+ const groups = getTaskGroups(state);
+
+ const [prevCredits, setPrevCredits] = useState<number | null>(credits);
+ const [flash, setFlash] = useState(false);
+ const [walletOpen, setWalletOpen] = useState(false);
+ const [topUpOpen, setTopUpOpen] = useState(false);
+
+ const walletRef = useRef<HTMLButtonElement | null>(null);
+
+ const totalCount = groups.reduce((acc, group) => acc + group.tasks.length, 0);
+
+ // Total completed task count across all groups
+ const completedCount = state
+ ? groups.reduce(
+ (acc, group) =>
+ acc +
+ group.tasks.filter((task) => state.completedSteps?.includes(task.id))
+ .length,
+ 0,
+ )
+ : null;
+
+ async function onWalletOpen() {
+ if (!state?.walletShown) {
+ updateState({ walletShown: true });
+ }
+ // Refresh credits when the wallet is opened
+ fetchCredits();
+ }
+
+ function onAddCredits() {
+ setWalletOpen(false);
+ setTopUpOpen(true);
+ }
+
+ function onTopUpClose() {
+ setTopUpOpen(false);
+ }
+
+ // React to onboarding notifications emitted by the provider
+ function handleNotification(notification: WebSocketNotification) {
+ if (
+ notification.type !== "onboarding" ||
+ notification.event !== "step_completed"
+ ) {
+ return;
+ }
+
+ // Always refresh credits when any onboarding step completes
+ fetchCredits();
+
+ // Only trigger confetti for tasks that are in displayed groups
+ if (!walletRef.current) {
+ return;
+ }
+ const taskIds = groups
+ .flatMap((group) => group.tasks)
+ .map((task) => task.id);
+ if (!taskIds.includes(notification.step as OnboardingStep)) {
+ return;
+ }
+
+ const rect = walletRef.current.getBoundingClientRect();
+ if (rect.width === 0 || rect.height === 0) {
+ return;
+ }
+
+ const origin = {
+ x: (rect.left + rect.width / 2) / window.innerWidth,
+ y: (rect.top + rect.height / 2) / window.innerHeight,
+ };
+ const shared: ConfettiOptions = {
+ particleCount: 50,
+ spread: 70,
+ shapes: ["square"],
+ scalar: 1.2,
+ startVelocity: 20,
+ gravity: 0.6,
+ decay: 0.92,
+ ticks: 100,
+ colors: AGPT_CONFETTI_COLORS,
+ origin,
+ };
+ confetti({ ...shared, angle: 45 });
+ confetti({ ...shared, angle: 135 });
+ }
+
+ // `handleNotification` is a fresh closure on every render. Route the listener
+ // through a ref, refreshed after each render, so the subscription below stays
+ // mounted for the lifetime of the hook instead of tearing down and
+ // reconnecting each time.
+ const notificationRef = useRef(handleNotification);
+
+ useEffect(() => {
+ notificationRef.current = handleNotification;
+ });
+
+ // WebSocket setup for onboarding notifications
+ useEffect(() => {
+ const detachMessage = api.onWebSocketMessage(
+ "notification",
+ (notification) => notificationRef.current(notification),
+ );
+
+ api.connectWebSocket();
+
+ return () => {
+ detachMessage();
+ };
+ }, [api]);
+
+ // Wallet flash on credits change
+ useEffect(() => {
+ if (credits === prevCredits) {
+ return;
+ }
+ setPrevCredits(credits);
+ if (prevCredits === null) {
+ return;
+ }
+ setFlash(true);
+ setTimeout(() => {
+ setFlash(false);
+ }, 300);
+ }, [credits, prevCredits]);
+
+ return {
+ state,
+ groups,
+ credits,
+ formatCredits,
+ flash,
+ walletOpen,
+ setWalletOpen,
+ onWalletOpen,
+ walletRef,
+ completedCount,
+ totalCount,
+ topUpOpen,
+ onAddCredits,
+ onTopUpClose,
+ };
+}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx
index 74955d4f4a..4ffec3623d 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpDialog/TopUpDialog.tsx
@@ -11,9 +11,18 @@ import { TopUpForm } from "../TopUpForm/TopUpForm";
interface Props {
isOpen: boolean;
onClose: () => void;
+ // "out-of-credits" is the reactive nudge shown when the balance hits zero;
+ // "add-credits" is the same form opened deliberately from the wallet.
+ variant?: "out-of-credits" | "add-credits";
}
-export function TopUpDialog({ isOpen, onClose }: Props) {
+export function TopUpDialog({
+ isOpen,
+ onClose,
+ variant = "out-of-credits",
+}: Props) {
+ const isOutOfCredits = variant === "out-of-credits";
+
function handleOpenChange(open: boolean) {
if (!open) onClose();
}
@@ -21,17 +30,23 @@ export function TopUpDialog({ isOpen, onClose }: Props) {
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>
+ isOutOfCredits ? (
+ <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>
+ ) : (
+ "Add automation credits"
+ )
}
styling={{ maxWidth: "28rem" }}
controlled={{ isOpen, set: handleOpenChange }}
>
<Dialog.Content>
<Text variant="large">
- Top up to keep your agents and Autopilot running. You can also{" "}
+ {isOutOfCredits
+ ? "Top up to keep your agents and Autopilot running. You can also "
+ : "Credits are used to run your agents and Autopilot. You can also "}
<Link href="/settings/billing" className="underline">
enable auto-refill in billing settings
</Link>
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx
new file mode 100644
index 0000000000..2c366e857a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpDialog.test.tsx
@@ -0,0 +1,79 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+
+import { TopUpDialog } from "../TopUpDialog/TopUpDialog";
+
+vi.mock("../TopUpForm/TopUpForm", () => ({
+ TopUpForm: ({ submitLabel }: { submitLabel?: string }) => (
+ <button type="submit">{submitLabel}</button>
+ ),
+}));
+
+describe("TopUpDialog", () => {
+ it("defaults to the out-of-credits copy", () => {
+ render(<TopUpDialog isOpen onClose={() => {}} />);
+
+ expect(screen.getByText("You're out of automation credits")).toBeDefined();
+ expect(screen.getByText(/Top up to keep your agents/)).toBeDefined();
+ expect(screen.queryByText("Add automation credits")).toBeNull();
+ });
+
+ it("uses the add-credits copy when opened deliberately from the wallet", () => {
+ render(<TopUpDialog isOpen onClose={() => {}} variant="add-credits" />);
+
+ expect(screen.getByText("Add automation credits")).toBeDefined();
+ expect(
+ screen.getByText(/Credits are used to run your agents/),
+ ).toBeDefined();
+ expect(screen.queryByText("You're out of automation credits")).toBeNull();
+ });
+
+ it("links to billing settings in both variants", () => {
+ const { unmount } = render(<TopUpDialog isOpen onClose={() => {}} />);
+
+ expect(
+ screen
+ .getByRole("link", { name: /enable auto-refill/ })
+ .getAttribute("href"),
+ ).toBe("/settings/billing");
+
+ unmount();
+ render(<TopUpDialog isOpen onClose={() => {}} variant="add-credits" />);
+
+ expect(
+ screen
+ .getByRole("link", { name: /enable auto-refill/ })
+ .getAttribute("href"),
+ ).toBe("/settings/billing");
+ });
+
+ it("does not render its content while closed", () => {
+ render(<TopUpDialog isOpen={false} onClose={() => {}} />);
+
+ expect(screen.queryByText(/automation credits/i)).toBeNull();
+ });
+
+ it("calls onClose once when the close button is used", async () => {
+ const onClose = vi.fn();
+ render(<TopUpDialog isOpen onClose={onClose} />);
+
+ await userEvent.click(screen.getByRole("button", { name: "Close" }));
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ // Escape is handled twice by the design-system Dialog: `DialogWrap` passes
+ // `onEscapeKeyDown={handleClose}`, and Radix's dismissable layer then also
+ // fires `onOpenChange(false)` on the root. Both land on `controlled.set`.
+ // Closing is idempotent so nothing breaks, but pin the count — if the Dialog
+ // is ever fixed this test should be the thing that notices.
+ it("notifies close on Escape (twice, via the shared Dialog)", async () => {
+ const onClose = vi.fn();
+ render(<TopUpDialog isOpen onClose={onClose} />);
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(onClose).toHaveBeenCalledTimes(2);
+ });
+});