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(platform): admin users page to look up, ban and impersonate a user, with rate limits folded in (#15675)

Reinier van der Leerfb13f37c2c85
diff --git a/autogpt_platform/backend/backend/api/features/admin/user_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/user_admin_routes.py
new file mode 100644
index 0000000000..e8933d25ba
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/user_admin_routes.py
@@ -0,0 +1,21 @@
+"""Admin endpoints backing the user view on the admin users page."""
+
+from autogpt_libs.auth import requires_admin_user
+from fastapi import APIRouter, Security
+
+from backend.api.features.orgs import db as org_db
+from backend.api.features.orgs.model import OrgResponse
+
+router = APIRouter(
+ prefix="/admin/users",
+ dependencies=[Security(requires_admin_user)],
+)
+
+
+ "/{user_id}/organizations",
+ summary="Get user organizations",
+)
+async def get_user_organizations(user_id: str) -> list[OrgResponse]:
+ """The organizations a user is an active member of. Admin-only."""
+ return await org_db.list_user_orgs(user_id)
diff --git a/autogpt_platform/backend/backend/api/features/admin/user_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/user_admin_routes_test.py
new file mode 100644
index 0000000000..19761abe68
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/user_admin_routes_test.py
@@ -0,0 +1,67 @@
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+from backend.api.features.orgs.model import OrgResponse
+
+from .user_admin_routes import router as user_admin_router
+
+app = fastapi.FastAPI()
+app.include_router(user_admin_router)
+
+client = fastapi.testclient.TestClient(app)
+
+_MOCK_MODULE = "backend.api.features.admin.user_admin_routes"
+_TARGET_USER_ID = "5d0a1c2e-0000-4000-8000-000000000001"
+
+
[email protected](autouse=True)
+def setup_app_admin_auth(mock_jwt_admin):
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_admin["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+def test_get_user_organizations_returns_the_target_users_orgs(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ org = OrgResponse(
+ id="org-1",
+ name="Acme",
+ slug="acme",
+ avatar_url=None,
+ description=None,
+ is_personal=False,
+ member_count=0,
+ created_at=datetime(2026, 1, 2, tzinfo=UTC),
+ )
+ list_user_orgs = mocker.patch(
+ f"{_MOCK_MODULE}.org_db.list_user_orgs",
+ new_callable=AsyncMock,
+ return_value=[org],
+ )
+
+ response = client.get(f"/admin/users/{_TARGET_USER_ID}/organizations")
+
+ assert response.status_code == 200
+ assert [o["slug"] for o in response.json()] == ["acme"]
+ list_user_orgs.assert_awaited_once_with(_TARGET_USER_ID)
+
+
+def test_get_user_organizations_requires_admin_role(
+ mock_jwt_user, mocker: pytest_mock.MockerFixture
+) -> None:
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ list_user_orgs = mocker.patch(
+ f"{_MOCK_MODULE}.org_db.list_user_orgs", new_callable=AsyncMock
+ )
+
+ response = client.get(f"/admin/users/{_TARGET_USER_ID}/organizations")
+
+ assert response.status_code == 403
+ list_user_orgs.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 07b088fc45..fbcae42e01 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -28,6 +28,7 @@ import backend.api.features.admin.platform_cost_routes
import backend.api.features.admin.rate_limit_admin_routes
import backend.api.features.admin.store_admin_routes
import backend.api.features.admin.test_data_routes
+import backend.api.features.admin.user_admin_routes
import backend.api.features.api_keys.routes as api_keys_routes
import backend.api.features.auth_email.routes as auth_email_routes
import backend.api.features.billing.credits.routes as credits_routes
@@ -523,6 +524,11 @@ app.include_router(
tags=["v2", "admin"],
prefix="/api",
)
+app.include_router(
+ backend.api.features.admin.user_admin_routes.router,
+ tags=["admin"],
+ prefix="/api",
+)
# Dev-only surface: the test-data seeder is never mounted outside a local
# app_env, matching how docs_url/metrics are gated above. The runtime
# `_guard_local_only` check stays as defense-in-depth for LOCAL+CLOUD drift.
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminLayoutShell.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminLayoutShell.test.tsx
index a0aa981510..e1b0a4245e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminLayoutShell.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminLayoutShell.test.tsx
@@ -90,7 +90,10 @@ describe("AdminLayout shell switching", () => {
screen.getAllByRole("link", { name: /marketplace management/i }).length,
).toBeGreaterThan(0);
expect(
- screen.getAllByRole("link", { name: /admin user management/i }).length,
+ screen.getAllByRole("link", { name: /^users$/i }).length,
+ ).toBeGreaterThan(0);
+ expect(
+ screen.getAllByRole("link", { name: /admin settings/i }).length,
).toBeGreaterThan(0);
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
index 6f7143ea82..4d2198506c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
@@ -4,17 +4,16 @@ import * as testDataHelpers from "../test-data/helpers";
import AdminLayout from "../layout";
const ADMIN_LINKS = [
+ { text: "Users", href: "/admin/users" },
{ text: "Marketplace Management", href: "/admin/marketplace" },
{ text: "User Spending", href: "/admin/spending" },
{ text: "System Diagnostics", href: "/admin/diagnostics" },
- { text: "User Impersonation", href: "/admin/impersonation" },
- { text: "Rate Limits", href: "/admin/rate-limits" },
{ text: "Platform Costs", href: "/admin/platform-costs" },
{ text: "Execution Analytics", href: "/admin/execution-analytics" },
{ text: "Bot Analytics", href: "/admin/bots" },
{ text: "Block Cost Estimates", href: "/admin/block-cost-estimates" },
{ text: "Memory Inspector", href: "/admin/memory" },
- { text: "Admin User Management", href: "/admin/settings" },
+ { text: "Admin settings", href: "/admin/settings" },
];
describe("AdminLayout", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
index 4205c6ccef..44aaf5d683 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
@@ -6,11 +6,10 @@ import {
Database01Icon,
DollarSignIcon,
File02Icon,
- GaugeIcon,
Pulse01Icon,
ReceiptTextIcon,
Robot01Icon,
- Search01Icon,
+ UserIcon,
UserMultipleIcon,
} from "@hugeicons/core-free-icons";
import { ReactNode } from "react";
@@ -24,6 +23,11 @@ function getSidebarLinkGroups() {
return [
{
links: [
+ {
+ text: "Users",
+ href: "/admin/users",
+ icon: <Icon icon={UserIcon} className="h-6 w-6" />,
+ },
{
text: "Marketplace Management",
href: "/admin/marketplace",
@@ -39,16 +43,6 @@ function getSidebarLinkGroups() {
href: "/admin/diagnostics",
icon: <Icon icon={Pulse01Icon} className="h-6 w-6" />,
},
- {
- text: "User Impersonation",
- href: "/admin/impersonation",
- icon: <Icon icon={Search01Icon} className="h-6 w-6" />,
- },
- {
- text: "Rate Limits",
- href: "/admin/rate-limits",
- icon: <Icon icon={GaugeIcon} className="h-6 w-6" />,
- },
{
text: "Platform Costs",
href: "/admin/platform-costs",
@@ -75,7 +69,7 @@ function getSidebarLinkGroups() {
icon: <Icon icon={BrainIcon} className="h-6 w-6" />,
},
{
- text: "Admin User Management",
+ text: "Admin settings",
href: "/admin/settings",
icon: <IconSliders className="h-6 w-6" />,
},
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx
deleted file mode 100644
index 75fcee6c78..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { Card } from "@/components/atoms/Card/Card";
-import { Input } from "@/components/atoms/Input/Input";
-import { Button } from "@/components/atoms/Button/Button";
-import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
-import { useAdminImpersonation } from "./useAdminImpersonation";
-import { useGetV1GetUserCredits } from "@/app/api/__generated__/endpoints/credits/credits";
-import {
- CreditCardIcon,
- UserCheck01Icon,
- UserRemove01Icon,
-} from "@hugeicons/core-free-icons";
-import { Icon } from "@/components/atoms/Icon/Icon";
-
-export function AdminImpersonationPanel() {
- const [userIdInput, setUserIdInput] = useState("");
- const [error, setError] = useState("");
- const {
- isImpersonating,
- impersonatedUserId,
- isStarting,
- startImpersonating,
- stopImpersonating,
- } = useAdminImpersonation();
-
- // Demo: Use existing credits API - it will automatically use impersonation if active
- const {
- data: creditsResponse,
- isLoading: creditsLoading,
- error: creditsError,
- } = useGetV1GetUserCredits();
-
- async function handleStartImpersonation() {
- setError("");
-
- const trimmed = userIdInput.trim();
- if (!trimmed) {
- setError("Please enter a valid user ID");
- return;
- }
-
- // Basic UUID validation
- const uuidRegex =
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
- if (!uuidRegex.test(trimmed)) {
- setError("Please enter a valid UUID format user ID");
- return;
- }
-
- // startImpersonating handles its own errors (toast) and gates on the audit
- // alert. Don't clear the input here: on success the page reloads, and on a
- // blocked/failed alert we keep the entered ID so the admin can retry.
- await startImpersonating(trimmed);
- }
-
- function handleStopImpersonation() {
- stopImpersonating();
- setError("");
- }
-
- return (
- <Card className="w-full max-w-2xl">
- <div className="space-y-4">
- <div className="border-b pb-4">
- <div className="mb-2 flex items-center space-x-2">
- <Icon icon={UserCheck01Icon} className="h-5 w-5" />
- <h2 className="text-xl font-semibold">Admin User Impersonation</h2>
- </div>
- <p className="text-sm text-gray-600">
- Act on behalf of another user for debugging and support purposes
- </p>
- </div>
-
- {/* Security Warning */}
- <Alert variant="error">
- <AlertDescription>
- <strong>Security Notice:</strong> This feature is for admin
- debugging and support only. All impersonation actions are logged for
- audit purposes.
- </AlertDescription>
- </Alert>
-
- {/* Current Status */}
- {isImpersonating && (
- <Alert variant="warning">
- <AlertDescription>
- <strong>Currently impersonating:</strong>{" "}
- <code className="rounded bg-amber-100 px-1 font-mono text-sm">
- {impersonatedUserId}
- </code>
- </AlertDescription>
- </Alert>
- )}
-
- {/* Impersonation Controls */}
- <div className="space-y-3">
- <Input
- label="User ID to Impersonate"
- id="user-id-input"
- placeholder="e.g., 2e7ea138-2097-425d-9cad-c660f29cc251"
- value={userIdInput}
- onChange={(e) => setUserIdInput(e.target.value)}
- disabled={isImpersonating}
- error={error}
- />
-
- <div className="flex space-x-2">
- <Button
- onClick={() => void handleStartImpersonation()}
- disabled={isImpersonating || isStarting || !userIdInput.trim()}
- className="min-w-[100px]"
- >
- {isImpersonating ? "Active" : isStarting ? "Starting…" : "Start"}
- </Button>
-
- {isImpersonating && (
- <Button
- onClick={handleStopImpersonation}
- variant="secondary"
- leftIcon={<Icon icon={UserRemove01Icon} className="h-4 w-4" />}
- >
- Stop Impersonation
- </Button>
- )}
- </div>
- </div>
-
- {/* Demo: Live Credits Display */}
- <Card className="bg-gray-50">
- <div className="space-y-3">
- <div className="flex items-center space-x-2">
- <Icon icon={CreditCardIcon} className="h-4 w-4" />
- <h3 className="text-sm font-medium">Live Demo: User Credits</h3>
- </div>
-
- {creditsLoading ? (
- <p className="text-sm text-gray-600">Loading credits...</p>
- ) : creditsError ? (
- <Alert variant="error">
- <AlertDescription className="text-sm">
- Error loading credits:{" "}
- {creditsError &&
- typeof creditsError === "object" &&
- "message" in creditsError
- ? String(creditsError.message)
- : "Unknown error"}
- </AlertDescription>
- </Alert>
- ) : creditsResponse?.data ? (
- <div className="space-y-1">
- <p className="text-sm">
- <strong>
- {creditsResponse.data &&
- typeof creditsResponse.data === "object" &&
- "credits" in creditsResponse.data
- ? String(creditsResponse.data.credits)
- : "N/A"}
- </strong>{" "}
- credits available
- {isImpersonating && (
- <span className="ml-2 text-amber-600">
- (via impersonation)
- </span>
- )}
- </p>
- <p className="text-xs text-gray-500">
- {isImpersonating
- ? `Showing credits for user ${impersonatedUserId}`
- : "Showing your own credits"}
- </p>
- </div>
- ) : (
- <p className="text-sm text-gray-600">No credits data available</p>
- )}
- </div>
- </Card>
-
- {/* Instructions */}
- <div className="space-y-1 text-sm text-gray-600">
- <p>
- <strong>Instructions:</strong>
- </p>
- <ul className="ml-2 list-inside list-disc space-y-1">
- <li>Enter the UUID of the user you want to impersonate</li>
- <li>
- All existing API endpoints automatically work with impersonation
- </li>
- <li>A warning banner will appear while impersonation is active</li>
- <li>
- Impersonation persists across page refreshes in this session
- </li>
- </ul>
- </div>
- </div>
- </Card>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSection.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSection.tsx
new file mode 100644
index 0000000000..2b1a297ec2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSection.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+import { ReactNode, useId } from "react";
+
+interface Props {
+ title?: string;
+ description?: string;
+ className?: string;
+ children: ReactNode;
+}
+
+export function AdminSection({
+ title,
+ description,
+ className,
+ children,
+}: Props) {
+ const titleId = useId();
+
+ return (
+ <section
+ aria-labelledby={title ? titleId : undefined}
+ className={cn(
+ "rounded-[18px] border border-zinc-200 bg-white px-5 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)]",
+ className,
+ )}
+ >
+ {title ? (
+ <div className="mb-4 flex flex-col">
+ <Text variant="body-medium" as="h2" id={titleId}>
+ {title}
+ </Text>
+ {description ? (
+ <Text variant="small" className="text-zinc-500">
+ {description}
+ </Text>
+ ) : null}
+ </div>
+ ) : null}
+ {children}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
index 1762d4991b..b039146774 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
@@ -4,12 +4,11 @@ import {
Database01Icon,
DollarSignIcon,
File02Icon,
- GaugeIcon,
Pulse01Icon,
ReceiptTextIcon,
Robot01Icon,
- Search01Icon,
SlidersHorizontalIcon,
+ UserIcon,
UserMultipleIcon,
} from "@hugeicons/core-free-icons";
@@ -26,6 +25,7 @@ export interface AdminNavItem {
// environment check instead of the value at module load.
export function getAdminNavItems(): AdminNavItem[] {
return [
+ { label: "Users", href: "/admin/users", Icon: UserIcon },
{
label: "Marketplace Management",
href: "/admin/marketplace",
@@ -37,12 +37,6 @@ export function getAdminNavItems(): AdminNavItem[] {
href: "/admin/diagnostics",
Icon: Pulse01Icon,
},
- {
- label: "User Impersonation",
- href: "/admin/impersonation",
- Icon: Search01Icon,
- },
- { label: "Rate Limits", href: "/admin/rate-limits", Icon: GaugeIcon },
{
label: "Platform Costs",
href: "/admin/platform-costs",
@@ -61,7 +55,7 @@ export function getAdminNavItems(): AdminNavItem[] {
},
{ label: "Memory Inspector", href: "/admin/memory", Icon: BrainIcon },
{
- label: "Admin User Management",
+ label: "Admin settings",
href: "/admin/settings",
Icon: SlidersHorizontalIcon,
},
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx
deleted file mode 100644
index a104c7d420..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { http, HttpResponse } from "msw";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-
-import { getPostV2NotifyImpersonationStartMockHandler200 } from "@/app/api/__generated__/endpoints/admin/admin.msw";
-import { getGetV1GetUserCreditsMockHandler } from "@/app/api/__generated__/endpoints/credits/credits.msw";
-import { ImpersonationState } from "@/lib/impersonation";
-import { server } from "@/mocks/mock-server";
-import {
- fireEvent,
- render,
- screen,
- waitFor,
-} from "@/tests/integrations/test-utils";
-
-import { AdminImpersonationPanel } from "../AdminImpersonationPanel";
-
-const NOTIFY_URL =
- "http://localhost:3000/api/proxy/api/admin/impersonation/notify";
-const VALID_UUID = "2e7ea138-2097-425d-9cad-c660f29cc251";
-
-const toastMock = vi.fn();
-vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
- const actual =
- await importOriginal<
- typeof import("@/components/molecules/Toast/use-toast")
- >();
- return { ...actual, useToast: () => ({ toast: toastMock }) };
-});
-
-const reloadMock = vi.fn();
-
-beforeEach(() => {
- toastMock.mockClear();
- reloadMock.mockClear();
- sessionStorage.clear();
- Object.defineProperty(window.location, "reload", {
- configurable: true,
- value: reloadMock,
- });
- // Avoid persisting impersonation state across tests; assert reload instead.
- vi.spyOn(ImpersonationState, "set").mockImplementation(() => {});
- // The panel renders a live-credits demo; keep that query happy.
- server.use(getGetV1GetUserCreditsMockHandler());
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-function typeUserId(value: string) {
- fireEvent.change(screen.getByLabelText(/user id to impersonate/i), {
- target: { value },
- });
-}
-
-function clickStart() {
- fireEvent.click(screen.getByRole("button", { name: /^start$/i }));
-}
-
-describe("AdminImpersonationPanel", () => {
- test("disables Start until a user id is entered", () => {
- render(<AdminImpersonationPanel />);
- const start = screen.getByRole("button", {
- name: /^start$/i,
- }) as HTMLButtonElement;
- expect(start.disabled).toBe(true);
-
- typeUserId(VALID_UUID);
- expect(start.disabled).toBe(false);
- });
-
- test("rejects a non-UUID value with an inline error and no swap", async () => {
- render(<AdminImpersonationPanel />);
- typeUserId("not-a-uuid");
- clickStart();
-
- expect(await screen.findByText(/valid uuid format/i)).toBeDefined();
- expect(reloadMock).not.toHaveBeenCalled();
- });
-
- test("keeps the entered id and shows a destructive toast when the alert is blocked (502)", async () => {
- server.use(
- http.post(NOTIFY_URL, () => new HttpResponse(null, { status: 502 })),
- );
-
- render(<AdminImpersonationPanel />);
- const input = screen.getByLabelText(
- /user id to impersonate/i,
- ) as HTMLInputElement;
- typeUserId(VALID_UUID);
- clickStart();
-
- await waitFor(() => {
- expect(toastMock).toHaveBeenCalledWith(
- expect.objectContaining({ variant: "destructive" }),
- );
- });
- // The fix: a blocked alert must not wipe the entered UUID.
- expect(input.value).toBe(VALID_UUID);
- expect(reloadMock).not.toHaveBeenCalled();
- });
-
- test("starts impersonation (reload) when the audit alert is delivered", async () => {
- server.use(
- getPostV2NotifyImpersonationStartMockHandler200({ alerted: true }),
- );
-
- render(<AdminImpersonationPanel />);
- typeUserId(VALID_UUID);
- clickStart();
-
- await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1));
- });
-});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/__tests__/page.test.tsx
new file mode 100644
index 0000000000..75449b9daf
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/__tests__/page.test.tsx
@@ -0,0 +1,41 @@
+import { ImpersonationState } from "@/lib/impersonation";
+import { redirect } from "next/navigation";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import ImpersonationPage from "../page";
+
+vi.mock("next/navigation", () => ({ redirect: vi.fn() }));
+
+const TARGET_ID = "11111111-1111-4111-8111-111111111111";
+
+beforeEach(() => {
+ vi.mocked(redirect).mockReset();
+ vi.restoreAllMocks();
+});
+
+describe("/admin/impersonation", () => {
+ it("sends a bookmark of the old page to the users page", async () => {
+ vi.spyOn(ImpersonationState, "getServerSide").mockResolvedValue(null);
+
+ await ImpersonationPage({ searchParams: Promise.resolve({}) });
+
+ expect(redirect).toHaveBeenCalledWith("/admin/users");
+ });
+
+ it("opens the user being impersonated", async () => {
+ vi.spyOn(ImpersonationState, "getServerSide").mockResolvedValue(TARGET_ID);
+
+ await ImpersonationPage({ searchParams: Promise.resolve({}) });
+
+ expect(redirect).toHaveBeenCalledWith(`/admin/users?user=${TARGET_ID}`);
+ });
+
+ it("prefers a user named in the link over the one being impersonated", async () => {
+ vi.spyOn(ImpersonationState, "getServerSide").mockResolvedValue(TARGET_ID);
+
+ await ImpersonationPage({
+ searchParams: Promise.resolve({ user_id: "other-user" }),
+ });
+
+ expect(redirect).toHaveBeenCalledWith("/admin/users?user=other-user");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/page.tsx
index b6075a065d..14f01e631d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/impersonation/page.tsx
@@ -1,19 +1,18 @@
-import { AdminImpersonationPanel } from "../components/AdminImpersonationPanel";
-import { Text } from "@/components/atoms/Text/Text";
+import { ImpersonationState } from "@/lib/impersonation";
+import { redirect } from "next/navigation";
+import { getAdminUsersHref } from "../users/helpers";
-export default function AdminImpersonationPage() {
- return (
- <div className="container mx-auto space-y-6 py-6">
- <div className="space-y-2">
- <Text variant="h1" className="text-3xl font-bold tracking-tight">
- User Impersonation
- </Text>
- <Text variant="body" className="text-gray-600">
- Manage admin user impersonation for debugging and support purposes
- </Text>
- </div>
+interface SearchParams {
+ user?: string | string[];
+ user_id?: string | string[];
+}
- <AdminImpersonationPanel />
- </div>
- );
+export default async function ImpersonationPage({
+ searchParams,
+}: {
+ searchParams: Promise<SearchParams>;
+}) {
+ const { user, user_id } = await searchParams;
+ const impersonatedUserId = await ImpersonationState.getServerSide();
+ redirect(getAdminUsersHref(user ?? user_id ?? impersonatedUserId));
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/__tests__/page.test.tsx
new file mode 100644
index 0000000000..f0d6231aa1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/__tests__/page.test.tsx
@@ -0,0 +1,29 @@
+import { redirect } from "next/navigation";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import RateLimitsPage from "../page";
+
+vi.mock("next/navigation", () => ({ redirect: vi.fn() }));
+
+beforeEach(() => vi.mocked(redirect).mockReset());
+
+describe("/admin/rate-limits", () => {
+ it("sends a bookmark of the old page to the users page", async () => {
+ await RateLimitsPage({ searchParams: Promise.resolve({}) });
+
+ expect(redirect).toHaveBeenCalledWith("/admin/users");
+ });
+
+ it.each([
+ [
+ { user_id: "11111111-1111-4111-8111-111111111111" },
+ "11111111-1111-4111-8111-111111111111",
+ ],
+ [{ email: "[email protected]" }, "first_last%40example.com"],
+ [{ user: "[email protected]" }, "first_last%40example.com"],
+ [{ user_id: ["first-id", "second-id"] }, "first-id"],
+ ])("carries the user in %o", async (searchParams, expected) => {
+ await RateLimitsPage({ searchParams: Promise.resolve(searchParams) });
+
+ expect(redirect).toHaveBeenCalledWith(`/admin/users?user=${expected}`);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx
deleted file mode 100644
index 81ddc4bc90..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitManager.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-"use client";
-
-import { AdminUserSearch } from "../../components/AdminUserSearch";
-import { RateLimitDisplay } from "./RateLimitDisplay";
-import { useRateLimitManager } from "./useRateLimitManager";
-
-export function RateLimitManager() {
- const {
- isSearching,
- isLoadingRateLimit,
- searchResults,
- selectedUser,
- rateLimitData,
- tierMultipliers,
- handleSearch,
- handleSelectUser,
- handleReset,
- handleTierChange,
- } = useRateLimitManager();
-
- return (
- <div className="space-y-6">
- <div className="rounded-md border bg-white p-6">
- <label className="mb-2 block text-sm font-medium">Search User</label>
- <AdminUserSearch
- onSearch={handleSearch}
- placeholder="Search by name, email, or user ID..."
- isLoading={isSearching}
- />
- <p className="mt-1.5 text-xs text-gray-500">
- Exact email or user ID does a direct lookup. Partial text searches
- user history.
- </p>
- </div>
-
- {/* User selection list -- always require explicit selection */}
- {searchResults.length >= 1 && !selectedUser && (
- <div className="rounded-md border bg-white p-4">
- <h3 className="mb-2 text-sm font-medium text-gray-700">
- Select a user ({searchResults.length}{" "}
- {searchResults.length === 1 ? "result" : "results"})
- </h3>
- <ul className="divide-y">
- {searchResults.map((user) => (
- <li key={user.user_id}>
- <button
- className="w-full px-2 py-2 text-left text-sm hover:bg-gray-100"
- onClick={() => handleSelectUser(user)}
- >
- <span className="font-medium">{user.user_email}</span>
- <span className="ml-2 text-xs text-gray-500">
- {user.user_id}
- </span>
- </button>
- </li>
- ))}
- </ul>
- </div>
- )}
-
- {/* Show selected user */}
- {selectedUser && searchResults.length >= 1 && (
- <div className="rounded-md border border-blue-200 bg-blue-50 px-4 py-2 text-sm">
- Selected:{" "}
- <span className="font-medium">{selectedUser.user_email}</span>
- <span className="ml-2 text-xs text-gray-500">
- {selectedUser.user_id}
- </span>
- </div>
- )}
-
- {isLoadingRateLimit && (
- <div className="py-4 text-center text-sm text-gray-500">
- Loading rate limits...
- </div>
- )}
-
- {rateLimitData && (
- <RateLimitDisplay
- data={rateLimitData}
- onReset={handleReset}
- onTierChange={handleTierChange}
- tierMultipliers={tierMultipliers}
- />
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx
deleted file mode 100644
index 100a4de032..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitDisplay.test.tsx
+++ /dev/null
@@ -1,439 +0,0 @@
-import {
- render,
- screen,
- fireEvent,
- waitFor,
- cleanup,
-} from "@/tests/integrations/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { RateLimitDisplay } from "../RateLimitDisplay";
-import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
-
-const toastSpy = vi.hoisted(() => vi.fn());
-
-vi.mock("@/components/molecules/Toast/use-toast", () => ({
- useToast: () => ({ toast: toastSpy }),
-}));
-
-const mockConfirm = vi.fn();
-
-beforeEach(() => {
- mockConfirm.mockReset();
- toastSpy.mockClear();
- window.confirm = mockConfirm;
-});
-
-afterEach(() => {
- cleanup();
-});
-
-function makeData(
- overrides: Partial<UserRateLimitResponse> = {},
-): UserRateLimitResponse {
- return {
- user_id: "user-abc-123",
- user_email: "[email protected]",
- daily_cost_limit_microdollars: 10_000_000,
- weekly_cost_limit_microdollars: 50_000_000,
- daily_cost_used_microdollars: 2_500_000,
- weekly_cost_used_microdollars: 10_000_000,
- tier: "BASIC",
- ...overrides,
- };
-}
-
-describe("RateLimitDisplay", () => {
- it("renders the user email heading", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- expect(
- screen.getByText(/Rate Limits for alice@example\.com/),
- ).toBeDefined();
- });
-
- it("renders user ID when email is present", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- expect(screen.getByText(/user-abc-123/)).toBeDefined();
- });
-
- it("falls back to user_id in heading when email is absent", () => {
- render(
- <RateLimitDisplay
- data={makeData({ user_email: undefined })}
- onReset={vi.fn()}
- />,
- );
- expect(screen.getByText(/Rate Limits for user-abc-123/)).toBeDefined();
- });
-
- it("displays the current tier badge", () => {
- render(
- <RateLimitDisplay data={makeData({ tier: "PRO" })} onReset={vi.fn()} />,
- );
- const badge = screen.getByText("PRO");
- expect(badge).toBeDefined();
- expect(badge.className).toContain("bg-blue-100");
- });
-
- it("defaults unknown tier to NO_TIER", () => {
- render(
- <RateLimitDisplay
- data={makeData({ tier: "UNKNOWN" as UserRateLimitResponse["tier"] })}
- onReset={vi.fn()}
- />,
- );
- const badge = screen.getByText("NO_TIER");
- expect(badge).toBeDefined();
- expect(screen.queryByText("BASIC")).toBeNull();
- });
-
- it("displays NO_TIER as a first-class tier instead of masking as BASIC", () => {
- render(
- <RateLimitDisplay
- data={makeData({ tier: "NO_TIER" })}
- onReset={vi.fn()}
- />,
- );
- const badge = screen.getByText("NO_TIER");
- expect(badge).toBeDefined();
- expect(badge.className).toContain("bg-red-100");
- expect(screen.queryByText("BASIC")).toBeNull();
- expect(screen.getByText(/no access \(paywalled\)/)).toBeDefined();
-
- const select = screen.getByLabelText(
- "Subscription tier",
- ) as HTMLSelectElement;
- expect(select.value).toBe("NO_TIER");
- });
-
- it("renders tier dropdown with all tiers", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- const select = screen.getByLabelText("Subscription tier");
- expect(select).toBeDefined();
- expect(select.querySelectorAll("option").length).toBe(6);
- });
-
- it("disables tier dropdown when onTierChange is not provided", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- const select = screen.getByLabelText(
- "Subscription tier",
- ) as HTMLSelectElement;
- expect(select.disabled).toBe(true);
- });
-
- it("enables tier dropdown when onTierChange is provided", () => {
- render(
- <RateLimitDisplay
- data={makeData()}
- onReset={vi.fn()}
- onTierChange={vi.fn()}
- />,
- );
- const select = screen.getByLabelText(
- "Subscription tier",
- ) as HTMLSelectElement;
- expect(select.disabled).toBe(false);
- });
-
- it("renders daily and weekly usage sections", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- expect(screen.getByText("Daily Spend")).toBeDefined();
- expect(screen.getByText("Weekly Spend")).toBeDefined();
- });
-
- it("renders reset scope dropdown and reset button", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- expect(screen.getByLabelText("Reset scope")).toBeDefined();
- expect(screen.getByText("Reset Usage")).toBeDefined();
- });
-
- it("disables reset button when nothing to reset", () => {
- render(
- <RateLimitDisplay
- data={makeData({ daily_cost_used_microdollars: 0 })}
- onReset={vi.fn()}
- />,
- );
- const button = screen.getByText("Reset Usage").closest("button")!;
- expect(button.disabled).toBe(true);
- });
-
- it("enables reset button when there is usage to reset", () => {
- render(
- <RateLimitDisplay
- data={makeData({ daily_cost_used_microdollars: 100_000 })}
- onReset={vi.fn()}
- />,
- );
- const button = screen.getByText("Reset Usage").closest("button")!;
- expect(button.disabled).toBe(false);
- });
-
- it("calls onReset when reset button is clicked and confirmed", async () => {
- const onReset = vi.fn().mockResolvedValue(undefined);
- mockConfirm.mockReturnValue(true);
-
- render(<RateLimitDisplay data={makeData()} onReset={onReset} />);
-
- fireEvent.click(screen.getByText("Reset Usage"));
-
- await waitFor(() => {
- expect(onReset).toHaveBeenCalledWith(false);
- });
- });
-
- it("does not call onReset when confirm is cancelled", () => {
- const onReset = vi.fn();
- mockConfirm.mockReturnValue(false);
-
- render(<RateLimitDisplay data={makeData()} onReset={onReset} />);
-
- fireEvent.click(screen.getByText("Reset Usage"));
- expect(onReset).not.toHaveBeenCalled();
- });
-
- it("passes resetWeekly=true when 'both' is selected", async () => {
- const onReset = vi.fn().mockResolvedValue(undefined);
- mockConfirm.mockReturnValue(true);
-
- render(
- <RateLimitDisplay
- data={makeData({ weekly_cost_used_microdollars: 100_000 })}
- onReset={onReset}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Reset scope"), {
- target: { value: "both" },
- });
- fireEvent.click(screen.getByText("Reset Usage"));
-
- await waitFor(() => {
- expect(onReset).toHaveBeenCalledWith(true);
- });
- });
-
- it("calls onTierChange when tier is changed and confirmed", async () => {
- const onTierChange = vi.fn().mockResolvedValue(undefined);
- mockConfirm.mockReturnValue(true);
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "PRO" },
- });
-
- await waitFor(() => {
- expect(onTierChange).toHaveBeenCalledWith("PRO");
- });
- });
-
- it("shows a success toast when the tier change carries no warning", async () => {
- const onTierChange = vi.fn().mockResolvedValue(null);
- mockConfirm.mockReturnValue(true);
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "PRO" },
- });
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({ title: "Tier updated" }),
- );
- });
- });
-
- it("shows the backend warning when the Stripe sweep will revert the grant", async () => {
- const warning =
- "This user already has a Stripe customer with no active subscription.";
- const onTierChange = vi.fn().mockResolvedValue(warning);
- mockConfirm.mockReturnValue(true);
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "PRO" },
- });
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith({
- title: "Tier set to PRO, but Stripe will revert it",
- description: warning,
- variant: "destructive",
- });
- });
- expect(toastSpy).not.toHaveBeenCalledWith(
- expect.objectContaining({ title: "Tier updated" }),
- );
- });
-
- it("does not call onTierChange when selecting the same tier", () => {
- const onTierChange = vi.fn();
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "BASIC" },
- });
-
- expect(onTierChange).not.toHaveBeenCalled();
- });
-
- it("does not call onTierChange when confirm is cancelled", () => {
- const onTierChange = vi.fn();
- mockConfirm.mockReturnValue(false);
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "PRO" },
- });
-
- expect(onTierChange).not.toHaveBeenCalled();
- });
-
- it("catches error when onTierChange rejects", async () => {
- const onTierChange = vi.fn().mockRejectedValue(new Error("fail"));
- mockConfirm.mockReturnValue(true);
-
- render(
- <RateLimitDisplay
- data={makeData({ tier: "BASIC" })}
- onReset={vi.fn()}
- onTierChange={onTierChange}
- />,
- );
-
- fireEvent.change(screen.getByLabelText("Subscription tier"), {
- target: { value: "PRO" },
- });
-
- await waitFor(() => {
- expect(onTierChange).toHaveBeenCalledWith("PRO");
- });
- });
-
- it("shows live multiplier label for PRO from the tierMultipliers map", () => {
- render(
- <RateLimitDisplay
- data={makeData({ tier: "PRO" })}
- onReset={vi.fn()}
- tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
- />,
- );
- const select = screen.getByLabelText("Subscription tier");
- expect(select.textContent).toContain("PRO — 5× base limits");
- });
-
- it("renders a non-default fractional multiplier (MAX 42.66) from the map", () => {
- render(
- <RateLimitDisplay
- data={makeData()}
- onReset={vi.fn()}
- tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
- />,
- );
- const select = screen.getByLabelText("Subscription tier");
- expect(select.textContent).toContain("MAX — 42.66× base limits");
- // The old hardcoded "20x" value must not appear.
- expect(select.textContent).not.toContain("20x");
- });
-
- it("keeps NO_TIER paywalled label even with a multipliers map present", () => {
- render(
- <RateLimitDisplay
- data={makeData({ tier: "NO_TIER" })}
- onReset={vi.fn()}
- tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
- />,
- );
- expect(screen.getByText(/no access \(paywalled\)/)).toBeDefined();
- const select = screen.getByLabelText("Subscription tier");
- expect(select.textContent).not.toContain("NO_TIER — 0");
- });
-
- it("does not fabricate a number for a tier missing from the map", () => {
- render(
- <RateLimitDisplay
- data={makeData()}
- onReset={vi.fn()}
- tierMultipliers={{ BASIC: 1, PRO: 5, MAX: 42.66 }}
- />,
- );
- const select = screen.getByLabelText("Subscription tier");
- // ENTERPRISE has no entry -> generic label, never a hardcoded multiplier.
- expect(select.textContent).toContain("ENTERPRISE — tier limits");
- expect(select.textContent).not.toContain("ENTERPRISE — 60");
- });
-
- it("shows the multiplier for ENTERPRISE when present in the full map", () => {
- render(
- <RateLimitDisplay
- data={makeData()}
- onReset={vi.fn()}
- tierMultipliers={{
- NO_TIER: 0,
- BASIC: 1,
- PRO: 5,
- BUSINESS: 20,
- ENTERPRISE: 60,
- }}
- />,
- );
- const select = screen.getByLabelText("Subscription tier");
- expect(select.textContent).toContain("ENTERPRISE — 60× base limits");
- expect(select.textContent).toContain("BUSINESS — 20× base limits");
- expect(select.textContent).not.toContain("ENTERPRISE — tier limits");
- // NO_TIER's 0 short-circuits to the paywalled label, not "0× base limits".
- expect(select.textContent).toContain("NO_TIER — no access (paywalled)");
- });
-
- it("falls back to generic labels when no multipliers map is provided", () => {
- render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
- const select = screen.getByLabelText("Subscription tier");
- expect(select.textContent).toContain("PRO — tier limits");
- expect(select.textContent).not.toContain("5x");
- });
-
- it("applies custom className when provided", () => {
- const { container } = render(
- <RateLimitDisplay
- data={makeData()}
- onReset={vi.fn()}
- className="custom-class"
- />,
- );
- expect(container.firstElementChild?.className).toBe("custom-class");
- });
-});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx
deleted file mode 100644
index a52b013b5b..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx
+++ /dev/null
@@ -1,492 +0,0 @@
-import {
- render,
- screen,
- fireEvent,
- waitFor,
- cleanup,
-} from "@/tests/integrations/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { server } from "@/mocks/mock-server";
-import {
- getGetV2GetUserRateLimitMockHandler,
- getGetV2GetUserRateLimitMockHandler200,
- getGetV2SearchUsersByNameOrEmailMockHandler200,
- getPostV2ResetUserRateLimitUsageMockHandler200,
- getPostV2SetUserRateLimitTierMockHandler200,
-} from "@/app/api/__generated__/endpoints/admin/admin.msw";
-import { http, HttpResponse } from "msw";
-import { RateLimitManager } from "../RateLimitManager";
-import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
-import { isKey } from "@/lib/keyboard";
-
-const toastSpy = vi.hoisted(() => vi.fn());
-const tierChangeResult = vi.hoisted(() => ({ value: undefined as unknown }));
-
-vi.mock("@/components/molecules/Toast/use-toast", () => ({
- useToast: () => ({ toast: toastSpy }),
- toast: toastSpy,
-}));
-
-vi.mock("../../../components/AdminUserSearch", () => ({
- AdminUserSearch: ({
- onSearch,
- placeholder,
- isLoading,
- }: {
- onSearch: (q: string) => void;
- placeholder: string;
- isLoading: boolean;
- }) => (
- <div data-testid="admin-user-search">
- <input
- data-testid="search-input"
- placeholder={placeholder}
- disabled={isLoading}
- onKeyDown={(e) => {
- if (isKey(e, "Enter")) onSearch((e.target as HTMLInputElement).value);
- }}
- />
- </div>
- ),
-}));
-
-vi.mock("../RateLimitDisplay", () => ({
- RateLimitDisplay: ({
- data,
- onReset,
- onTierChange,
- }: {
- data: UserRateLimitResponse;
- onReset: (rw: boolean) => Promise<void>;
- onTierChange: (t: string) => Promise<string | null>;
- }) => (
- <div data-testid="rate-limit-display">
- <span>{data.user_email ?? data.user_id}</span>
- <span data-testid="display-tier">{data.tier}</span>
- <span data-testid="display-daily-used">
- {data.daily_cost_used_microdollars}
- </span>
- <button
- onClick={() => {
- onReset(false).catch(() => {});
- }}
- >
- mock-reset
- </button>
- <button
- onClick={() => {
- onTierChange("PRO")
- .then((result) => {
- tierChangeResult.value = result;
- })
- .catch(() => {});
- }}
- >
- mock-tier
- </button>
- </div>
- ),
-}));
-
-const RATE_LIMIT_URL =
- "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit";
-const SEARCH_URL =
- "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/search_users";
-const RESET_URL =
- "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/reset";
-const TIER_URL =
- "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/tier";
-
-function makeRateLimit(
- overrides: Partial<UserRateLimitResponse> = {},
-): UserRateLimitResponse {
- return {
- user_id: "user-123",
- user_email: "[email protected]",
- daily_cost_limit_microdollars: 10_000_000,
- weekly_cost_limit_microdollars: 50_000_000,
- daily_cost_used_microdollars: 2_500_000,
- weekly_cost_used_microdollars: 10_000_000,
- tier: "BASIC",
- ...overrides,
- };
-}
-
-function typeAndSearch(query: string) {
- const input = screen.getByTestId("search-input") as HTMLInputElement;
- fireEvent.keyDown(input, { key: "Enter", target: { value: query } });
-}
-
-beforeEach(() => {
- toastSpy.mockClear();
- tierChangeResult.value = undefined;
-});
-
-afterEach(() => {
- cleanup();
-});
-
-describe("RateLimitManager - rendering", () => {
- it("renders the search section", () => {
- render(<RateLimitManager />);
- expect(screen.getByText("Search User")).toBeDefined();
- expect(screen.getByTestId("admin-user-search")).toBeDefined();
- });
-
- it("renders description text for search", () => {
- render(<RateLimitManager />);
- expect(
- screen.getByText(/Exact email or user ID does a direct lookup/),
- ).toBeDefined();
- });
-
- it("does not show user list initially", () => {
- render(<RateLimitManager />);
- expect(screen.queryByText(/Select a user/)).toBeNull();
- });
-
- it("does not render RateLimitDisplay initially", () => {
- render(<RateLimitManager />);
- expect(screen.queryByTestId("rate-limit-display")).toBeNull();
- });
-});
-
-describe("RateLimitManager - search behavior", () => {
- it("performs a direct lookup for an email and shows the rate limit display", async () => {
- const data = makeRateLimit();
- server.use(getGetV2GetUserRateLimitMockHandler200(data));
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- expect(await screen.findByTestId("rate-limit-display")).toBeDefined();
- expect(screen.getByText("[email protected]")).toBeDefined();
- });
-
- it("performs a direct lookup for a UUID and shows the rate limit display", async () => {
- const uuid = "550e8400-e29b-41d4-a716-446655440000";
- const data = makeRateLimit({ user_id: uuid });
- server.use(getGetV2GetUserRateLimitMockHandler200(data));
-
- render(<RateLimitManager />);
- typeAndSearch(uuid);
-
- expect(await screen.findByTestId("rate-limit-display")).toBeDefined();
- });
-
- it("shows error toast on direct lookup failure", async () => {
- server.use(
- http.get(RATE_LIMIT_URL, () =>
- HttpResponse.json({ detail: "not found" }, { status: 404 }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Error",
- variant: "destructive",
- }),
- );
- });
- expect(screen.queryByTestId("rate-limit-display")).toBeNull();
- });
-
- it("does fuzzy search for partial text and renders the result list", async () => {
- server.use(
- getGetV2SearchUsersByNameOrEmailMockHandler200([
- { user_id: "u1", user_email: "[email protected]" },
- { user_id: "u2", user_email: "[email protected]" },
- ]),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("alice");
-
- expect(await screen.findByText("Select a user (2 results)")).toBeDefined();
- expect(screen.getByText("[email protected]")).toBeDefined();
- expect(screen.getByText("[email protected]")).toBeDefined();
- });
-
- it("shows toast when fuzzy search returns no results", async () => {
- server.use(getGetV2SearchUsersByNameOrEmailMockHandler200([]));
-
- render(<RateLimitManager />);
- typeAndSearch("nonexistent");
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({ title: "No results" }),
- );
- });
- });
-
- it("shows error toast on fuzzy search failure", async () => {
- server.use(
- http.get(SEARCH_URL, () =>
- HttpResponse.json({ detail: "boom" }, { status: 500 }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("alice");
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Error",
- variant: "destructive",
- }),
- );
- });
- });
-});
-
-describe("RateLimitManager - user selection list", () => {
- it("shows singular 'result' text for single result", async () => {
- server.use(
- getGetV2SearchUsersByNameOrEmailMockHandler200([
- { user_id: "u1", user_email: "[email protected]" },
- ]),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("alice");
-
- expect(await screen.findByText("Select a user (1 result)")).toBeDefined();
- });
-
- it("loads rate limit display when a user in the list is clicked", async () => {
- const users = [
- { user_id: "u1", user_email: "[email protected]" },
- { user_id: "u2", user_email: "[email protected]" },
- ];
- server.use(
- getGetV2SearchUsersByNameOrEmailMockHandler200(users),
- getGetV2GetUserRateLimitMockHandler200(
- makeRateLimit({ user_id: "u2", user_email: "[email protected]" }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("user");
-
- fireEvent.click(await screen.findByText("[email protected]"));
-
- expect(await screen.findByTestId("rate-limit-display")).toBeDefined();
- expect(screen.getByText("Selected:")).toBeDefined();
- });
-
- it("shows error toast when fetching rate limit for selected user fails", async () => {
- server.use(
- getGetV2SearchUsersByNameOrEmailMockHandler200([
- { user_id: "u1", user_email: "[email protected]" },
- ]),
- http.get(RATE_LIMIT_URL, () =>
- HttpResponse.json({ detail: "boom" }, { status: 500 }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("alice");
-
- fireEvent.click(await screen.findByText("[email protected]"));
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Error",
- variant: "destructive",
- }),
- );
- });
- expect(screen.queryByTestId("rate-limit-display")).toBeNull();
- });
-});
-
-describe("RateLimitManager - reset and tier change", () => {
- it("calls reset endpoint, updates rate limit data, and shows success toast", async () => {
- const initial = makeRateLimit({ daily_cost_used_microdollars: 5_000_000 });
- const after = makeRateLimit({ daily_cost_used_microdollars: 0 });
-
- server.use(
- getGetV2GetUserRateLimitMockHandler200(initial),
- getPostV2ResetUserRateLimitUsageMockHandler200(after),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await screen.findByTestId("rate-limit-display");
- fireEvent.click(screen.getByText("mock-reset"));
-
- await waitFor(() => {
- expect(screen.getByTestId("display-daily-used").textContent).toBe("0");
- });
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({ title: "Success" }),
- );
- });
-
- it("shows error toast when reset endpoint fails", async () => {
- server.use(
- getGetV2GetUserRateLimitMockHandler200(makeRateLimit()),
- http.post(RESET_URL, () =>
- HttpResponse.json({ detail: "boom" }, { status: 500 }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await screen.findByTestId("rate-limit-display");
- fireEvent.click(screen.getByText("mock-reset"));
-
- await waitFor(() => {
- expect(toastSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Error",
- description: "Failed to reset rate limit usage.",
- variant: "destructive",
- }),
- );
- });
- });
-
- it("changes tier and re-fetches the rate limit data", async () => {
- let callCount = 0;
- server.use(
- http.get(RATE_LIMIT_URL, () => {
- callCount += 1;
- const tier = callCount === 1 ? "BASIC" : "PRO";
- return HttpResponse.json(makeRateLimit({ tier }), { status: 200 });
- }),
- getPostV2SetUserRateLimitTierMockHandler200(),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await waitFor(() =>
- expect(screen.getByTestId("display-tier").textContent).toBe("BASIC"),
- );
-
- fireEvent.click(screen.getByText("mock-tier"));
-
- await waitFor(() =>
- expect(screen.getByTestId("display-tier").textContent).toBe("PRO"),
- );
- });
-
- it("passes the sweep-revert warning from the set-tier response to the display", async () => {
- const warning =
- "The Stripe reconciliation sweep will revert this PRO grant to NO_TIER within 6 hours.";
- server.use(
- http.get(RATE_LIMIT_URL, () =>
- HttpResponse.json(makeRateLimit({ tier: "PRO" }), { status: 200 }),
- ),
- http.post(TIER_URL, () =>
- HttpResponse.json(
- { user_id: "user-123", tier: "PRO", warning },
- { status: 200 },
- ),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await screen.findByTestId("rate-limit-display");
- fireEvent.click(screen.getByText("mock-tier"));
-
- await waitFor(() => {
- expect(tierChangeResult.value).toBe(warning);
- });
- });
-
- it("resolves with no warning when the set-tier response has none", async () => {
- server.use(
- getGetV2GetUserRateLimitMockHandler200(makeRateLimit({ tier: "PRO" })),
- http.post(TIER_URL, () =>
- HttpResponse.json(
- { user_id: "user-123", tier: "PRO" },
- { status: 200 },
- ),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await screen.findByTestId("rate-limit-display");
- fireEvent.click(screen.getByText("mock-tier"));
-
- await waitFor(() => {
- expect(tierChangeResult.value).toBeNull();
- });
- });
-
- it("does not update tier when the set-tier endpoint fails", async () => {
- let getCount = 0;
- server.use(
- http.get(RATE_LIMIT_URL, () => {
- getCount += 1;
- return HttpResponse.json(makeRateLimit({ tier: "BASIC" }), {
- status: 200,
- });
- }),
- http.post(TIER_URL, () =>
- HttpResponse.json({ detail: "boom" }, { status: 500 }),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("[email protected]");
-
- await screen.findByTestId("rate-limit-display");
- expect(getCount).toBe(1);
-
- fireEvent.click(screen.getByText("mock-tier"));
-
- // The hook throws on non-200, so it never re-fetches. The displayed tier
- // should remain BASIC and no second GET should fire.
- await waitFor(() => {
- expect(screen.getByTestId("display-tier").textContent).toBe("BASIC");
- });
- expect(getCount).toBe(1);
- });
-
- it("does not render RateLimitDisplay when search returns no rate limit data", () => {
- // Default initial render: ensure the display is gated on rateLimitData.
- render(<RateLimitManager />);
- expect(screen.queryByTestId("rate-limit-display")).toBeNull();
- });
-});
-
-describe("RateLimitManager - loading states", () => {
- it("shows loading message while fetching rate limit after selecting user", async () => {
- server.use(
- getGetV2SearchUsersByNameOrEmailMockHandler200([
- { user_id: "u1", user_email: "[email protected]" },
- ]),
- // Delayed handler so we can observe the loading state
- getGetV2GetUserRateLimitMockHandler(
- async () =>
- new Promise<UserRateLimitResponse>((resolve) =>
- setTimeout(() => resolve(makeRateLimit()), 50),
- ),
- ),
- );
-
- render(<RateLimitManager />);
- typeAndSearch("alice");
-
- fireEvent.click(await screen.findByText("[email protected]"));
-
- expect(await screen.findByText("Loading rate limits...")).toBeDefined();
- expect(await screen.findByTestId("rate-limit-display")).toBeDefined();
- });
-});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts
deleted file mode 100644
index 1c72b4ff5e..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/useRateLimitManager.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useToast } from "@/components/molecules/Toast/use-toast";
-import type { SetUserTierRequest } from "@/app/api/__generated__/models/setUserTierRequest";
-import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
-import {
- getV2GetUserRateLimit,
- getV2SearchUsersByNameOrEmail,
- postV2ResetUserRateLimitUsage,
- postV2SetUserRateLimitTier,
-} from "@/app/api/__generated__/endpoints/admin/admin";
-
-export interface UserOption {
- user_id: string;
- user_email: string;
-}
-
-function looksLikeEmail(input: string): boolean {
- return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input);
-}
-
-function looksLikeUuid(input: string): boolean {
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
- input,
- );
-}
-
-export function useRateLimitManager() {
- const { toast } = useToast();
- const [isSearching, setIsSearching] = useState(false);
- const [isLoadingRateLimit, setIsLoadingRateLimit] = useState(false);
- const [searchResults, setSearchResults] = useState<UserOption[]>([]);
- const [selectedUser, setSelectedUser] = useState<UserOption | null>(null);
- const [rateLimitData, setRateLimitData] =
- useState<UserRateLimitResponse | null>(null);
-
- const tierMultipliers = rateLimitData?.tier_multipliers;
-
- async function handleDirectLookup(trimmed: string) {
- setIsSearching(true);
- setSearchResults([]);
- setSelectedUser(null);
- setRateLimitData(null);
-
- try {
- const params = looksLikeEmail(trimmed)
- ? { email: trimmed }
- : { user_id: trimmed };
- const response = await getV2GetUserRateLimit(params);
- if (response.status !== 200) {
- throw new Error("Failed to fetch rate limit");
- }
- setRateLimitData(response.data);
- setSelectedUser({
- user_id: response.data.user_id,
- user_email: response.data.user_email ?? response.data.user_id,
- });
- } catch (error) {
- console.error("Error fetching rate limit:", error);
- const hint = looksLikeEmail(trimmed)
- ? "No user found with that email address."
- : "Check the user ID and try again.";
- toast({
- title: "Error",
- description: `Failed to fetch rate limits. ${hint}`,
- variant: "destructive",
- });
- setRateLimitData(null);
- } finally {
- setIsSearching(false);
- }
- }
-
- async function handleFuzzySearch(trimmed: string) {
- setIsSearching(true);
- setSearchResults([]);
- setSelectedUser(null);
- setRateLimitData(null);
-
- try {
- const response = await getV2SearchUsersByNameOrEmail({
- query: trimmed,
- limit: 20,
- });
- if (response.status !== 200) {
- throw new Error("Failed to search users");
- }
-
- const users = (response.data ?? []).map((u) => ({
- user_id: u.user_id,
- user_email: u.user_email ?? u.user_id,
- }));
- if (users.length === 0) {
- toast({ title: "No results", description: "No users found." });
- }
- setSearchResults(users);
- } catch (error) {
- console.error("Error searching users:", error);
- toast({
- title: "Error",
- description: "Failed to search users.",
- variant: "destructive",
- });
- } finally {
- setIsSearching(false);
- }
- }
-
- async function handleSearch(query: string) {
- const trimmed = query.trim();
- if (!trimmed) return;
-
- // Direct lookup when the input is a full email or UUID.
- // This avoids the spending-history indirection and works even for
- // users who have no credit transaction history.
- if (looksLikeEmail(trimmed) || looksLikeUuid(trimmed)) {
- await handleDirectLookup(trimmed);
- } else {
- await handleFuzzySearch(trimmed);
- }
- }
-
- async function fetchRateLimit(userId: string) {
- setIsLoadingRateLimit(true);
- try {
- const response = await getV2GetUserRateLimit({ user_id: userId });
- if (response.status !== 200) {
- throw new Error("Failed to fetch rate limit");
- }
- setRateLimitData(response.data);
- } catch (error) {
- console.error("Error fetching rate limit:", error);
- toast({
- title: "Error",
- description: "Failed to fetch user rate limit.",
- variant: "destructive",
- });
- setRateLimitData(null);
- } finally {
- setIsLoadingRateLimit(false);
- }
- }
-
- async function handleSelectUser(user: UserOption) {
- setSelectedUser(user);
- setRateLimitData(null);
- await fetchRateLimit(user.user_id);
- }
-
- async function handleReset(resetWeekly: boolean) {
- if (!rateLimitData) return;
-
- try {
- const response = await postV2ResetUserRateLimitUsage({
- user_id: rateLimitData.user_id,
- reset_weekly: resetWeekly,
- });
- if (response.status !== 200) {
- throw new Error("Failed to reset usage");
- }
- setRateLimitData(response.data);
- toast({
- title: "Success",
- description: resetWeekly
- ? "Daily and weekly usage reset to zero."
- : "Daily usage reset to zero.",
- });
- } catch (error) {
- console.error("Error resetting rate limit:", error);
- toast({
- title: "Error",
- description: "Failed to reset rate limit usage.",
- variant: "destructive",
- });
- }
- }
-
- async function handleTierChange(newTier: string) {
- if (!rateLimitData) return null;
-
- const response = await postV2SetUserRateLimitTier({
- user_id: rateLimitData.user_id,
- tier: newTier as SetUserTierRequest["tier"],
- });
-
- if (response.status !== 200) {
- throw new Error("Failed to update tier");
- }
-
- const warning = response.data.warning ?? null;
-
- // Re-fetch rate limit data to reflect new tier-adjusted limits.
- try {
- const refreshResponse = await getV2GetUserRateLimit({
- user_id: rateLimitData.user_id,
- });
- if (refreshResponse.status === 200) {
- setRateLimitData(refreshResponse.data);
- }
- } catch {
- // Tier was changed server-side; UI will be stale but not incorrect.
- // The caller's success toast is still valid — the tier change worked.
- }
- return warning;
- }
-
- return {
- isSearching,
- isLoadingRateLimit,
- searchResults,
- selectedUser,
- rateLimitData,
- tierMultipliers,
- handleSearch,
- handleSelectUser,
- handleReset,
- handleTierChange,
- };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/page.tsx
index 5eacf1c7ec..3b8df7aaf7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/page.tsx
@@ -1,25 +1,17 @@
-import { withRoleAccess } from "@/lib/withRoleAccess";
-import { RateLimitManager } from "./components/RateLimitManager";
+import { redirect } from "next/navigation";
+import { getAdminUsersHref } from "../users/helpers";
-function RateLimitsDashboard() {
- return (
- <div className="mx-auto p-6">
- <div className="flex flex-col gap-4">
- <div>
- <h1 className="text-3xl font-bold">User Rate Limits</h1>
- <p className="text-gray-500">
- Check and manage CoPilot rate limits per user
- </p>
- </div>
- <RateLimitManager />
- </div>
- </div>
- );
+interface SearchParams {
+ user?: string | string[];
+ user_id?: string | string[];
+ email?: string | string[];
}
-export default async function RateLimitsDashboardPage() {
- "use server";
- const withAdminAccess = await withRoleAccess(["admin"]);
- const ProtectedDashboard = await withAdminAccess(RateLimitsDashboard);
- return <ProtectedDashboard />;
+export default async function RateLimitsPage({
+ searchParams,
+}: {
+ searchParams: Promise<SearchParams>;
+}) {
+ const { user, user_id, email } = await searchParams;
+ redirect(getAdminUsersHref(user ?? user_id ?? email));
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/RateLimitDisplay.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/RateLimitDisplay.test.tsx
new file mode 100644
index 0000000000..8a654f35a6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/RateLimitDisplay.test.tsx
@@ -0,0 +1,210 @@
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+} from "@/tests/integrations/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RateLimitDisplay } from "../components/RateLimitDisplay";
+import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
+
+const mockConfirm = vi.fn();
+
+beforeEach(() => {
+ mockConfirm.mockReset();
+ window.confirm = mockConfirm;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+function makeData(
+ overrides: Partial<UserRateLimitResponse> = {},
+): UserRateLimitResponse {
+ return {
+ user_id: "user-abc-123",
+ user_email: "[email protected]",
+ daily_cost_limit_microdollars: 10_000_000,
+ weekly_cost_limit_microdollars: 50_000_000,
+ daily_cost_used_microdollars: 2_500_000,
+ weekly_cost_used_microdollars: 10_000_000,
+ tier: "BASIC",
+ ...overrides,
+ };
+}
+
+describe("RateLimitDisplay", () => {
+ it("renders the user email heading", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ expect(
+ screen.getByText(/Rate Limits for alice@example\.com/),
+ ).toBeDefined();
+ });
+
+ it("renders user ID when email is present", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ expect(screen.getByText(/user-abc-123/)).toBeDefined();
+ });
+
+ it("falls back to user_id in heading when email is absent", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ user_email: undefined })}
+ onReset={vi.fn()}
+ />,
+ );
+ expect(screen.getByText(/Rate Limits for user-abc-123/)).toBeDefined();
+ });
+
+ it("displays the current tier badge", () => {
+ render(
+ <RateLimitDisplay data={makeData({ tier: "PRO" })} onReset={vi.fn()} />,
+ );
+ const badge = screen.getByText("PRO");
+ expect(badge).toBeDefined();
+ expect(badge.className).toContain("bg-blue-100");
+ });
+
+ it("defaults unknown tier to NO_TIER", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ tier: "UNKNOWN" as UserRateLimitResponse["tier"] })}
+ onReset={vi.fn()}
+ />,
+ );
+ const badge = screen.getByText("NO_TIER");
+ expect(badge).toBeDefined();
+ expect(screen.queryByText("BASIC")).toBeNull();
+ });
+
+ it("displays NO_TIER as a first-class tier instead of masking as BASIC", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ tier: "NO_TIER" })}
+ onReset={vi.fn()}
+ />,
+ );
+ const badge = screen.getByText("NO_TIER");
+ expect(badge).toBeDefined();
+ expect(badge.className).toContain("bg-red-100");
+ expect(screen.queryByText("BASIC")).toBeNull();
+ expect(screen.getByText(/no access \(paywalled\)/)).toBeDefined();
+
+ const select = screen.getByLabelText(
+ "Subscription tier",
+ ) as HTMLSelectElement;
+ expect(select.value).toBe("NO_TIER");
+ });
+
+ it("renders tier dropdown with all tiers", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select).toBeDefined();
+ expect(select.querySelectorAll("option").length).toBe(6);
+ });
+
+ it("shows the tier read-only", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ const select = screen.getByLabelText(
+ "Subscription tier",
+ ) as HTMLSelectElement;
+ expect(select.disabled).toBe(true);
+ });
+
+ it("renders daily and weekly usage sections", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ expect(screen.getByText("Daily Spend")).toBeDefined();
+ expect(screen.getByText("Weekly Spend")).toBeDefined();
+ });
+
+ it("renders reset scope dropdown and reset button", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ expect(screen.getByLabelText("Reset scope")).toBeDefined();
+ expect(screen.getByText("Reset Usage")).toBeDefined();
+ });
+
+ it("disables reset button when nothing to reset", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ daily_cost_used_microdollars: 0 })}
+ onReset={vi.fn()}
+ />,
+ );
+ const button = screen.getByText("Reset Usage").closest("button")!;
+ expect(button.disabled).toBe(true);
+ });
+
+ it("enables reset button when there is usage to reset", () => {
+ render(
+ <RateLimitDisplay
+ data={makeData({ daily_cost_used_microdollars: 100_000 })}
+ onReset={vi.fn()}
+ />,
+ );
+ const button = screen.getByText("Reset Usage").closest("button")!;
+ expect(button.disabled).toBe(false);
+ });
+
+ it("calls onReset when reset button is clicked and confirmed", async () => {
+ const onReset = vi.fn().mockResolvedValue(undefined);
+ mockConfirm.mockReturnValue(true);
+
+ render(<RateLimitDisplay data={makeData()} onReset={onReset} />);
+
+ fireEvent.click(screen.getByText("Reset Usage"));
+
+ await waitFor(() => {
+ expect(onReset).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it("does not call onReset when confirm is cancelled", () => {
+ const onReset = vi.fn();
+ mockConfirm.mockReturnValue(false);
+
+ render(<RateLimitDisplay data={makeData()} onReset={onReset} />);
+
+ fireEvent.click(screen.getByText("Reset Usage"));
+ expect(onReset).not.toHaveBeenCalled();
+ });
+
+ it("passes resetWeekly=true when 'both' is selected", async () => {
+ const onReset = vi.fn().mockResolvedValue(undefined);
+ mockConfirm.mockReturnValue(true);
+
+ render(
+ <RateLimitDisplay
+ data={makeData({ weekly_cost_used_microdollars: 100_000 })}
+ onReset={onReset}
+ />,
+ );
+
+ fireEvent.change(screen.getByLabelText("Reset scope"), {
+ target: { value: "both" },
+ });
+ fireEvent.click(screen.getByText("Reset Usage"));
+
+ await waitFor(() => {
+ expect(onReset).toHaveBeenCalledWith(true);
+ });
+ });
+
+ it("labels every paid tier generically", () => {
+ render(<RateLimitDisplay data={makeData()} onReset={vi.fn()} />);
+ const select = screen.getByLabelText("Subscription tier");
+ expect(select.textContent).toContain("PRO — tier limits");
+ });
+
+ it("applies custom className when provided", () => {
+ const { container } = render(
+ <RateLimitDisplay
+ data={makeData()}
+ onReset={vi.fn()}
+ className="custom-class"
+ />,
+ );
+ expect(container.firstElementChild?.className).toBe("custom-class");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitDisplay.tsx
similarity index 63%
rename from autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx
rename to autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitDisplay.tsx
index 68b306acf9..c444cf6075 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/RateLimitDisplay.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitDisplay.tsx
@@ -3,7 +3,6 @@
import { useState } from "react";
import { Button } from "@/components/atoms/Button/Button";
import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
-import { useToast } from "@/components/molecules/Toast/use-toast";
import { UsageBar } from "../../components/UsageBar";
const TIERS = [
@@ -25,44 +24,20 @@ const TIER_COLORS: Record<Tier, string> = {
ENTERPRISE: "bg-amber-100 text-amber-700",
};
-// Derives the per-tier label from the live, LaunchDarkly-driven multiplier map.
-// NO_TIER is paywalled (0 / absent), and tiers missing from the map fall back
-// to a generic label rather than a fabricated number.
-function tierLabel(
- tier: Tier,
- tierMultipliers?: Record<string, number>,
-): string {
- if (tier === "NO_TIER") return "no access (paywalled)";
-
- const multiplier = tierMultipliers?.[tier];
- if (multiplier === undefined || multiplier <= 0) return "tier limits";
-
- // Round to at most 2 decimals (5 → "5", 42.664 → "42.66").
- const rounded = Math.round(multiplier * 100) / 100;
- return `${rounded}× base limits`;
+function tierLabel(tier: Tier): string {
+ return tier === "NO_TIER" ? "no access (paywalled)" : "tier limits";
}
interface Props {
data: UserRateLimitResponse;
onReset: (resetWeekly: boolean) => Promise<void>;
- onTierChange?: (newTier: string) => Promise<string | null>;
- /** Full per-tier multiplier map (incl. admin-managed tiers) from the admin rate-limit endpoint. */
- tierMultipliers?: Record<string, number>;
/** Override the outer container classes (default: bordered card). */
className?: string;
}
-export function RateLimitDisplay({
- data,
- onReset,
- onTierChange,
- tierMultipliers,
- className,
-}: Props) {
+export function RateLimitDisplay({ data, onReset, className }: Props) {
const [isResetting, setIsResetting] = useState(false);
const [resetWeekly, setResetWeekly] = useState(false);
- const [isChangingTier, setIsChangingTier] = useState(false);
- const { toast } = useToast();
const currentTier = TIERS.includes(data.tier as Tier)
? (data.tier as Tier)
@@ -82,41 +57,6 @@ export function RateLimitDisplay({
}
}
- async function handleTierChange(newTier: string) {
- if (newTier === currentTier || !onTierChange) return;
- if (
- !window.confirm(
- `Change tier from ${currentTier} to ${newTier}? This will change the user's rate limits.`,
- )
- )
- return;
-
- setIsChangingTier(true);
- try {
- const warning = await onTierChange(newTier);
- if (warning) {
- toast({
- title: `Tier set to ${newTier}, but Stripe will revert it`,
- description: warning,
- variant: "destructive",
- });
- return;
- }
- toast({
- title: "Tier updated",
- description: `Changed to ${newTier} (${tierLabel(newTier as Tier, tierMultipliers)}).`,
- });
- } catch {
- toast({
- title: "Error",
- description: "Failed to update tier.",
- variant: "destructive",
- });
- } finally {
- setIsChangingTier(false);
- }
- }
-
const nothingToReset = resetWeekly
? data.daily_cost_used_microdollars === 0 &&
data.weekly_cost_used_microdollars === 0
@@ -147,19 +87,15 @@ export function RateLimitDisplay({
<select
aria-label="Subscription tier"
value={currentTier}
- onChange={(e) => handleTierChange(e.target.value)}
className="rounded-md border bg-white px-3 py-1.5 text-sm"
- disabled={isChangingTier || !onTierChange}
+ disabled
>
{TIERS.map((tier) => (
<option key={tier} value={tier}>
- {tier} — {tierLabel(tier, tierMultipliers)}
+ {tier} — {tierLabel(tier)}
</option>
))}
</select>
- {isChangingTier && (
- <span className="text-xs text-gray-500">Updating...</span>
- )}
</div>
<div className="grid grid-cols-2 gap-6">
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitModal.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitModal.tsx
index b8a4ba64bb..847fd5ddc7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitModal.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/RateLimitModal.tsx
@@ -15,7 +15,7 @@ import {
getV2GetUserRateLimit,
postV2ResetUserRateLimitUsage,
} from "@/app/api/__generated__/endpoints/admin/admin";
-import { RateLimitDisplay } from "../../rate-limits/components/RateLimitDisplay";
+import { RateLimitDisplay } from "./RateLimitDisplay";
import { GaugeIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/AdminUsersView.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/AdminUsersView.test.tsx
new file mode 100644
index 0000000000..b342634b4a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/AdminUsersView.test.tsx
@@ -0,0 +1,381 @@
+import { ImpersonationState } from "@/lib/impersonation";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@/tests/integrations/test-utils";
+import { http, HttpResponse } from "msw";
+import { NuqsTestingAdapter } from "nuqs/adapters/testing";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AdminUsersView } from "../components/AdminUsersView/AdminUsersView";
+
+const mockToast = vi.hoisted(() => vi.fn());
+const auth = vi.hoisted(() => ({
+ user: { id: "admin-self" } as { id: string } | null,
+}));
+const reloadMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user: auth.user }),
+}));
+
+const ALEX = {
+ id: "5d0a1c2e-0000-4000-8000-000000000001",
+ email: "[email protected]",
+ name: "Alex Rivera",
+ image: null,
+ role: "user",
+ emailVerified: true,
+ createdAt: "2026-03-12T10:00:00.000Z",
+ updatedAt: "2026-03-12T10:00:00.000Z",
+ banned: false,
+ banReason: null,
+ banExpires: null,
+};
+
+const ORGANISATION = {
+ id: "org-1",
+ name: "Acme Inc",
+ slug: "acme",
+ avatar_url: null,
+ description: null,
+ is_personal: false,
+ member_count: 0,
+ created_at: "2026-03-12T10:00:00.000Z",
+};
+
+beforeEach(() => {
+ mockToast.mockReset();
+ reloadMock.mockReset();
+ auth.user = { id: "admin-self" };
+ // happy-dom can't navigate; a started impersonation reloads the page.
+ Object.defineProperty(window.location, "reload", {
+ configurable: true,
+ value: reloadMock,
+ });
+ mockUserRoutes(ALEX);
+});
+
+afterEach(() => ImpersonationState.clear());
+
+describe("/admin/users", () => {
+ it("shows a user found by exact email with their plan, organisations and filtered money links", async () => {
+ renderPage(`?user=${encodeURIComponent(ALEX.email)}`);
+
+ expect(
+ await screen.findByRole("heading", { name: "Alex Rivera" }),
+ ).toBeDefined();
+ const details = screen.getByRole("region", { name: "Details" });
+ expect(await within(details).findByText("Pro")).toBeDefined();
+ expect(within(details).getByText(ALEX.id)).toBeDefined();
+ expect(await screen.findByText("Acme Inc")).toBeDefined();
+
+ expect(
+ screen
+ .getByRole("link", { name: /spending history/i })
+ .getAttribute("href"),
+ ).toBe(`/admin/spending?search=${ALEX.id}`);
+ expect(
+ screen.getByRole("link", { name: /platform cost/i }).getAttribute("href"),
+ ).toBe(`/admin/platform-costs?user_id=${ALEX.id}`);
+ });
+
+ it("offers the spending search when nothing matches exactly", async () => {
+ renderPage("?user=alex");
+
+ expect(
+ await screen.findByRole("heading", { name: /no user matches alex/i }),
+ ).toBeDefined();
+ expect(
+ screen
+ .getByRole("link", { name: /search spending history/i })
+ .getAttribute("href"),
+ ).toBe("/admin/spending?search=alex");
+ });
+
+ it("bans only once a reason is given, then shows the user as banned", async () => {
+ const bans = mockBan();
+ renderPage(`?user=${ALEX.id}`);
+
+ fireEvent.click(await screen.findByRole("button", { name: /ban user/i }));
+ const dialog = await screen.findByRole("dialog");
+ const confirm = within(dialog).getByRole("button", { name: "Ban user" });
+ expect((confirm as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.change(within(dialog).getByLabelText(/reason/i), {
+ target: { value: "Spam signups" },
+ });
+ expect((confirm as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(confirm);
+
+ await waitFor(() =>
+ expect(bans).toEqual([{ userId: ALEX.id, banReason: "Spam signups" }]),
+ );
+ expect(await screen.findByRole("alert")).toBeDefined();
+ expect(screen.getByText(/“Spam signups”/)).toBeDefined();
+ expect(screen.getByRole("button", { name: "Unban" })).toBeDefined();
+ });
+
+ it("treats a temporary ban that has run out as no ban", async () => {
+ mockUserRoutes({
+ ...ALEX,
+ banned: true,
+ banReason: "Spam",
+ banExpires: "2026-01-01T00:00:00.000Z",
+ } as unknown as typeof ALEX);
+ renderPage(`?user=${ALEX.id}`);
+
+ expect(
+ await screen.findByRole("button", { name: /ban user/i }),
+ ).toBeDefined();
+ expect(screen.queryByRole("button", { name: "Unban" })).toBeNull();
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(screen.getByText("Active")).toBeDefined();
+ });
+
+ it("warns before banning another admin", async () => {
+ mockUserRoutes({ ...ALEX, role: "admin" });
+ renderPage(`?user=${ALEX.id}`);
+
+ fireEvent.click(await screen.findByRole("button", { name: /ban user/i }));
+
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByText("This account is an admin.")).toBeDefined();
+ });
+
+ it("offers no ban or impersonation on the signed-in admin's own account", async () => {
+ auth.user = { id: ALEX.id };
+ renderPage(`?user=${ALEX.id}`);
+
+ expect(
+ await screen.findByRole("heading", { name: "Alex Rivera" }),
+ ).toBeDefined();
+ expect(screen.getByText("You")).toBeDefined();
+ expect(screen.queryByRole("button", { name: /ban user/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /impersonate/i })).toBeNull();
+ });
+
+ it("asks before changing the plan, and sends nothing on cancel", async () => {
+ const tiers = mockSetTier();
+ renderPage(`?user=${ALEX.id}`);
+
+ await chooseOption(/plan/i, /^Max/);
+ let dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByText("Change plan to Max?")).toBeDefined();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(tiers).toEqual([]);
+
+ await chooseOption(/plan/i, /^Max/);
+ dialog = await screen.findByRole("dialog");
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Change plan" }),
+ );
+ await waitFor(() =>
+ expect(tiers).toEqual([{ user_id: ALEX.id, tier: "MAX" }]),
+ );
+ });
+
+ it("says when the plan couldn't load rather than showing it blank", async () => {
+ server.use(
+ http.get("*/api/copilot/admin/rate_limit", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+ renderPage(`?user=${ALEX.id}`);
+
+ const details = await screen.findByRole("region", { name: "Details" });
+ expect(await within(details).findByText("Couldn't load")).toBeDefined();
+ });
+
+ it("shows a billing-set plan again after a plan change is cancelled", async () => {
+ server.use(
+ http.get("*/api/copilot/admin/rate_limit", () =>
+ HttpResponse.json({
+ user_id: ALEX.id,
+ user_email: ALEX.email,
+ daily_cost_limit_microdollars: 5_000_000,
+ weekly_cost_limit_microdollars: 25_000_000,
+ daily_cost_used_microdollars: 0,
+ weekly_cost_used_microdollars: 0,
+ tier: "TRIAL",
+ tier_multipliers: { MAX: 10 },
+ }),
+ ),
+ );
+ renderPage(`?user=${ALEX.id}`);
+
+ await chooseOption(/plan/i, /^Max/);
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+
+ const select = screen.getByRole("combobox", { name: /plan/i });
+ expect(select.textContent).toContain("Trial (set by billing)");
+ expect(select.textContent).not.toContain("Max");
+ });
+
+ it("asks before impersonating, and stays put when the audit notice fails", async () => {
+ const notices = mockImpersonationNotice(502);
+ renderPage(`?user=${ALEX.id}`);
+
+ fireEvent.click(await screen.findByRole("button", { name: "Impersonate" }));
+ const dialog = await screen.findByRole("dialog");
+ expect(notices).toEqual([]);
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Impersonate" }),
+ );
+
+ await waitFor(() =>
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Couldn't start impersonation",
+ variant: "destructive",
+ }),
+ ),
+ );
+ expect(notices).toEqual([{ target_user_id: ALEX.id }]);
+ expect(ImpersonationState.get()).toBeNull();
+ expect(reloadMock).not.toHaveBeenCalled();
+ expect(screen.getByRole("dialog")).toBeDefined();
+ });
+
+ it("starts impersonating once the audit notice is delivered", async () => {
+ mockImpersonationNotice(200);
+ renderPage(`?user=${ALEX.id}`);
+
+ fireEvent.click(await screen.findByRole("button", { name: "Impersonate" }));
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Impersonate" }),
+ );
+
+ await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1));
+ expect(ImpersonationState.get()).toBe(ALEX.id);
+ });
+
+ it("offers a retry when the organisations fail to load", async () => {
+ let calls = 0;
+ server.use(
+ http.get(`*/api/admin/users/${ALEX.id}/organizations`, () => {
+ calls += 1;
+ return calls === 1
+ ? HttpResponse.json({ detail: "boom" }, { status: 500 })
+ : HttpResponse.json([ORGANISATION]);
+ }),
+ );
+ renderPage(`?user=${ALEX.id}`);
+
+ const section = await screen.findByRole("region", {
+ name: "Organisations",
+ });
+ fireEvent.click(
+ await within(section).findByRole("button", { name: "Retry" }),
+ );
+
+ expect(await within(section).findByText("Acme Inc")).toBeDefined();
+ });
+
+ it("offers no ban or impersonation until the signed-in admin is known", async () => {
+ auth.user = null;
+ renderPage(`?user=${ALEX.id}`);
+
+ expect(
+ await screen.findByRole("heading", { name: "Alex Rivera" }),
+ ).toBeDefined();
+ expect(screen.queryByRole("button", { name: /ban user/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /impersonate/i })).toBeNull();
+ });
+});
+
+function renderPage(search: string) {
+ return render(
+ <NuqsTestingAdapter hasMemory searchParams={search}>
+ <AdminUsersView />
+ </NuqsTestingAdapter>,
+ );
+}
+
+async function chooseOption(combobox: RegExp, option: RegExp) {
+ const select = await screen.findByRole("combobox", { name: combobox });
+ fireEvent.click(select);
+ fireEvent.click(await screen.findByRole("option", { name: option }));
+}
+
+function mockUserRoutes(user: typeof ALEX) {
+ server.use(
+ http.get("*/api/auth/admin/get-user", ({ request }) =>
+ new URL(request.url).searchParams.get("id") === user.id
+ ? HttpResponse.json(user)
+ : HttpResponse.json({ code: "USER_NOT_FOUND" }, { status: 404 }),
+ ),
+ http.get("*/api/auth/admin/list-users", ({ request }) => {
+ const value = new URL(request.url).searchParams.get("filterValue");
+ const users = value === user.email ? [user] : [];
+ return HttpResponse.json({ users, total: users.length });
+ }),
+ http.get("*/api/copilot/admin/rate_limit", () =>
+ HttpResponse.json({
+ user_id: user.id,
+ user_email: user.email,
+ daily_cost_limit_microdollars: 5_000_000,
+ weekly_cost_limit_microdollars: 25_000_000,
+ daily_cost_used_microdollars: 1_200_000,
+ weekly_cost_used_microdollars: 4_800_000,
+ tier: "PRO",
+ tier_multipliers: { BASIC: 1, PRO: 3, MAX: 10 },
+ }),
+ ),
+ http.get(`*/api/admin/users/${user.id}/organizations`, () =>
+ HttpResponse.json([ORGANISATION]),
+ ),
+ );
+}
+
+function mockBan() {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/auth/admin/ban-user", async ({ request }) => {
+ const body = (await request.json()) as { banReason: string };
+ bodies.push(body);
+ return HttpResponse.json({
+ user: { ...ALEX, banned: true, banReason: body.banReason },
+ });
+ }),
+ );
+ return bodies;
+}
+
+function mockSetTier() {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/copilot/admin/rate_limit/tier", async ({ request }) => {
+ bodies.push(await request.json());
+ return HttpResponse.json({ user_id: ALEX.id, tier: "MAX" });
+ }),
+ );
+ return bodies;
+}
+
+function mockImpersonationNotice(status: 200 | 502) {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/admin/impersonation/notify", async ({ request }) => {
+ bodies.push(await request.json());
+ return status === 200
+ ? HttpResponse.json({ alerted: true })
+ : HttpResponse.json(
+ { detail: "audit channel unavailable" },
+ { status },
+ );
+ }),
+ );
+ return bodies;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/money-links.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/money-links.test.tsx
new file mode 100644
index 0000000000..f1bbf093fa
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/money-links.test.tsx
@@ -0,0 +1,71 @@
+import { render } from "@/tests/integrations/test-utils";
+import { describe, expect, it, vi } from "vitest";
+import { PlatformCostContent } from "../../platform-costs/components/PlatformCostContent";
+import SpendingDashboardPage from "../../spending/page";
+import { getSpendingSearchHref, getUserPlatformCostsHref } from "../helpers";
+
+// The user page links out rather than summarising; these pin that each target
+// page filters by the parameters the link carries.
+
+const USER_ID = "5d0a1c2e-0000-4000-8000-000000000001";
+
+const mockUseGetDashboard = vi.hoisted(() =>
+ vi.fn(() => ({ data: undefined, isLoading: true, error: null })),
+);
+const mockGrantHistory = vi.hoisted(() => vi.fn(() => null));
+
+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({
+ useGetV2GetPlatformCostDashboard: mockUseGetDashboard,
+ useGetV2GetPlatformCostLogs: () => ({
+ data: undefined,
+ isLoading: true,
+ error: null,
+ }),
+}));
+
+vi.mock("@/lib/withRoleAccess", () => ({
+ withRoleAccess: async () => async (Component: unknown) => Component,
+}));
+
+vi.mock("../../spending/components/AdminUserGrantHistory", () => ({
+ AdminUserGrantHistory: mockGrantHistory,
+}));
+
+vi.mock("../../spending/components/ExportCreditTransactionsButton", () => ({
+ ExportCreditTransactionsButton: () => null,
+}));
+
+vi.mock("../../spending/components/ExportCopilotUsageButton", () => ({
+ ExportCopilotUsageButton: () => null,
+}));
+
+describe("the user page's money links", () => {
+ it("open platform costs filtered to the user", () => {
+ render(
+ <PlatformCostContent
+ searchParams={paramsOf(getUserPlatformCostsHref(USER_ID))}
+ />,
+ );
+
+ expect(mockUseGetDashboard).toHaveBeenCalledWith(
+ expect.objectContaining({ user_id: USER_ID }),
+ expect.anything(),
+ );
+ });
+
+ it("open spending history filtered to the user", async () => {
+ const page = await SpendingDashboardPage({
+ searchParams: Promise.resolve(paramsOf(getSpendingSearchHref(USER_ID))),
+ });
+ render(page);
+
+ expect(mockGrantHistory).toHaveBeenCalledWith(
+ expect.objectContaining({ initialSearch: USER_ID }),
+ expect.anything(),
+ );
+ });
+});
+
+function paramsOf(href: string) {
+ return Object.fromEntries(new URL(href, "http://localhost").searchParams);
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAdminUserLookup.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAdminUserLookup.test.tsx
new file mode 100644
index 0000000000..fe54dbfa61
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAdminUserLookup.test.tsx
@@ -0,0 +1,152 @@
+import { server } from "@/mocks/mock-server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { NuqsTestingAdapter } from "nuqs/adapters/testing";
+import { ReactNode } from "react";
+import { describe, expect, it } from "vitest";
+import { useAdminUserLookup } from "../useAdminUserLookup";
+
+const FIRST_LAST = authUser({
+ id: "11111111-1111-4111-8111-111111111111",
+ email: "[email protected]",
+});
+const FIRSTXLAST = authUser({
+ id: "22222222-2222-4222-8222-222222222222",
+ email: "[email protected]",
+});
+
+describe("useAdminUserLookup", () => {
+ it("looks an email up by exact match, so `_` matches only itself", async () => {
+ const requests = mockListUsers([FIRSTXLAST, FIRST_LAST]);
+ const { result } = renderLookup();
+
+ act(() => result.current.search(" [email protected] "));
+
+ await waitFor(() => expect(result.current.user).not.toBeNull());
+ expect(result.current.user?.id).toBe(FIRST_LAST.id);
+ // React Query may refetch under load; every request must be the exact one.
+ expect(requests.length).toBeGreaterThan(0);
+ for (const params of requests) {
+ expect(params.get("filterField")).toBe("email");
+ expect(params.get("filterOperator")).toBe("eq");
+ expect(params.get("filterValue")).toBe("[email protected]");
+ expect(params.get("searchValue")).toBeNull();
+ }
+ });
+
+ it("reports an email with no exact match as not found", async () => {
+ mockListUsers([FIRSTXLAST]);
+ const { result } = renderLookup();
+
+ act(() => result.current.search("[email protected]"));
+
+ await waitFor(() => expect(result.current.isNotFound).toBe(true));
+ expect(result.current.user).toBeNull();
+ });
+
+ it("looks an ID up through get-user", async () => {
+ const requestedIds: (string | null)[] = [];
+ server.use(
+ http.get("*/api/auth/admin/get-user", ({ request }) => {
+ requestedIds.push(new URL(request.url).searchParams.get("id"));
+ return HttpResponse.json({ ...FIRST_LAST, banned: true });
+ }),
+ );
+ const { result } = renderLookup();
+
+ act(() => result.current.search(FIRST_LAST.id));
+
+ await waitFor(() => expect(result.current.user).not.toBeNull());
+ expect([...new Set(requestedIds)]).toEqual([FIRST_LAST.id]);
+ expect(result.current.user?.banned).toBe(true);
+ expect(result.current.user?.createdAt).toBeInstanceOf(Date);
+ });
+
+ it("reports an unknown ID as not found rather than as an error", async () => {
+ server.use(
+ http.get("*/api/auth/admin/get-user", () =>
+ HttpResponse.json(
+ { code: "USER_NOT_FOUND", message: "User not found" },
+ { status: 404 },
+ ),
+ ),
+ );
+ const { result } = renderLookup();
+
+ act(() => result.current.search("33333333-3333-4333-8333-333333333333"));
+
+ await waitFor(() => expect(result.current.isNotFound).toBe(true));
+ expect(result.current.error).toBeNull();
+ });
+
+ it("surfaces a refused lookup as an error", async () => {
+ server.use(
+ http.get("*/api/auth/admin/get-user", () =>
+ HttpResponse.json(
+ { code: "FORBIDDEN", message: "You are not allowed to get user" },
+ { status: 403 },
+ ),
+ ),
+ );
+ const { result } = renderLookup();
+
+ act(() => result.current.search(FIRST_LAST.id));
+
+ await waitFor(() => expect(result.current.error).not.toBeNull());
+ expect(result.current.error?.message).toBe(
+ "You are not allowed to get user",
+ );
+ expect(result.current.isNotFound).toBe(false);
+ });
+});
+
+function renderLookup() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <NuqsTestingAdapter hasMemory>{children}</NuqsTestingAdapter>
+ </QueryClientProvider>
+ );
+ }
+ return renderHook(() => useAdminUserLookup(), { wrapper: Wrapper });
+}
+
+// Answers like the real endpoint for the exact filter it is sent, and with
+// every row for anything looser, as a LIKE with `_` in it would.
+function mockListUsers(users: ReturnType<typeof authUser>[]) {
+ const requests: URLSearchParams[] = [];
+ server.use(
+ http.get("*/api/auth/admin/list-users", ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ requests.push(params);
+ const exact =
+ params.get("filterField") === "email" &&
+ params.get("filterOperator") === "eq";
+ const matches = exact
+ ? users.filter((user) => user.email === params.get("filterValue"))
+ : users;
+ return HttpResponse.json({ users: matches, total: matches.length });
+ }),
+ );
+ return requests;
+}
+
+function authUser({ id, email }: { id: string; email: string }) {
+ return {
+ id,
+ email,
+ name: "Test User",
+ image: null,
+ role: "user",
+ emailVerified: true,
+ createdAt: "2026-01-02T03:04:05.000Z",
+ updatedAt: "2026-01-02T03:04:05.000Z",
+ banned: false,
+ banReason: null,
+ banExpires: null,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAutoPilotUsage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAutoPilotUsage.test.tsx
new file mode 100644
index 0000000000..4782e2fa37
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useAutoPilotUsage.test.tsx
@@ -0,0 +1,130 @@
+import { getGetV2GetUserRateLimitQueryKey } from "@/app/api/__generated__/endpoints/admin/admin";
+import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";
+import { server } from "@/mocks/mock-server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { useAutoPilotUsage } from "../components/AutoPilotUsageSection/useAutoPilotUsage";
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: vi.fn() }),
+}));
+
+const USER_A = "11111111-1111-4111-8111-111111111111";
+const USER_B = "22222222-2222-4222-8222-222222222222";
+
+// The page keeps one usage section mounted across lookups, so a result that
+// lands after the admin has moved on must still go to the user it was for.
+describe("useAutoPilotUsage after switching users mid-request", () => {
+ it("stores a usage reset under the user it was made for", async () => {
+ const release = holdResponses(
+ "*/api/copilot/admin/rate_limit/reset",
+ (userID) => usage(userID, 0),
+ );
+ const { result, rerender, queryClient } = renderUsageFor(USER_B);
+ await waitFor(() => expect(result.current.rateLimit?.user_id).toBe(USER_B));
+ rerender({ userId: USER_A });
+ await waitFor(() => expect(result.current.rateLimit?.user_id).toBe(USER_A));
+
+ act(() => result.current.resetUsage("daily", () => {}));
+ rerender({ userId: USER_B });
+ release();
+
+ await waitFor(() =>
+ expect(
+ cachedUsage(queryClient, USER_A)?.daily_cost_used_microdollars,
+ ).toBe(0),
+ );
+ expect(cachedUsage(queryClient, USER_B)?.user_id).toBe(USER_B);
+ expect(result.current.rateLimit?.user_id).toBe(USER_B);
+ });
+
+ it("refreshes the plan of the user it was changed for", async () => {
+ const release = holdResponses(
+ "*/api/copilot/admin/rate_limit/tier",
+ (userID) => ({
+ user_id: userID,
+ tier: "MAX",
+ }),
+ );
+ const { result, rerender, queryClient } = renderUsageFor(USER_B);
+ await waitFor(() => expect(result.current.rateLimit?.user_id).toBe(USER_B));
+ rerender({ userId: USER_A });
+ await waitFor(() => expect(result.current.rateLimit?.user_id).toBe(USER_A));
+
+ act(() => result.current.changePlan("MAX", () => {}));
+ rerender({ userId: USER_B });
+ release();
+
+ await waitFor(() =>
+ expect(queryClient.getQueryState(usageKey(USER_A))?.isInvalidated).toBe(
+ true,
+ ),
+ );
+ });
+});
+
+function renderUsageFor(userId: string) {
+ server.use(
+ http.get("*/api/copilot/admin/rate_limit", ({ request }) =>
+ HttpResponse.json(
+ usage(
+ new URL(request.url).searchParams.get("user_id") ?? "",
+ 1_200_000,
+ ),
+ ),
+ ),
+ );
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+ const rendered = renderHook(
+ (props: { userId: string }) => useAutoPilotUsage(props.userId),
+ { wrapper: Wrapper, initialProps: { userId } },
+ );
+ return { ...rendered, queryClient };
+}
+
+// Answers each POST to `path` only once `release()` is called.
+function holdResponses(path: string, answer: (userID: string) => object) {
+ let release = () => {};
+ const held = new Promise<void>((resolve) => (release = resolve));
+ server.use(
+ http.post(path, async ({ request }) => {
+ const body = (await request.json()) as { user_id: string };
+ await held;
+ return HttpResponse.json(answer(body.user_id));
+ }),
+ );
+ return () => release();
+}
+
+function usageKey(userID: string) {
+ return getGetV2GetUserRateLimitQueryKey({ user_id: userID });
+}
+
+function cachedUsage(queryClient: QueryClient, userID: string) {
+ return queryClient.getQueryData<{ data: UserRateLimitResponse }>(
+ usageKey(userID),
+ )?.data;
+}
+
+function usage(userID: string, dailyUsed: number): UserRateLimitResponse {
+ return {
+ user_id: userID,
+ user_email: `${userID}@example.com`,
+ daily_cost_limit_microdollars: 5_000_000,
+ weekly_cost_limit_microdollars: 25_000_000,
+ daily_cost_used_microdollars: dailyUsed,
+ weekly_cost_used_microdollars: 4_800_000,
+ tier: "PRO",
+ tier_multipliers: { PRO: 3 },
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useUserBan.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useUserBan.test.tsx
new file mode 100644
index 0000000000..9bfc9030fc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/__tests__/useUserBan.test.tsx
@@ -0,0 +1,176 @@
+import { server } from "@/mocks/mock-server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { type AdminUser, parseLookupQuery, toAdminUser } from "../helpers";
+import { getAdminUserLookupQueryKey } from "../useAdminUserLookup";
+import { useUserBan } from "../useUserBan";
+
+const mockToast = vi.hoisted(() => vi.fn());
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+const RECORD = {
+ id: "11111111-1111-4111-8111-111111111111",
+ email: "[email protected]",
+ name: "Test User",
+ image: null,
+ role: "user",
+ emailVerified: true,
+ createdAt: "2026-01-02T03:04:05.000Z",
+ banned: false,
+ banReason: null,
+ banExpires: null,
+};
+const USER = toAdminUser(RECORD);
+
+beforeEach(() => mockToast.mockReset());
+
+describe("useUserBan", () => {
+ it("bans through Better Auth with the reason and expiry, and shows the banned user", async () => {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/auth/admin/ban-user", async ({ request }) => {
+ bodies.push(await request.json());
+ return HttpResponse.json({
+ user: {
+ ...RECORD,
+ banned: true,
+ banReason: "spam",
+ banExpires: new Date(Date.now() + 7 * 24 * 3600 * 1000),
+ },
+ });
+ }),
+ );
+ const { result, queryClient } = renderBan(USER);
+
+ act(() => result.current.banUser({ reason: " spam ", duration: "7d" }));
+
+ await waitFor(() => expect(bodies).toHaveLength(1));
+ expect(bodies[0]).toEqual({
+ userId: USER.id,
+ banReason: "spam",
+ banExpiresIn: 7 * 24 * 60 * 60,
+ });
+ await waitFor(() =>
+ expect(cachedUser(queryClient, USER.email)?.banned).toBe(true),
+ );
+ expect(cachedUser(queryClient, USER.id)?.banReason).toBe("spam");
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "success" }),
+ );
+ });
+
+ it("sends no expiry for a permanent ban", async () => {
+ const bodies: Record<string, unknown>[] = [];
+ server.use(
+ http.post("*/api/auth/admin/ban-user", async ({ request }) => {
+ bodies.push((await request.json()) as Record<string, unknown>);
+ return HttpResponse.json({ user: { ...RECORD, banned: true } });
+ }),
+ );
+ const { result } = renderBan(USER);
+
+ act(() =>
+ result.current.banUser({ reason: "spam", duration: "permanent" }),
+ );
+
+ await waitFor(() => expect(bodies).toHaveLength(1));
+ expect(bodies[0]).toEqual({ userId: USER.id, banReason: "spam" });
+ });
+
+ it("refuses a ban without a reason and sends nothing", async () => {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/auth/admin/ban-user", async ({ request }) => {
+ bodies.push(await request.json());
+ return HttpResponse.json({ user: { ...RECORD, banned: true } });
+ }),
+ );
+ const { result } = renderBan(USER);
+
+ act(() => result.current.banUser({ reason: " ", duration: "1h" }));
+
+ await waitFor(() =>
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ ),
+ );
+ expect(bodies).toEqual([]);
+ });
+
+ it("shows why Better Auth refused a ban and leaves the user unbanned", async () => {
+ server.use(
+ http.post("*/api/auth/admin/ban-user", () =>
+ HttpResponse.json(
+ {
+ code: "YOU_CANNOT_BAN_YOURSELF",
+ message: "You cannot ban yourself",
+ },
+ { status: 400 },
+ ),
+ ),
+ );
+ const { result, queryClient } = renderBan(USER);
+
+ act(() => result.current.banUser({ reason: "spam", duration: "1h" }));
+
+ await waitFor(() =>
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: "destructive",
+ description: "You cannot ban yourself",
+ }),
+ ),
+ );
+ expect(cachedUser(queryClient, USER.id)?.banned).toBe(false);
+ });
+
+ it("unbans through Better Auth and shows the unbanned user", async () => {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/auth/admin/unban-user", async ({ request }) => {
+ bodies.push(await request.json());
+ return HttpResponse.json({ user: RECORD });
+ }),
+ );
+ const banned: AdminUser = { ...USER, banned: true, banReason: "spam" };
+ const { result, queryClient } = renderBan(banned);
+
+ act(() => result.current.unbanUser());
+
+ await waitFor(() => expect(bodies).toEqual([{ userId: USER.id }]));
+ await waitFor(() =>
+ expect(cachedUser(queryClient, USER.id)?.banned).toBe(false),
+ );
+ });
+});
+
+function renderBan(user: AdminUser) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ for (const lookup of [user.id, user.email]) {
+ queryClient.setQueryData(
+ getAdminUserLookupQueryKey(parseLookupQuery(lookup)),
+ user,
+ );
+ }
+ function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+ const rendered = renderHook(() => useUserBan(user), { wrapper: Wrapper });
+ return { ...rendered, queryClient };
+}
+
+function cachedUser(queryClient: QueryClient, lookup: string) {
+ return queryClient.getQueryData<AdminUser>(
+ getAdminUserLookupQueryKey(parseLookupQuery(lookup)),
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AdminUsersView/AdminUsersView.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AdminUsersView/AdminUsersView.tsx
new file mode 100644
index 0000000000..099005b553
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AdminUsersView/AdminUsersView.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { useAdminUserLookup } from "../../useAdminUserLookup";
+import { EmptyState, LookupSkeleton, NotFoundState } from "../LookupStates";
+import { UserLookupBar } from "../UserLookupBar";
+import { UserView } from "../UserView/UserView";
+
+export function AdminUsersView() {
+ const {
+ rawQuery,
+ query,
+ user,
+ isLoading,
+ isNotFound,
+ error,
+ search,
+ refetch,
+ } = useAdminUserLookup();
+
+ return (
+ <div className="flex w-full max-w-[1120px] flex-col gap-6">
+ <div className="flex flex-col">
+ <Text variant="h4" as="h1" className="leading-[28px] text-textBlack">
+ Users
+ </Text>
+ <Text variant="body" className="mt-4 max-w-[600px] text-zinc-700">
+ Look up an account by ID or email to inspect it, limit it, or act as
+ the user.
+ </Text>
+ </div>
+
+ <UserLookupBar
+ key={rawQuery}
+ initialValue={rawQuery}
+ isLoading={isLoading}
+ showHint={query === null}
+ onSearch={search}
+ />
+
+ {query === null ? (
+ <EmptyState />
+ ) : isLoading ? (
+ <LookupSkeleton />
+ ) : error ? (
+ <ErrorCard
+ context="user lookup"
+ responseError={{ message: error.message }}
+ onRetry={() => {
+ void refetch();
+ }}
+ />
+ ) : isNotFound || !user ? (
+ <NotFoundState query={rawQuery.trim()} />
+ ) : (
+ <UserView user={user} />
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/AutoPilotUsageSection.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/AutoPilotUsageSection.tsx
new file mode 100644
index 0000000000..e3b5bc6bc5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/AutoPilotUsageSection.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import { useState } from "react";
+import { AdminSection } from "../../../components/AdminSection";
+import { UsageBar } from "../../../components/UsageBar";
+import { getPlanName } from "../../helpers";
+import { ChangePlanDialog } from "./components/ChangePlanDialog";
+import { PlanSelect } from "./components/PlanSelect";
+import { ResetControls } from "./components/ResetControls";
+import { useAutoPilotUsage } from "./useAutoPilotUsage";
+
+interface Props {
+ userId: string;
+}
+
+export function AutoPilotUsageSection({ userId }: Props) {
+ const usage = useAutoPilotUsage(userId);
+ const [pendingTier, setPendingTier] = useState<string | null>(null);
+ const data = usage.rateLimit;
+
+ return (
+ <AdminSection
+ title="AutoPilot usage"
+ description="Daily and weekly spend against this user's plan limits."
+ >
+ {usage.isLoading ? (
+ <div className="flex flex-col gap-4" aria-busy="true">
+ <Skeleton className="h-9 w-[260px] rounded-lg" />
+ <Skeleton className="h-12 w-full rounded-lg" />
+ <Skeleton className="h-12 w-full rounded-lg" />
+ </div>
+ ) : !data ? (
+ <div className="flex items-center justify-between gap-4">
+ <Text variant="small" className="text-zinc-500">
+ Couldn&apos;t load this user&apos;s usage.
+ </Text>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => void usage.refetch()}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-5">
+ <PlanSelect
+ tier={data.tier}
+ multipliers={data.tier_multipliers}
+ disabled={usage.isChangingPlan}
+ onPick={setPendingTier}
+ />
+ <UsageRow
+ label="Daily"
+ used={data.daily_cost_used_microdollars}
+ limit={data.daily_cost_limit_microdollars}
+ />
+ <UsageRow
+ label="Weekly"
+ used={data.weekly_cost_used_microdollars}
+ limit={data.weekly_cost_limit_microdollars}
+ />
+ <ResetControls
+ dailyUsed={data.daily_cost_used_microdollars}
+ weeklyUsed={data.weekly_cost_used_microdollars}
+ isResetting={usage.isResetting}
+ onReset={usage.resetUsage}
+ />
+ </div>
+ )}
+
+ <ChangePlanDialog
+ planName={pendingTier ? getPlanName(pendingTier) : ""}
+ isOpen={pendingTier !== null}
+ isChanging={usage.isChangingPlan}
+ onCancel={() => setPendingTier(null)}
+ onConfirm={() => {
+ if (pendingTier) {
+ usage.changePlan(pendingTier, () => setPendingTier(null));
+ }
+ }}
+ />
+ </AdminSection>
+ );
+}
+
+function UsageRow({
+ label,
+ used,
+ limit,
+}: {
+ label: string;
+ used: number;
+ limit: number;
+}) {
+ return (
+ <div className="flex flex-col gap-1">
+ <Text variant="small-medium" as="span">
+ {label}
+ </Text>
+ <UsageBar used={used} limit={limit} />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ChangePlanDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ChangePlanDialog.tsx
new file mode 100644
index 0000000000..c914a502c5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ChangePlanDialog.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+
+interface Props {
+ planName: string;
+ isOpen: boolean;
+ isChanging: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}
+
+export function ChangePlanDialog({
+ planName,
+ isOpen,
+ isChanging,
+ onCancel,
+ onConfirm,
+}: Props) {
+ return (
+ <Dialog
+ title={`Change plan to ${planName}?`}
+ styling={{ maxWidth: "480px" }}
+ controlled={{
+ isOpen,
+ set: (open) => {
+ if (!open) onCancel();
+ },
+ }}
+ >
+ <Dialog.Content>
+ <Text variant="body" className="text-zinc-600">
+ Their AutoPilot limits change right away. If they pay through Stripe,
+ the next billing sync sets the plan back to what they pay for.
+ </Text>
+ <Dialog.Footer>
+ <Button variant="secondary" size="small" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ loading={isChanging}
+ onClick={onConfirm}
+ >
+ Change plan
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/PlanSelect.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/PlanSelect.tsx
new file mode 100644
index 0000000000..5bda8cf124
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/PlanSelect.tsx
@@ -0,0 +1,37 @@
+import { Select } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
+import { getPlanName } from "../../../helpers";
+import { getPlanOptions, isAssignableTier } from "../helpers";
+
+interface Props {
+ tier: string;
+ multipliers?: Record<string, number>;
+ disabled: boolean;
+ onPick: (tier: string) => void;
+}
+
+export function PlanSelect({ tier, multipliers, disabled, onPick }: Props) {
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Text variant="small-medium" as="span" aria-hidden>
+ Plan
+ </Text>
+ <Select
+ id="user-plan"
+ label="Plan"
+ hideLabel
+ size="small"
+ // "" keeps Radix controlled and shows the placeholder; undefined would
+ // let it keep a pick the admin then cancelled.
+ value={isAssignableTier(tier) ? tier : ""}
+ placeholder={`${getPlanName(tier)} (set by billing)`}
+ options={getPlanOptions(multipliers)}
+ onValueChange={(picked) => {
+ if (picked !== tier) onPick(picked);
+ }}
+ disabled={disabled}
+ wrapperClassName="mb-0 w-full sm:w-[260px]"
+ />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetControls.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetControls.tsx
new file mode 100644
index 0000000000..d69e0ff71c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetControls.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { Select } from "@/components/atoms/Select/Select";
+import { useState } from "react";
+import { RESET_SCOPE_OPTIONS, type ResetScope } from "../helpers";
+import { ResetUsageDialog } from "./ResetUsageDialog";
+
+interface Props {
+ dailyUsed: number;
+ weeklyUsed: number;
+ isResetting: boolean;
+ onReset: (scope: ResetScope, onSuccess: () => void) => void;
+}
+
+export function ResetControls({
+ dailyUsed,
+ weeklyUsed,
+ isResetting,
+ onReset,
+}: Props) {
+ const [scope, setScope] = useState<ResetScope>("daily");
+
+ return (
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <Select
+ id="reset-scope"
+ label="What to reset"
+ hideLabel
+ size="small"
+ value={scope}
+ onValueChange={(value) => setScope(value as ResetScope)}
+ options={RESET_SCOPE_OPTIONS}
+ wrapperClassName="mb-0 w-[220px]"
+ />
+ <ResetUsageDialog
+ scope={scope}
+ nothingToReset={
+ dailyUsed === 0 && (scope === "daily" || weeklyUsed === 0)
+ }
+ isResetting={isResetting}
+ onConfirm={onReset}
+ />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetUsageDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetUsageDialog.tsx
new file mode 100644
index 0000000000..23495ac2a1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/components/ResetUsageDialog.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { useState } from "react";
+import type { ResetScope } from "../helpers";
+
+interface Props {
+ scope: ResetScope;
+ nothingToReset: boolean;
+ isResetting: boolean;
+ onConfirm: (scope: ResetScope, onSuccess: () => void) => void;
+}
+
+export function ResetUsageDialog({
+ scope,
+ nothingToReset,
+ isResetting,
+ onConfirm,
+}: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+ const both = scope === "both";
+
+ return (
+ <Dialog
+ title={both ? "Reset daily and weekly usage?" : "Reset daily usage?"}
+ styling={{ maxWidth: "480px" }}
+ controlled={{ isOpen, set: setIsOpen }}
+ >
+ <Dialog.Trigger>
+ <Button variant="secondary" size="small" disabled={nothingToReset}>
+ Reset…
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <Text variant="body" className="text-zinc-600">
+ {both
+ ? "Sets this user's AutoPilot spend for today and this week back to $0.00. Their limits don't change."
+ : "Sets this user's AutoPilot spend for today back to $0.00. Their limits don't change."}
+ </Text>
+ <Dialog.Footer>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ loading={isResetting}
+ onClick={() => onConfirm(scope, () => setIsOpen(false))}
+ >
+ Reset
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/helpers.ts
new file mode 100644
index 0000000000..d0a0c54f3a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/helpers.ts
@@ -0,0 +1,43 @@
+import { getPlanName } from "../../helpers";
+
+// TRIAL is set by billing, never assigned by hand.
+const ASSIGNABLE_TIERS = [
+ "NO_TIER",
+ "BASIC",
+ "PRO",
+ "MAX",
+ "BUSINESS",
+ "ENTERPRISE",
+] as const;
+
+export type ResetScope = "daily" | "both";
+
+export const RESET_SCOPE_OPTIONS = [
+ { value: "daily", label: "Daily usage" },
+ { value: "both", label: "Daily and weekly usage" },
+];
+
+export function isAssignableTier(tier: string) {
+ return (ASSIGNABLE_TIERS as readonly string[]).includes(tier);
+}
+
+export function getPlanOptions(multipliers?: Record<string, number>) {
+ return ASSIGNABLE_TIERS.map((tier) => ({
+ value: tier,
+ label: getPlanOptionLabel(tier, multipliers),
+ }));
+}
+
+// Multipliers come live from the admin endpoint; a tier missing from the map
+// gets a generic label rather than a made-up number.
+function getPlanOptionLabel(
+ tier: string,
+ multipliers?: Record<string, number>,
+) {
+ if (tier === "NO_TIER") return "No plan — no AutoPilot access";
+ const multiplier = multipliers?.[tier];
+ if (multiplier === undefined || multiplier <= 0) {
+ return `${getPlanName(tier)} — tier limits`;
+ }
+ return `${getPlanName(tier)} — ${Math.round(multiplier * 100) / 100}× base limits`;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/useAutoPilotUsage.ts b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/useAutoPilotUsage.ts
new file mode 100644
index 0000000000..41dc4799ba
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/AutoPilotUsageSection/useAutoPilotUsage.ts
@@ -0,0 +1,107 @@
+"use client";
+
+import type { SubscriptionTier } from "@/app/api/__generated__/models/subscriptionTier";
+import {
+ getGetV2GetUserRateLimitQueryKey,
+ useGetV2GetUserRateLimit,
+ usePostV2ResetUserRateLimitUsage,
+ usePostV2SetUserRateLimitTier,
+} from "@/app/api/__generated__/endpoints/admin/admin";
+import { okData } from "@/app/api/helpers";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { getErrorMessage, getPlanName } from "../../helpers";
+import type { ResetScope } from "./helpers";
+
+export function useAutoPilotUsage(userId: string) {
+ const { toast } = useToast();
+ const queryClient = useQueryClient();
+
+ const rateLimit = useGetV2GetUserRateLimit(
+ { user_id: userId },
+ { query: { select: okData } },
+ );
+
+ const setTier = usePostV2SetUserRateLimitTier({
+ mutation: {
+ onSuccess: (response, { data }) => {
+ const planName = getPlanName(data.tier);
+ const warning = okData(response)?.warning;
+ toast(
+ warning
+ ? {
+ title: `Plan set to ${planName}, but Stripe will revert it`,
+ description: warning,
+ variant: "destructive",
+ }
+ : { title: `Plan set to ${planName}`, variant: "success" },
+ );
+ void queryClient.invalidateQueries({
+ queryKey: getUsageQueryKey(data.user_id),
+ });
+ },
+ onError: (error) => {
+ toast({
+ title: "Couldn't change the plan",
+ description: getErrorMessage(error),
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ const reset = usePostV2ResetUserRateLimitUsage({
+ mutation: {
+ onSuccess: (response, { data }) => {
+ queryClient.setQueryData(getUsageQueryKey(data.user_id), response);
+ toast({
+ title: data.reset_weekly
+ ? "Daily and weekly usage reset"
+ : "Daily usage reset",
+ variant: "success",
+ });
+ },
+ onError: (error) => {
+ toast({
+ title: "Couldn't reset usage",
+ description: getErrorMessage(error),
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ function changePlan(tier: string, onSuccess: () => void) {
+ setTier.mutate(
+ {
+ data: { user_id: userId, tier: tier as SubscriptionTier },
+ },
+ { onSuccess },
+ );
+ }
+
+ function resetUsage(scope: ResetScope, onSuccess: () => void) {
+ reset.mutate(
+ { data: { user_id: userId, reset_weekly: scope === "both" } },
+ { onSuccess },
+ );
+ }
+
+ return {
+ rateLimit: rateLimit.data,
+ isLoading: rateLimit.isLoading,
+ error: rateLimit.error,
+ refetch: rateLimit.refetch,
+ changePlan,
+ isChangingPlan: setTier.isPending,
+ resetUsage,
+ isResetting: reset.isPending,
+ };
+}
+
+// Keyed by the user a request was sent for, never the one now on screen: the
+// section stays mounted across lookups, and React Query hands a pending
+// mutation the latest render's callbacks.
+function getUsageQueryKey(userID: string) {
+ return getGetV2GetUserRateLimitQueryKey({ user_id: userID });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/BannedAlert.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/BannedAlert.tsx
new file mode 100644
index 0000000000..0351d7dec7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/BannedAlert.tsx
@@ -0,0 +1,27 @@
+import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { UserBlock01Icon } from "@hugeicons/core-free-icons";
+import { type AdminUser, formatDateTime, formatTimeUntil } from "../helpers";
+
+interface Props {
+ user: AdminUser;
+}
+
+export function BannedAlert({ user }: Props) {
+ const until = user.banExpires
+ ? `until ${formatDateTime(user.banExpires)} (${formatTimeUntil(user.banExpires)})`
+ : "permanently";
+
+ return (
+ <Alert variant="error" icon={BannedIcon}>
+ <AlertDescription className="break-words">
+ <strong className="font-medium">Banned</strong> · {until}
+ {user.banReason ? <> · &ldquo;{user.banReason}&rdquo;</> : null}
+ </AlertDescription>
+ </Alert>
+ );
+}
+
+function BannedIcon({ className }: { className?: string }) {
+ return <Icon icon={UserBlock01Icon} className={className} aria-hidden />;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/DetailsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/DetailsSection.tsx
new file mode 100644
index 0000000000..947c7c1128
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/DetailsSection.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useGetV2GetUserRateLimit } from "@/app/api/__generated__/endpoints/admin/admin";
+import { okData } from "@/app/api/helpers";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { ReactNode } from "react";
+import { AdminSection } from "../../components/AdminSection";
+import { type AdminUser, formatDate, getPlanName } from "../helpers";
+
+interface Props {
+ user: AdminUser;
+}
+
+export function DetailsSection({ user }: Props) {
+ const { toast } = useToast();
+ const { data: rateLimit, isError: planFailed } = useGetV2GetUserRateLimit(
+ { user_id: user.id },
+ { query: { select: okData } },
+ );
+
+ async function copyUserID() {
+ try {
+ await navigator.clipboard.writeText(user.id);
+ toast({ title: "User ID copied" });
+ } catch {
+ toast({
+ title: "Couldn't copy the user ID",
+ description: "Select it and copy it by hand.",
+ variant: "destructive",
+ });
+ }
+ }
+
+ return (
+ <AdminSection title="Details">
+ <dl className="flex flex-col gap-3">
+ <Row label="User ID">
+ <span className="flex items-start gap-1">
+ <span
+ className="min-w-0 break-all font-mono text-[13px]"
+ translate="no"
+ >
+ {user.id}
+ </span>
+ <Button
+ variant="icon"
+ size="icon-xs"
+ aria-label="Copy user ID"
+ onClick={() => void copyUserID()}
+ >
+ <Icon icon={Copy01Icon} size={14} aria-hidden />
+ </Button>
+ </span>
+ </Row>
+ <Row label="Email">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <span className="break-all" translate="no">
+ {user.email}
+ </span>
+ {user.emailVerified ? (
+ <Badge variant="success" size="small">
+ Verified
+ </Badge>
+ ) : (
+ <Badge variant="warning" size="small">
+ Unverified
+ </Badge>
+ )}
+ </span>
+ </Row>
+ <Row label="Role">{user.role === "admin" ? "Admin" : "User"}</Row>
+ <Row label="Plan">
+ {rateLimit
+ ? getPlanName(rateLimit.tier)
+ : planFailed
+ ? "Couldn't load"
+ : "—"}
+ </Row>
+ <Row label="Joined">{formatDate(user.createdAt)}</Row>
+ <Row label="Status">
+ {user.banned ? (
+ <span className="text-red-700">
+ {user.banExpires
+ ? `Banned until ${formatDate(user.banExpires)}`
+ : "Banned permanently"}
+ </span>
+ ) : (
+ "Active"
+ )}
+ </Row>
+ </dl>
+ </AdminSection>
+ );
+}
+
+function Row({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="flex gap-3">
+ <Text variant="small" as="dt" className="w-[88px] shrink-0 text-zinc-500">
+ {label}
+ </Text>
+ <Text variant="body" as="dd" className="min-w-0 flex-1">
+ {children}
+ </Text>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/LookupStates.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/LookupStates.tsx
new file mode 100644
index 0000000000..3db932d322
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/LookupStates.tsx
@@ -0,0 +1,77 @@
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Link } from "@/components/atoms/Link/Link";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import {
+ UserQuestion01Icon,
+ UserSearch01Icon,
+} from "@hugeicons/core-free-icons";
+import { getSpendingSearchHref } from "../helpers";
+
+export function EmptyState() {
+ return (
+ <div className="flex flex-col items-center gap-2 py-16 text-center">
+ <Icon
+ icon={UserSearch01Icon}
+ size={32}
+ className="text-zinc-400"
+ aria-hidden
+ />
+ <Text variant="large-medium" as="h2">
+ Look up a user
+ </Text>
+ <Text variant="body" className="text-zinc-600">
+ Paste a user ID or the complete email address.
+ </Text>
+ </div>
+ );
+}
+
+export function NotFoundState({ query }: { query: string }) {
+ return (
+ <div className="flex flex-col items-center gap-2 py-16 text-center">
+ <Icon
+ icon={UserQuestion01Icon}
+ size={32}
+ className="text-zinc-400"
+ aria-hidden
+ />
+ <Text variant="large-medium" as="h2" className="break-all">
+ No user matches <span className="font-medium">{query}</span>
+ </Text>
+ <Text variant="body" className="text-zinc-600">
+ Lookup is exact: a full user ID or the complete email address.
+ </Text>
+ <Link
+ variant="secondary"
+ href={getSpendingSearchHref(query)}
+ className="mt-2"
+ >
+ Search spending history for &ldquo;{query}&rdquo; instead
+ </Link>
+ </div>
+ );
+}
+
+export function LookupSkeleton() {
+ return (
+ <div
+ className="flex flex-col gap-6"
+ aria-busy="true"
+ aria-live="polite"
+ aria-label="Loading user"
+ >
+ <Skeleton className="h-[88px] w-full rounded-[18px]" />
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="flex flex-col gap-6">
+ <Skeleton className="h-[220px] w-full rounded-[18px]" />
+ <Skeleton className="h-[160px] w-full rounded-[18px]" />
+ </div>
+ <div className="flex flex-col gap-6">
+ <Skeleton className="h-[260px] w-full rounded-[18px]" />
+ <Skeleton className="h-[112px] w-full rounded-[18px]" />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/OrganisationsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/OrganisationsSection.tsx
new file mode 100644
index 0000000000..f74187fe11
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/OrganisationsSection.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { useGetAdminGetUserOrganizations } from "@/app/api/__generated__/endpoints/admin/admin";
+import { okData } from "@/app/api/helpers";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Button } from "@/components/atoms/Button/Button";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import { AdminSection } from "../../components/AdminSection";
+import { formatMonth } from "../helpers";
+
+interface Props {
+ userId: string;
+}
+
+export function OrganisationsSection({ userId }: Props) {
+ const {
+ data: organisations,
+ isLoading,
+ refetch,
+ } = useGetAdminGetUserOrganizations(userId, { query: { select: okData } });
+
+ return (
+ <AdminSection
+ title="Organisations"
+ description="Every account has a personal organisation."
+ >
+ {isLoading ? (
+ <div className="flex flex-col gap-2" aria-busy="true">
+ <Skeleton className="h-10 w-full rounded-lg" />
+ <Skeleton className="h-10 w-full rounded-lg" />
+ </div>
+ ) : !organisations ? (
+ <div className="flex items-center justify-between gap-4">
+ <Text variant="small" className="text-zinc-500">
+ Couldn&apos;t load organisations.
+ </Text>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => void refetch()}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : organisations.length === 0 ? (
+ <Text variant="small" className="text-zinc-500">
+ No organisations.
+ </Text>
+ ) : (
+ <ul className="divide-y divide-zinc-200">
+ {organisations.map((organisation) => (
+ <li
+ key={organisation.id}
+ className="flex items-center justify-between gap-3 py-2.5 first:pt-0 last:pb-0"
+ >
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5">
+ <Text variant="body-medium" as="span" className="truncate">
+ {organisation.name}
+ </Text>
+ <Text
+ variant="small"
+ as="span"
+ className="font-mono text-zinc-500"
+ translate="no"
+ >
+ {organisation.slug}
+ </Text>
+ {organisation.is_personal ? (
+ <Badge variant="info" size="small">
+ Personal
+ </Badge>
+ ) : null}
+ </div>
+ <Text
+ variant="small"
+ as="span"
+ className="shrink-0 text-zinc-500"
+ >
+ {formatMonth(new Date(organisation.created_at))}
+ </Text>
+ </li>
+ ))}
+ </ul>
+ )}
+ </AdminSection>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/SpendingSection.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/SpendingSection.tsx
new file mode 100644
index 0000000000..69b6630d68
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/SpendingSection.tsx
@@ -0,0 +1,40 @@
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Link } from "@/components/atoms/Link/Link";
+import { ArrowUpRight01Icon } from "@hugeicons/core-free-icons";
+import { AdminSection } from "../../components/AdminSection";
+import { getSpendingSearchHref, getUserPlatformCostsHref } from "../helpers";
+
+interface Props {
+ userId: string;
+}
+
+export function SpendingSection({ userId }: Props) {
+ const links = [
+ { label: "Spending history", href: getSpendingSearchHref(userId) },
+ { label: "Platform cost", href: getUserPlatformCostsHref(userId) },
+ ];
+
+ return (
+ <AdminSection title="Spending and cost">
+ <ul className="-mx-2 flex flex-col">
+ {links.map((link) => (
+ <li key={link.href}>
+ <Link
+ variant="secondary"
+ href={link.href}
+ className="flex items-center justify-between rounded-lg px-2 py-1.5 no-underline hover:bg-zinc-50"
+ >
+ {link.label}
+ <Icon
+ icon={ArrowUpRight01Icon}
+ size={16}
+ className="text-zinc-500"
+ aria-hidden
+ />
+ </Link>
+ </li>
+ ))}
+ </ul>
+ </AdminSection>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/UserHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/UserHeader.tsx
new file mode 100644
index 0000000000..63f861204a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/UserHeader.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+} from "@/components/atoms/Avatar/Avatar";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { UserSwitchIcon } from "@hugeicons/core-free-icons";
+import { AdminSection } from "../../../components/AdminSection";
+import { useAdminImpersonation } from "../../../components/useAdminImpersonation";
+import { type AdminUser, getDisplayName } from "../../helpers";
+import { BanDialog } from "./components/BanDialog";
+import { ImpersonateDialog } from "./components/ImpersonateDialog";
+import { UnbanDialog } from "./components/UnbanDialog";
+
+interface Props {
+ user: AdminUser;
+ isSelf: boolean;
+ canAct: boolean;
+}
+
+export function UserHeader({ user, isSelf, canAct }: Props) {
+ const impersonation = useAdminImpersonation();
+ const displayName = getDisplayName(user);
+ const isImpersonatingThisUser = impersonation.impersonatedUserId === user.id;
+
+ return (
+ <AdminSection className="flex flex-wrap items-start justify-between gap-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <Avatar className="h-10 w-10 shrink-0">
+ {user.image ? <AvatarImage src={user.image} alt="" /> : null}
+ <AvatarFallback accessibleLabel={displayName} className="bg-zinc-100">
+ <span className="text-base font-medium text-zinc-700">
+ {displayName.charAt(0).toUpperCase()}
+ </span>
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex min-w-0 flex-col">
+ <div className="flex flex-wrap items-center gap-2">
+ <Text variant="large-medium" as="h2" className="break-all">
+ {displayName}
+ </Text>
+ {isSelf ? (
+ <Badge variant="info" size="small">
+ You
+ </Badge>
+ ) : null}
+ {user.role === "admin" ? (
+ <Badge variant="info" size="small">
+ Admin
+ </Badge>
+ ) : null}
+ {user.banned ? (
+ <Badge variant="error" size="small">
+ Banned
+ </Badge>
+ ) : null}
+ {user.emailVerified ? null : (
+ <Badge variant="warning" size="small">
+ Unverified
+ </Badge>
+ )}
+ </div>
+ <Text
+ variant="body"
+ className="break-all text-zinc-600"
+ translate="no"
+ >
+ {user.email}
+ </Text>
+ </div>
+ </div>
+
+ {canAct ? (
+ <div className="flex flex-wrap gap-2">
+ {isImpersonatingThisUser ? (
+ <Button
+ variant="secondary"
+ size="small"
+ leadingIcon={UserSwitchIcon}
+ onClick={impersonation.stopImpersonating}
+ >
+ Stop impersonating
+ </Button>
+ ) : (
+ <ImpersonateDialog
+ user={user}
+ currentImpersonationID={impersonation.impersonatedUserId}
+ isStarting={impersonation.isStarting}
+ onConfirm={() => impersonation.startImpersonating(user.id)}
+ />
+ )}
+ {user.banned ? (
+ <UnbanDialog user={user} />
+ ) : (
+ <BanDialog user={user} />
+ )}
+ </div>
+ ) : null}
+ </AdminSection>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/BanDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/BanDialog.tsx
new file mode 100644
index 0000000000..636ea5a9b5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/BanDialog.tsx
@@ -0,0 +1,122 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Select } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
+import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { UserBlock01Icon } from "@hugeicons/core-free-icons";
+import { useState } from "react";
+import {
+ type AdminUser,
+ BAN_DURATIONS,
+ type BanDuration,
+ formatDateTime,
+ formatTimeUntil,
+ getBanEnd,
+ getDisplayName,
+} from "../../../helpers";
+import { useUserBan } from "../../../useUserBan";
+
+interface Props {
+ user: AdminUser;
+}
+
+const DURATION_OPTIONS = BAN_DURATIONS.map(({ value, label }) => ({
+ value,
+ label,
+}));
+
+export function BanDialog({ user }: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [reason, setReason] = useState("");
+ const [duration, setDuration] = useState<BanDuration>("permanent");
+ const { banUser, isBanning } = useUserBan(user);
+ const banEnd = getBanEnd(duration);
+
+ function handleOpenChange(open: boolean) {
+ setIsOpen(open);
+ if (open) {
+ setReason("");
+ setDuration("permanent");
+ }
+ }
+
+ return (
+ <Dialog
+ title={`Ban ${getDisplayName(user)}?`}
+ styling={{ maxWidth: "480px" }}
+ controlled={{ isOpen, set: handleOpenChange }}
+ >
+ <Dialog.Trigger>
+ <Button variant="secondary" size="small" leadingIcon={UserBlock01Icon}>
+ Ban user…
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <div className="flex flex-col gap-4">
+ <Text variant="body" className="text-zinc-600">
+ They&apos;re signed out and can&apos;t sign in again until the ban
+ ends, but for up to 5 minutes they can still get a token that works
+ for an hour. Their API keys, schedules and triggers keep running.
+ </Text>
+ {user.role === "admin" ? (
+ <Alert variant="warning">
+ <AlertDescription>This account is an admin.</AlertDescription>
+ </Alert>
+ ) : null}
+ <Input
+ id="ban-reason"
+ label="Reason (required)"
+ type="textarea"
+ rows={3}
+ placeholder="What they did"
+ value={reason}
+ onChange={(event) => setReason(event.target.value)}
+ required
+ wrapperClassName="mb-0"
+ />
+ <div className="flex flex-col gap-1">
+ <Select
+ id="ban-duration"
+ label="Duration"
+ value={duration}
+ onValueChange={(value) => setDuration(value as BanDuration)}
+ options={DURATION_OPTIONS}
+ wrapperClassName="mb-0"
+ />
+ <Text variant="small" className="text-zinc-500">
+ {banEnd
+ ? `Ends ${formatDateTime(banEnd)} (${formatTimeUntil(banEnd)})`
+ : "Doesn't end on its own."}
+ </Text>
+ </div>
+ </div>
+ <Dialog.Footer>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ size="small"
+ loading={isBanning}
+ disabled={!reason.trim()}
+ onClick={() =>
+ banUser(
+ { reason, duration },
+ { onSuccess: () => setIsOpen(false) },
+ )
+ }
+ >
+ Ban user
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/ImpersonateDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/ImpersonateDialog.tsx
new file mode 100644
index 0000000000..ab0f8e238c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/ImpersonateDialog.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { UserSwitchIcon } from "@hugeicons/core-free-icons";
+import { useState } from "react";
+import { type AdminUser, getDisplayName } from "../../../helpers";
+
+interface Props {
+ user: AdminUser;
+ currentImpersonationID: string | null;
+ isStarting: boolean;
+ onConfirm: () => Promise<void>;
+}
+
+export function ImpersonateDialog({
+ user,
+ currentImpersonationID,
+ isStarting,
+ onConfirm,
+}: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <Dialog
+ title={`Impersonate ${getDisplayName(user)}?`}
+ styling={{ maxWidth: "480px" }}
+ controlled={{ isOpen, set: setIsOpen }}
+ >
+ <Dialog.Trigger>
+ <Button variant="secondary" size="small" leadingIcon={UserSwitchIcon}>
+ Impersonate
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <Text variant="body" className="text-zinc-600">
+ You&apos;ll see and act as this user across the whole platform until
+ you stop. A notice goes to the audit channel first, then this page
+ reloads.
+ {currentImpersonationID
+ ? ` This ends your current impersonation of ${currentImpersonationID}.`
+ : null}
+ </Text>
+ <Dialog.Footer>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ loading={isStarting}
+ onClick={() => void onConfirm()}
+ >
+ Impersonate
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/UnbanDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/UnbanDialog.tsx
new file mode 100644
index 0000000000..ec7cf1201b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserHeader/components/UnbanDialog.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { UserUnlock01Icon } from "@hugeicons/core-free-icons";
+import { useState } from "react";
+import { type AdminUser, getDisplayName } from "../../../helpers";
+import { useUserBan } from "../../../useUserBan";
+
+interface Props {
+ user: AdminUser;
+}
+
+export function UnbanDialog({ user }: Props) {
+ const [isOpen, setIsOpen] = useState(false);
+ const { unbanUser, isUnbanning } = useUserBan(user);
+
+ return (
+ <Dialog
+ title={`Unban ${getDisplayName(user)}?`}
+ styling={{ maxWidth: "480px" }}
+ controlled={{ isOpen, set: setIsOpen }}
+ >
+ <Dialog.Trigger>
+ <Button variant="secondary" size="small" leadingIcon={UserUnlock01Icon}>
+ Unban
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <Text variant="body" className="text-zinc-600">
+ They can sign in again right away.
+ </Text>
+ <Dialog.Footer>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ loading={isUnbanning}
+ onClick={() =>
+ unbanUser(undefined, { onSuccess: () => setIsOpen(false) })
+ }
+ >
+ Unban
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserLookupBar.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserLookupBar.tsx
new file mode 100644
index 0000000000..b4c45d954e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserLookupBar.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { SearchInput } from "@/components/molecules/SearchInput/SearchInput";
+import { FormEvent, useEffect, useRef, useState } from "react";
+
+interface Props {
+ initialValue: string;
+ isLoading: boolean;
+ showHint: boolean;
+ onSearch: (value: string) => void;
+}
+
+export function UserLookupBar({
+ initialValue,
+ isLoading,
+ showHint,
+ onSearch,
+}: Props) {
+ const [value, setValue] = useState(initialValue);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ // Only where it can't pop up a touch keyboard over the page.
+ if (!initialValue && window.matchMedia("(pointer: fine)").matches) {
+ inputRef.current?.focus();
+ }
+ }, [initialValue]);
+
+ function handleSubmit(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ onSearch(value);
+ }
+
+ return (
+ <form
+ role="search"
+ onSubmit={handleSubmit}
+ className="flex max-w-[640px] flex-col gap-2"
+ >
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <SearchInput
+ ref={inputRef}
+ value={value}
+ onChange={setValue}
+ placeholder="User ID or email…"
+ name="user"
+ autoComplete="off"
+ spellCheck={false}
+ aria-label="User ID or email"
+ disabled={isLoading}
+ size="small"
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ loading={isLoading}
+ disabled={!value.trim()}
+ className="shrink-0"
+ >
+ Look up
+ </Button>
+ </div>
+ {showHint ? (
+ <Text variant="small" className="text-zinc-500">
+ Exact match only: a full user ID or the complete email address.
+ </Text>
+ ) : null}
+ </form>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserView/UserView.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserView/UserView.tsx
new file mode 100644
index 0000000000..22205c3eb1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/components/UserView/UserView.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { useAuth } from "@/lib/auth/hooks/useAuth";
+import type { AdminUser } from "../../helpers";
+import { AutoPilotUsageSection } from "../AutoPilotUsageSection/AutoPilotUsageSection";
+import { BannedAlert } from "../BannedAlert";
+import { DetailsSection } from "../DetailsSection";
+import { OrganisationsSection } from "../OrganisationsSection";
+import { SpendingSection } from "../SpendingSection";
+import { UserHeader } from "../UserHeader/UserHeader";
+
+interface Props {
+ user: AdminUser;
+}
+
+// The column wrappers are `display: contents` below lg, so the `order-*`
+// classes interleave both columns into one: identity before controls.
+export function UserView({ user }: Props) {
+ const { user: signedInUser } = useAuth();
+ const isSelf = signedInUser?.id === user.id;
+ // Until the signed-in admin is known, their own row would offer Ban.
+ const canAct = Boolean(signedInUser) && !isSelf;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <UserHeader user={user} isSelf={isSelf} canAct={canAct} />
+ {user.banned ? <BannedAlert user={user} /> : null}
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="contents lg:flex lg:flex-col lg:gap-6">
+ <div className="order-2 lg:order-none">
+ <AutoPilotUsageSection userId={user.id} />
+ </div>
+ <div className="order-3 lg:order-none">
+ <OrganisationsSection userId={user.id} />
+ </div>
+ </div>
+ <div className="contents lg:flex lg:flex-col lg:gap-6">
+ <div className="order-1 lg:order-none">
+ <DetailsSection user={user} />
+ </div>
+ <div className="order-4 lg:order-none">
+ <SpendingSection userId={user.id} />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/users/helpers.ts
new file mode 100644
index 0000000000..02940ea2e4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/helpers.ts
@@ -0,0 +1,172 @@
+export const USER_QUERY_PARAM = "user";
+
+export interface LookupQuery {
+ kind: "id" | "email";
+ value: string;
+}
+
+export interface AdminUser {
+ id: string;
+ email: string;
+ name: string;
+ image: string | null;
+ role: string | null;
+ emailVerified: boolean;
+ createdAt: Date;
+ banned: boolean;
+ banReason: string | null;
+ banExpires: Date | null;
+}
+
+// Better Auth's admin endpoints return the auth identity row with dates
+// already revived or as ISO strings, depending on the client's parser.
+export interface AuthUserRecord {
+ id: string;
+ email: string;
+ name: string;
+ image?: string | null;
+ role?: string | null;
+ emailVerified: boolean;
+ createdAt: Date | string;
+ banned?: boolean | null;
+ banReason?: string | null;
+ banExpires?: Date | string | null;
+}
+
+export const BAN_DURATIONS = [
+ { value: "permanent", label: "Permanent", seconds: undefined },
+ { value: "1h", label: "1 hour", seconds: 60 * 60 },
+ { value: "1d", label: "1 day", seconds: 60 * 60 * 24 },
+ { value: "7d", label: "7 days", seconds: 60 * 60 * 24 * 7 },
+ { value: "30d", label: "30 days", seconds: 60 * 60 * 24 * 30 },
+] as const;
+
+export type BanDuration = (typeof BAN_DURATIONS)[number]["value"];
+
+export function parseLookupQuery(
+ raw: string | null | undefined,
+): LookupQuery | null {
+ const value = raw?.trim();
+ if (!value) return null;
+ // Better Auth stores emails lowercased, so this makes the exact match
+ // case-insensitive without a LIKE.
+ if (value.includes("@")) return { kind: "email", value: value.toLowerCase() };
+ return { kind: "id", value };
+}
+
+export function toAdminUser(
+ record: AuthUserRecord,
+ now = new Date(),
+): AdminUser {
+ const banExpires = record.banExpires ? new Date(record.banExpires) : null;
+ // Better Auth clears a lapsed ban only at the user's next sign-in.
+ const banned = Boolean(record.banned) && !(banExpires && banExpires <= now);
+ return {
+ id: record.id,
+ email: record.email,
+ name: record.name,
+ image: record.image ?? null,
+ role: record.role ?? null,
+ emailVerified: record.emailVerified,
+ createdAt: new Date(record.createdAt),
+ banned,
+ banReason: banned ? (record.banReason ?? null) : null,
+ banExpires: banned ? banExpires : null,
+ };
+}
+
+export function getBanDurationSeconds(duration: BanDuration) {
+ return BAN_DURATIONS.find((option) => option.value === duration)?.seconds;
+}
+
+// A repeated query param (`?user=a&user=b`) reaches a page as an array.
+export function getAdminUsersHref(user?: string | string[] | null) {
+ const value = (Array.isArray(user) ? user[0] : user)?.trim();
+ if (!value) return "/admin/users";
+ return `/admin/users?${new URLSearchParams({ [USER_QUERY_PARAM]: value })}`;
+}
+
+// The spending search is a substring match on user ID, email and name. A full
+// UUID holds no LIKE wildcards, so searching one only ever matches that user.
+export function getSpendingSearchHref(search: string) {
+ return `/admin/spending?${new URLSearchParams({ search })}`;
+}
+
+export function getUserPlatformCostsHref(userId: string) {
+ return `/admin/platform-costs?${new URLSearchParams({ user_id: userId })}`;
+}
+
+// Pinned to en-GB so dates read "12 Mar 2026" and times 24h whatever the
+// admin's browser locale.
+const DATE_FORMAT = new Intl.DateTimeFormat("en-GB", {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+});
+const DATE_TIME_FORMAT = new Intl.DateTimeFormat("en-GB", {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+});
+const MONTH_FORMAT = new Intl.DateTimeFormat("en-GB", {
+ month: "short",
+ year: "numeric",
+});
+const RELATIVE_FORMAT = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
+
+const HOUR_MS = 60 * 60 * 1000;
+const DAY_MS = 24 * HOUR_MS;
+
+export function formatDate(date: Date) {
+ return DATE_FORMAT.format(date);
+}
+
+export function formatDateTime(date: Date) {
+ return DATE_TIME_FORMAT.format(date);
+}
+
+export function formatMonth(date: Date) {
+ return MONTH_FORMAT.format(date);
+}
+
+export function formatTimeUntil(date: Date, now = new Date()) {
+ const ms = date.getTime() - now.getTime();
+ if (Math.abs(ms) < DAY_MS) {
+ return RELATIVE_FORMAT.format(Math.round(ms / HOUR_MS), "hour");
+ }
+ return RELATIVE_FORMAT.format(Math.round(ms / DAY_MS), "day");
+}
+
+export function getBanEnd(duration: BanDuration, now = new Date()) {
+ const seconds = getBanDurationSeconds(duration);
+ return seconds === undefined
+ ? null
+ : new Date(now.getTime() + seconds * 1000);
+}
+
+export function getDisplayName(user: Pick<AdminUser, "name" | "email">) {
+ return user.name.trim() || user.email;
+}
+
+const PLAN_NAMES: Record<string, string> = {
+ NO_TIER: "No plan",
+ TRIAL: "Trial",
+ BASIC: "Basic",
+ PRO: "Pro",
+ MAX: "Max",
+ BUSINESS: "Business",
+ ENTERPRISE: "Enterprise",
+};
+
+export function getPlanName(tier: string) {
+ return PLAN_NAMES[tier] ?? tier;
+}
+
+// Orval types a mutation's error as the response body, but the mutator throws
+// an ApiError carrying the server's message.
+export function getErrorMessage(error: unknown) {
+ return error instanceof Error ? error.message : "Something went wrong.";
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/users/page.tsx
index 5c25206cd1..17f24d3eae 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/users/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/page.tsx
@@ -1,18 +1,9 @@
import { withRoleAccess } from "@/lib/withRoleAccess";
-import React from "react";
-
-function AdminUsers() {
- return (
- <div>
- <h1>Users Dashboard</h1>
- {/* Add your admin-only content here */}
- </div>
- );
-}
+import { AdminUsersView } from "./components/AdminUsersView/AdminUsersView";
export default async function AdminUsersPage() {
"use server";
const withAdminAccess = await withRoleAccess(["admin"]);
- const ProtectedAdminUsers = await withAdminAccess(AdminUsers);
+ const ProtectedAdminUsers = await withAdminAccess(AdminUsersView);
return <ProtectedAdminUsers />;
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/useAdminUserLookup.ts b/autogpt_platform/frontend/src/app/(platform)/admin/users/useAdminUserLookup.ts
new file mode 100644
index 0000000000..6dfebf1ed8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/useAdminUserLookup.ts
@@ -0,0 +1,67 @@
+"use client";
+
+import { authClient } from "@/lib/auth/client";
+import { useQuery } from "@tanstack/react-query";
+import { useQueryState } from "nuqs";
+import {
+ type AdminUser,
+ type LookupQuery,
+ parseLookupQuery,
+ toAdminUser,
+ USER_QUERY_PARAM,
+} from "./helpers";
+
+export function useAdminUserLookup() {
+ const [userParam, setUserParam] = useQueryState(USER_QUERY_PARAM);
+ const query = parseLookupQuery(userParam);
+
+ const lookup = useQuery({
+ queryKey: getAdminUserLookupQueryKey(query),
+ queryFn: () => lookUpUser(query!),
+ enabled: query !== null,
+ });
+
+ function search(raw: string) {
+ void setUserParam(raw.trim() || null);
+ }
+
+ return {
+ rawQuery: userParam ?? "",
+ query,
+ user: lookup.data ?? null,
+ isLoading: lookup.isLoading,
+ isNotFound: lookup.isSuccess && lookup.data === null,
+ error: lookup.error,
+ search,
+ refetch: lookup.refetch,
+ };
+}
+
+export function getAdminUserLookupQueryKey(query: LookupQuery | null) {
+ return ["admin", "user-lookup", query?.kind, query?.value] as const;
+}
+
+// Both paths are exact: get-user matches the primary key, and list-users with
+// filterOperator "eq" compiles to `=`, so `_` and `%` match only themselves.
+async function lookUpUser(query: LookupQuery): Promise<AdminUser | null> {
+ if (query.kind === "id") {
+ const { data, error } = await authClient.admin.getUser({
+ query: { id: query.value },
+ });
+ if (error?.status === 404) return null;
+ if (error) throw new Error(error.message || "Failed to look up the user");
+ return data ? toAdminUser(data) : null;
+ }
+
+ const { data, error } = await authClient.admin.listUsers({
+ query: {
+ filterField: "email",
+ filterOperator: "eq",
+ filterValue: query.value,
+ limit: 1,
+ },
+ });
+ if (error) throw new Error(error.message || "Failed to look up the user");
+ const match = data?.users[0];
+ return match ? toAdminUser(match) : null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/users/useUserBan.ts b/autogpt_platform/frontend/src/app/(platform)/admin/users/useUserBan.ts
new file mode 100644
index 0000000000..e92ecd94a0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/users/useUserBan.ts
@@ -0,0 +1,94 @@
+"use client";
+
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { authClient } from "@/lib/auth/client";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ type AdminUser,
+ type BanDuration,
+ getBanDurationSeconds,
+ parseLookupQuery,
+ toAdminUser,
+} from "./helpers";
+import { getAdminUserLookupQueryKey } from "./useAdminUserLookup";
+
+interface BanArgs {
+ reason: string;
+ duration: BanDuration;
+}
+
+export function useUserBan(user: AdminUser) {
+ const { toast } = useToast();
+ const queryClient = useQueryClient();
+
+ function storeUpdatedUser(updated: AdminUser) {
+ for (const lookup of [updated.id, updated.email]) {
+ queryClient.setQueryData(
+ getAdminUserLookupQueryKey(parseLookupQuery(lookup)),
+ updated,
+ );
+ }
+ }
+
+ const ban = useMutation({
+ mutationFn: async ({ reason, duration }: BanArgs) => {
+ const banReason = reason.trim();
+ if (!banReason) throw new Error("Give a reason for the ban.");
+ const { data, error } = await authClient.admin.banUser({
+ userId: user.id,
+ banReason,
+ banExpiresIn: getBanDurationSeconds(duration),
+ });
+ if (error || !data) {
+ throw new Error(error?.message || "Failed to ban the user");
+ }
+ return toAdminUser(data.user);
+ },
+ onSuccess: (updated) => {
+ storeUpdatedUser(updated);
+ toast({
+ title: `Banned ${updated.email}`,
+ description:
+ "Their sessions are signed out. Tokens they hold or get in the next 5 minutes work for up to an hour, and their API keys, schedules and triggers keep running.",
+ variant: "success",
+ });
+ },
+ onError: (error) => {
+ toast({
+ title: "Couldn't ban the user",
+ description: error.message,
+ variant: "destructive",
+ });
+ },
+ });
+
+ const unban = useMutation({
+ mutationFn: async () => {
+ const { data, error } = await authClient.admin.unbanUser({
+ userId: user.id,
+ });
+ if (error || !data) {
+ throw new Error(error?.message || "Failed to unban the user");
+ }
+ return toAdminUser(data.user);
+ },
+ onSuccess: (updated) => {
+ storeUpdatedUser(updated);
+ toast({ title: `Unbanned ${updated.email}`, variant: "success" });
+ },
+ onError: (error) => {
+ toast({
+ title: "Couldn't unban the user",
+ description: error.message,
+ variant: "destructive",
+ });
+ },
+ });
+
+ return {
+ banUser: ban.mutate,
+ unbanUser: unban.mutate,
+ isBanning: ban.isPending,
+ isUnbanning: unban.isPending,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 4ec7df3f9e..4df3209701 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2747,6 +2747,48 @@
}
}
},
+ "/api/admin/users/{user_id}/organizations": {
+ "get": {
+ "tags": ["admin"],
+ "summary": "Get user organizations",
+ "description": "The organizations a user is an active member of. Admin-only.",
+ "operationId": "getAdminGet user organizations",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "User Id" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/OrgResponse" },
+ "title": "Response Getadminget User Organizations"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/analytics/attribution": {
"post": {
"tags": ["analytics"],
diff --git a/autogpt_platform/frontend/src/components/molecules/SearchInput/SearchInput.tsx b/autogpt_platform/frontend/src/components/molecules/SearchInput/SearchInput.tsx
index 858eb769bf..6149564c02 100644
--- a/autogpt_platform/frontend/src/components/molecules/SearchInput/SearchInput.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/SearchInput/SearchInput.tsx
@@ -17,6 +17,9 @@ interface Props {
disabled?: boolean;
loading?: boolean;
maxLength?: number;
+ name?: string;
+ autoComplete?: string;
+ spellCheck?: boolean;
size?: "xsmall" | "small" | "medium";
className?: string;
}
@@ -43,6 +46,9 @@ export const SearchInput = forwardRef<HTMLInputElement, Props>(
disabled,
loading,
maxLength,
+ name,
+ autoComplete,
+ spellCheck,
size = "medium",
className,
},
@@ -68,6 +74,9 @@ export const SearchInput = forwardRef<HTMLInputElement, Props>(
aria-label={ariaLabel ?? placeholder}
disabled={disabled}
maxLength={maxLength}
+ name={name}
+ autoComplete={autoComplete}
+ spellCheck={spellCheck}
className={cn(
"w-full rounded-xl border border-input bg-background text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-60",
sizeStyles[size],