The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(ui): migrate 5 simple tables onto shared DataTable (#33548)
yuneng-jiang3459956fd259
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 9de171397db..cad2874c1e6 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -984,11 +984,6 @@"count": 2}},- "src/app/(dashboard)/projects/_components/ProjectsPage.tsx": {- "react-hooks/set-state-in-effect": {- "count": 1- }- },"src/app/(dashboard)/prompts/_components/add_prompt_form.tsx": {"no-restricted-imports": {"count": 1@@ -1528,14 +1523,6 @@"count": 1}},- "src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.tsx": {- "no-nested-ternary": {- "count": 1- },- "no-restricted-imports": {- "count": 1- }- },"src/components/Settings/RouterSettings/Fallbacks/AddFallbacks.tsx": {"no-restricted-imports": {"count": 1@@ -2095,11 +2082,6 @@"count": 1}},- "src/components/pass_through_settings.tsx": {- "no-restricted-imports": {- "count": 1- }- },"src/components/per_user_usage.tsx": {"no-restricted-imports": {"count": 1diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsxindex 4bf4af0c7f6..aac5405ce6b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx@@ -26,7 +26,7 @@ import HealthCheckComponent from "../../../components/model_dashboard/HealthChecimport ModelGroupAliasSettings from "../../../components/model_group_alias_settings";import ModelInfoView from "../../../components/model_info_view";import NotificationsManager from "../../../components/molecules/notifications_manager";-import PassThroughSettings from "../../../components/pass_through_settings";+import PassThroughSettings from "../../../components/PassThroughSettings/PassThroughSettings";import TeamInfoView from "../../../components/team/TeamInfo";import useAuthorized from "../hooks/useAuthorized";@@ -396,7 +396,6 @@ const ModelsAndEndpointsView: React.FC<ModelDashboardProps> = ({ premiumUser, teaccessToken={accessToken}userRole={userRole}userID={userID}- modelData={processedModelData}premiumUser={premiumUser}/></TabPanel>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.test.tsxindex 6f8676360c4..61d42f2aac6 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.test.tsx@@ -22,6 +22,12 @@ vi.mock("@/components/common_components/DefaultProxyAdminTag", () => ({default: ({ userId }: { userId: string }) => <span>{userId}</span>,}));+vi.mock("./ProjectKeysSection", () => ({+ ProjectKeysSection: ({ projectId }: { projectId: string }) => (+ <div data-testid="project-keys-section">{projectId}</div>+ ),+}));+const mockProject: ProjectResponse = {project_id: "proj-1",project_alias: "My Project",@@ -98,6 +104,11 @@ describe("ProjectDetail", () => {expect(screen.getByRole("heading", { name: "My Project" })).toBeInTheDocument();});+ it("should render the project keys section for the project", () => {+ renderWithProviders(<ProjectDetail projectId="proj-1" onBack={onBack} />);+ expect(screen.getByTestId("project-keys-section")).toHaveTextContent("proj-1");+ });+it("should display 'Active' for a non-blocked project", () => {renderWithProviders(<ProjectDetail projectId="proj-1" onBack={onBack} />);expect(screen.getByText("Active")).toBeInTheDocument();diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.tsxindex 2bc8bc31129..fd043031b26 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectDetailsPage.tsx@@ -17,10 +17,11 @@ import {} from "antd";import { LoadingOutlined } from "@ant-design/icons";import { BarChart } from "@/components/shared/charts";-import { ArrowLeftIcon, DollarSignIcon, EditIcon, KeyIcon, UsersIcon } from "lucide-react";+import { ArrowLeftIcon, DollarSignIcon, EditIcon, UsersIcon } from "lucide-react";import { useMemo, useState } from "react";import DefaultProxyAdminTag from "@/components/common_components/DefaultProxyAdminTag";import { EditProjectModal } from "./ProjectModals/EditProjectModal";+import { ProjectKeysSection } from "./ProjectKeysSection";const { Title, Text } = Typography;const { Content } = Layout;@@ -203,17 +204,7 @@ export function ProjectDetail({ projectId, onBack }: ProjectDetailProps) {{/* Keys & Team */}<Row gutter={[16, 16]} style={{ marginBottom: 24 }}><Col xs={24} lg={12}>- <Card- title={- <Flex align="center" gap={8}>- <KeyIcon size={16} />- Keys- </Flex>- }- style={{ height: "100%" }}- >- <Empty description="No keys to display" image={Empty.PRESENTED_IMAGE_SIMPLE} />- </Card>+ <ProjectKeysSection projectId={projectId} /></Col><Col xs={24} lg={12}><Carddiff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.test.tsxindex 7efbaedef46..0ba1dcab155 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.test.tsx@@ -35,7 +35,7 @@ describe("ProjectKeysSection", () => {isLoading: false,});renderWithProviders(<ProjectKeysSection projectId="proj-1" />);- expect(screen.getByText("42 keys")).toBeInTheDocument();+ expect(screen.getByTestId("pagination-range")).toHaveTextContent("of 42");});it("should show 'No keys found' when the project has no keys", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.tsxindex 9f60db596e8..4266b238e21 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysSection.tsx@@ -1,6 +1,6 @@import { useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";-import { LoadingOutlined } from "@ant-design/icons";-import { Card, Flex, Input, Pagination, Spin } from "antd";+import { PaginationState } from "@tanstack/react-table";+import { Card, Flex, Input } from "antd";import { KeyIcon, SearchIcon } from "lucide-react";import { useEffect, useState } from "react";import { ProjectKeysTable } from "./ProjectKeysTable";@@ -12,17 +12,16 @@ interface ProjectKeysSectionProps {const PAGE_SIZE = 5;export function ProjectKeysSection({ projectId }: ProjectKeysSectionProps) {- const [page, setPage] = useState(1);+ const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: PAGE_SIZE });const [keyAlias, setKeyAlias] = useState<string>("");- const { data, isLoading } = useKeys(page, PAGE_SIZE, {+ const { data, isLoading } = useKeys(pagination.pageIndex + 1, pagination.pageSize, {projectID: projectId,selectedKeyAlias: keyAlias || null,});- // Reset to page 1 when filter changesuseEffect(() => {- setPage(1);+ setPagination((current) => ({ ...current, pageIndex: 0 }));}, [keyAlias]);const keys = data?.keys ?? [];@@ -38,7 +37,7 @@ export function ProjectKeysSection({ projectId }: ProjectKeysSectionProps) {}style={{ height: "100%" }}>- <Flex justify="space-between" align="center" style={{ marginBottom: 12 }}>+ <Flex justify="flex-start" align="center" style={{ marginBottom: 12 }}><Inputprefix={<SearchIcon size={14} />}placeholder="Filter by key name..."@@ -48,19 +47,13 @@ export function ProjectKeysSection({ projectId }: ProjectKeysSectionProps) {allowClearsize="small"/>- <Pagination- current={page}- total={totalCount}- pageSize={PAGE_SIZE}- onChange={setPage}- size="small"- showSizeChanger={false}- showTotal={(total) => `${total} keys`}- /></Flex><ProjectKeysTablekeys={keys}- loading={isLoading ? { indicator: <Spin indicator={<LoadingOutlined spin />} /> } : false}+ totalCount={totalCount}+ isLoading={isLoading}+ pagination={pagination}+ onPaginationChange={setPagination}/></Card>);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.test.tsxindex c0f12f77cfb..3685d30b414 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.test.tsx@@ -1,4 +1,5 @@import { describe, it, expect, vi } from "vitest";+import userEvent from "@testing-library/user-event";import { renderWithProviders, screen } from "../../../../../tests/test-utils";import { ProjectKeysTable } from "./ProjectKeysTable";import { KeyResponse } from "@/components/key_team_helpers/key_list";@@ -7,6 +8,13 @@ vi.mock("@/components/common_components/DefaultProxyAdminTag", () => ({default: ({ userId }: { userId: string }) => <span data-testid="owner-tag">{userId}</span>,}));+const defaultProps = {+ totalCount: 0,+ isLoading: false,+ pagination: { pageIndex: 0, pageSize: 5 },+ onPaginationChange: vi.fn(),+};+function makeKey(overrides: Partial<KeyResponse> = {}): KeyResponse {return {token: "tok-abc123",@@ -70,52 +78,78 @@ function makeKey(overrides: Partial<KeyResponse> = {}): KeyResponse {describe("ProjectKeysTable", () => {it("should render", () => {- renderWithProviders(<ProjectKeysTable keys={[]} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[]} />);expect(screen.getByRole("table")).toBeInTheDocument();});it("should display 'No keys found' when the keys list is empty", () => {- renderWithProviders(<ProjectKeysTable keys={[]} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[]} />);expect(screen.getByText("No keys found")).toBeInTheDocument();});it("should display the key alias when provided", () => {- renderWithProviders(<ProjectKeysTable keys={[makeKey({ key_alias: "My API Key" })]} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[makeKey({ key_alias: "My API Key" })]} />);expect(screen.getByText("My API Key")).toBeInTheDocument();});it("should display '—' when the key alias is null", () => {// Provide a user_id so only the alias column shows "—" (not the owner column too)- renderWithProviders(<ProjectKeysTable keys={[makeKey({ key_alias: null as any, user_id: "owner-1" })]} />);+ renderWithProviders(+ <ProjectKeysTable {...defaultProps} keys={[makeKey({ key_alias: null as any, user_id: "owner-1" })]} />,+ );expect(screen.getByText("—")).toBeInTheDocument();});it("should display the owner using user.user_email when available", () => {- const key = makeKey({ user: { user_id: "u1", user_email: "[email protected]" } });- renderWithProviders(<ProjectKeysTable keys={[key]} />);+ const key = makeKey({ user: { user_id: "u1", user_email: "[email protected]", user_alias: null } });+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[key]} />);expect(screen.getByTestId("owner-tag")).toHaveTextContent("[email protected]");});it("should fall back to user_id when user.user_email is absent", () => {const key = makeKey({ user_id: "user-99" });- renderWithProviders(<ProjectKeysTable keys={[key]} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[key]} />);expect(screen.getByTestId("owner-tag")).toHaveTextContent("user-99");});it("should display 'Never' in the Last Active column when last_active is null", () => {- renderWithProviders(<ProjectKeysTable keys={[makeKey({ last_active: null })]} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[makeKey({ last_active: null })]} />);expect(screen.getByText("Never")).toBeInTheDocument();});it("should display a formatted date in the Last Active column when last_active is provided", () => {- renderWithProviders(<ProjectKeysTable keys={[makeKey({ last_active: "2024-06-15T10:00:00Z" })]} />);+ renderWithProviders(+ <ProjectKeysTable {...defaultProps} keys={[makeKey({ last_active: "2024-06-15T10:00:00Z" })]} />,+ );expect(screen.queryByText("Never")).not.toBeInTheDocument();});it("should render multiple keys as separate rows", () => {const keys = [makeKey({ token: "tok-1", key_alias: "Key One" }), makeKey({ token: "tok-2", key_alias: "Key Two" })];- renderWithProviders(<ProjectKeysTable keys={keys} />);+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={keys} />);expect(screen.getByText("Key One")).toBeInTheDocument();expect(screen.getByText("Key Two")).toBeInTheDocument();});++ it("should show skeleton rows while loading", () => {+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[]} isLoading />);+ expect(screen.getAllByTestId("skeleton-row").length).toBeGreaterThan(0);+ expect(screen.queryByText("No keys found")).not.toBeInTheDocument();+ });++ it("should show the server-side total in the pagination footer", () => {+ renderWithProviders(<ProjectKeysTable {...defaultProps} keys={[makeKey()]} totalCount={42} />);+ expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-5 of 42");+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 1 of 9");+ });++ it("should request the next page through the pagination footer", async () => {+ const user = userEvent.setup();+ const onPaginationChange = vi.fn();+ renderWithProviders(+ <ProjectKeysTable {...defaultProps} keys={[makeKey()]} totalCount={42} onPaginationChange={onPaginationChange} />,+ );+ await user.click(screen.getByTestId("pagination-next"));+ expect(onPaginationChange).toHaveBeenCalled();+ });});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.tsxindex 8269c843b98..080aad7b26d 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTable.tsx@@ -1,59 +1,59 @@+"use client";++import { OnChangeFn, PaginationState } from "@tanstack/react-table";+import { KeyRound } from "lucide-react";+import { useMemo } from "react";+import { KeyResponse } from "@/components/key_team_helpers/key_list";-import { Empty, Table, Tooltip } from "antd";-import type { ColumnsType } from "antd/es/table";-import type { SpinProps } from "antd";-import DefaultProxyAdminTag from "@/components/common_components/DefaultProxyAdminTag";-import { DateCell } from "@/components/shared/table_cells";+import { DataTable } from "@/components/shared/DataTable";++import { getProjectKeysTableColumns } from "./ProjectKeysTableColumns";interface ProjectKeysTableProps {keys: KeyResponse[];- loading?: boolean | SpinProps;+ totalCount: number;+ isLoading: boolean;+ pagination: PaginationState;+ onPaginationChange: OnChangeFn<PaginationState>;}-const columns: ColumnsType<KeyResponse> = [- {- title: "Key Name",- dataIndex: "key_alias",- key: "key_alias",- render: (alias: string | null) => alias || "—",- },- {- title: "Owner",- key: "owner",- render: (_: unknown, record: KeyResponse) => {- const email = record.user?.user_email ?? record.user_id ?? null;- if (!email) return "—";- return (- <Tooltip title={email}>- <DefaultProxyAdminTag userId={email} />- </Tooltip>- );- },- },- {- title: "Created",- dataIndex: "created_at",- key: "created_at",- render: (date: string) => <DateCell value={date} precision="date" />,- },- {- title: "Last Active",- dataIndex: "last_active",- key: "last_active",- render: (date: string | null) => <DateCell value={date} precision="date" fallback="Never" />,- },-];--export function ProjectKeysTable({ keys, loading }: ProjectKeysTableProps) {+const PAGE_SIZE_OPTIONS = [5, 10, 25];++function EmptyState() {+ return (+ <div className="flex flex-col items-center gap-1 py-6">+ <div className="mb-1 flex size-10 items-center justify-center rounded-lg bg-muted">+ <KeyRound className="size-5 text-muted-foreground" />+ </div>+ <div className="text-sm font-medium text-foreground">No keys found</div>+ <div className="text-sm text-muted-foreground">Keys created in this project will show up here.</div>+ </div>+ );+}++export function ProjectKeysTable({+ keys,+ totalCount,+ isLoading,+ pagination,+ onPaginationChange,+}: ProjectKeysTableProps) {+ const columns = useMemo(() => getProjectKeysTableColumns(), []);+return (- <Table+ <DataTable+ data={keys}columns={columns}- dataSource={keys}- rowKey="token"- loading={loading}- pagination={false}- size="small"- locale={{ emptyText: <Empty description="No keys found" image={Empty.PRESENTED_IMAGE_SIMPLE} /> }}+ getRowId={(key, index) => key.token || String(index)}+ paginationMode="server"+ pagination={pagination}+ onPaginationChange={onPaginationChange}+ rowCount={totalCount}+ pageSizeOptions={PAGE_SIZE_OPTIONS}+ isLoading={isLoading}+ loadingMessage="Loading keys…"+ noDataMessage={<EmptyState />}+ size="compact"/>);}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTableColumns.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTableColumns.tsxnew file mode 100644index 00000000000..b04a32844ea--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectKeysTableColumns.tsx@@ -0,0 +1,62 @@+"use client";++import { ColumnDef } from "@tanstack/react-table";++import DefaultProxyAdminTag from "@/components/common_components/DefaultProxyAdminTag";+import { KeyResponse } from "@/components/key_team_helpers/key_list";+import { CellTooltip, DateCell } from "@/components/shared/table_cells";++function OwnerCell({ record }: { record: KeyResponse }) {+ const email = record.user?.user_email ?? record.user_id ?? null;+ if (!email) return <span className="text-sm">—</span>;+ return (+ <CellTooltip+ content={email}+ trigger={+ <span className="inline-flex max-w-60 truncate">+ <DefaultProxyAdminTag userId={email} />+ </span>+ }+ />+ );+}++export const getProjectKeysTableColumns = (): ColumnDef<KeyResponse>[] => [+ {+ id: "key_alias",+ accessorKey: "key_alias",+ meta: { title: "Key Name" },+ header: "Key Name",+ enableSorting: false,+ cell: ({ row }) => (+ <span className="block max-w-60 truncate text-sm font-medium" title={row.original.key_alias ?? undefined}>+ {row.original.key_alias || "—"}+ </span>+ ),+ },+ {+ id: "owner",+ meta: { title: "Owner" },+ header: "Owner",+ enableSorting: false,+ cell: ({ row }) => <OwnerCell record={row.original} />,+ },+ {+ id: "created_at",+ accessorKey: "created_at",+ meta: { title: "Created" },+ header: "Created",+ size: 130,+ enableSorting: false,+ cell: ({ row }) => <DateCell value={row.original.created_at} precision="date" />,+ },+ {+ id: "last_active",+ accessorKey: "last_active",+ meta: { title: "Last Active" },+ header: "Last Active",+ size: 130,+ enableSorting: false,+ cell: ({ row }) => <DateCell value={row.original.last_active} precision="date" fallback="Never" />,+ },+];diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.test.tsxindex 73232baa03a..1c06b61698b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.test.tsx@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from "vitest";import userEvent from "@testing-library/user-event";-import { renderWithProviders, screen, waitFor } from "../../../../../tests/test-utils";+import { renderWithProviders, screen, waitFor, within } from "../../../../../tests/test-utils";import { ProjectsPage } from "./ProjectsPage";import { ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";@@ -141,7 +141,63 @@ describe("ProjectsPage", () => {it("should show the total project count in the pagination", () => {mockUseProjects.mockReturnValue({ data: mockProjects, isLoading: false });renderWithProviders(<ProjectsPage />);- expect(screen.getByText("2 projects")).toBeInTheDocument();+ expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-2 of 2");+ });++ it("should show skeleton rows while projects are loading", () => {+ mockUseProjects.mockReturnValue({ data: undefined, isLoading: true });+ renderWithProviders(<ProjectsPage />);+ expect(screen.getAllByTestId("skeleton-row").length).toBeGreaterThan(0);+ });++ it("should show the empty state when there are no projects", () => {+ mockUseProjects.mockReturnValue({ data: [], isLoading: false });+ renderWithProviders(<ProjectsPage />);+ expect(screen.getByText("No projects yet")).toBeInTheDocument();+ });++ it("should show the filtered empty state when a search matches nothing", async () => {+ const user = userEvent.setup();+ mockUseProjects.mockReturnValue({ data: mockProjects, isLoading: false });+ renderWithProviders(<ProjectsPage />);+ await user.type(screen.getByPlaceholderText(/search projects/i), "zzz-no-match");+ await waitFor(() => {+ expect(screen.getByText("No matching projects")).toBeInTheDocument();+ });+ });++ it("should sort by name when the Name header is clicked", async () => {+ const user = userEvent.setup();+ mockUseProjects.mockReturnValue({ data: mockProjects, isLoading: false });+ renderWithProviders(<ProjectsPage />);++ await user.click(screen.getByRole("button", { name: /^name$/i }));+ let rows = screen.getAllByRole("row").slice(1);+ expect(within(rows[0]).getByText("Alpha Project")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: /^name$/i }));+ rows = screen.getAllByRole("row").slice(1);+ expect(within(rows[0]).getByText("Beta Project")).toBeInTheDocument();+ });++ it("should reset to the first page when the search text changes", async () => {+ const user = userEvent.setup();+ const manyProjects = Array.from({ length: 12 }, (_, i) => ({+ ...mockProjects[0],+ project_id: `proj-${i + 1}`,+ project_alias: `Project ${String(i + 1).padStart(2, "0")}`,+ }));+ mockUseProjects.mockReturnValue({ data: manyProjects, isLoading: false });+ renderWithProviders(<ProjectsPage />);++ await user.click(screen.getByTestId("pagination-next"));+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 2 of 2");++ await user.type(screen.getByPlaceholderText(/search projects/i), "Project 01");+ await waitFor(() => {+ expect(screen.getByText("Project 01")).toBeInTheDocument();+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 1 of 1");+ });});it("should resolve team alias from the teams list in the Team column", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.tsxindex be989229022..58c2c4c3ad8 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsPage.tsx@@ -1,27 +1,12 @@-import { useProjects, ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";+import { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects";import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";-import { DateCell, IdCell } from "@/components/shared/table_cells";-import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";-import {- Button,- Card,- Flex,- Input,- Layout,- Pagination,- Space,- Spin,- Table,- Tag,- theme,- Tooltip,- Typography,-} from "antd";-import type { ColumnsType } from "antd/es/table";-import { LayersIcon, SearchIcon } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import { PlusOutlined } from "@ant-design/icons";+import { Button, Flex, Input, Layout, Space, theme, Typography } from "antd";+import { SearchIcon } from "lucide-react";+import { useMemo, useState } from "react";import { CreateProjectModal } from "./ProjectModals/CreateProjectModal";import { ProjectDetail } from "./ProjectDetailsPage";+import { ProjectsTable } from "./ProjectsTable";const { Title, Text } = Typography;const { Content } = Layout;@@ -34,14 +19,7 @@ export function ProjectsPage() {const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);const [searchText, setSearchText] = useState("");- const [currentPage, setCurrentPage] = useState(1);- const pageSize = 10;- useEffect(() => {- setCurrentPage(1);- }, [searchText]);-- // Build a team_id → team_alias lookup from the teams listconst teamAliasMap = useMemo(() => {const map = new Map<string, string>();for (const team of teams ?? []) {@@ -50,7 +28,6 @@ export function ProjectsPage() {return map;}, [teams]);- // ---------- filtered data ----------const filteredProjects = useMemo(() => {const list = projects ?? [];if (!searchText) return list;@@ -66,78 +43,6 @@ export function ProjectsPage() {});}, [projects, searchText, teamAliasMap]);- // ---------- Ant Design columns ----------- const columns: ColumnsType<ProjectResponse> = [- {- title: "ID",- dataIndex: "project_id",- key: "project_id",- width: 170,- render: (id: string) => <IdCell value={id} onClick={setSelectedProjectId} />,- },- {- title: "Name",- dataIndex: "project_alias",- key: "project_alias",- sorter: (a, b) => (a.project_alias ?? "").localeCompare(b.project_alias ?? ""),- render: (alias: string | null) => alias ?? "—",- },- {- title: "Team",- key: "team",- sorter: (a, b) => {- const aAlias = teamAliasMap.get(a.team_id ?? "") ?? "";- const bAlias = teamAliasMap.get(b.team_id ?? "") ?? "";- return aAlias.localeCompare(bAlias);- },- render: (_: unknown, record: ProjectResponse) => {- if (!record.team_id) return "—";- const alias = teamAliasMap.get(record.team_id);- if (alias) return alias;- if (isTeamsLoading) return <Spin indicator={<LoadingOutlined spin />} size="small" />;- return record.team_id;- },- },- {- title: "Models",- key: "models",- render: (_: unknown, record: ProjectResponse) => {- const models = record.models ?? [];- return (- <Tooltip title={models.length > 0 ? models.join(", ") : "No models"}>- <Tag color="blue" style={{ fontSize: 14, padding: "2px 8px", margin: 0 }}>- <Flex align="center" gap={6}>- <LayersIcon size={14} />- {models.length}- </Flex>- </Tag>- </Tooltip>- );- },- },- {- title: "Status",- dataIndex: "blocked",- key: "status",- render: (blocked: boolean) => <Tag color={blocked ? "red" : "green"}>{blocked ? "Blocked" : "Active"}</Tag>,- },- {- title: "Created",- dataIndex: "created_at",- key: "created_at",- sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),- responsive: ["lg"],- render: (date: string) => <DateCell value={date} precision="date" />,- },- {- title: "Updated",- dataIndex: "updated_at",- key: "updated_at",- responsive: ["xl"],- render: (date: string) => <DateCell value={date} precision="date" />,- },- ];-if (selectedProjectId) {return <ProjectDetail projectId={selectedProjectId} onBack={() => setSelectedProjectId(null)} />;}@@ -156,34 +61,25 @@ export function ProjectsPage() {</Button></Flex>- <Card styles={{ body: { padding: 0 } }}>- <Flex justify="space-between" align="center" style={{ padding: "12px 16px" }}>- <Input- prefix={<SearchIcon size={16} />}- placeholder="Search projects by name, ID, description, or team..."- style={{ maxWidth: 400 }}- value={searchText}- onChange={(e) => setSearchText(e.target.value)}- allowClear- />- <Pagination- current={currentPage}- total={filteredProjects.length}- pageSize={pageSize}- onChange={(page) => setCurrentPage(page)}- size="small"- showTotal={(total) => `${total} projects`}- showSizeChanger={false}- />- </Flex>- <Table- columns={columns}- dataSource={filteredProjects.slice((currentPage - 1) * pageSize, currentPage * pageSize)}- rowKey="project_id"- loading={isLoading}- pagination={false}+ <Flex align="center" style={{ marginBottom: 12 }}>+ <Input+ prefix={<SearchIcon size={16} />}+ placeholder="Search projects by name, ID, description, or team..."+ style={{ maxWidth: 400 }}+ value={searchText}+ onChange={(e) => setSearchText(e.target.value)}+ allowClear/>- </Card>+ </Flex>++ <ProjectsTable+ projects={filteredProjects}+ isLoading={isLoading}+ isFiltered={searchText.trim().length > 0}+ onProjectClick={setSelectedProjectId}+ teamAliasMap={teamAliasMap}+ isTeamsLoading={isTeamsLoading}+ /><CreateProjectModal isOpen={isCreateModalVisible} onClose={() => setIsCreateModalVisible(false)} /></Content>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTable.tsxnew file mode 100644index 00000000000..ad85019ca6d--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTable.tsx@@ -0,0 +1,70 @@+"use client";++import { SortingState } from "@tanstack/react-table";+import { FolderKanban } from "lucide-react";+import { useMemo, useState } from "react";++import { ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";+import { DataTable } from "@/components/shared/DataTable";++import { getProjectsTableColumns } from "./ProjectsTableColumns";++interface ProjectsTableProps {+ projects: ProjectResponse[];+ isLoading: boolean;+ isFiltered: boolean;+ onProjectClick: (projectId: string) => void;+ teamAliasMap: Map<string, string>;+ isTeamsLoading: boolean;+}++const PAGE_SIZE_OPTIONS = [10, 25, 50];++function EmptyState({ isFiltered }: { isFiltered: boolean }) {+ return (+ <div className="flex flex-col items-center gap-1 py-6">+ <div className="mb-1 flex size-10 items-center justify-center rounded-lg bg-muted">+ <FolderKanban className="size-5 text-muted-foreground" />+ </div>+ <div className="text-sm font-medium text-foreground">+ {isFiltered ? "No matching projects" : "No projects yet"}+ </div>+ <div className="text-sm text-muted-foreground">+ {isFiltered ? "Try a different search term." : "Create a project to organize keys within your teams."}+ </div>+ </div>+ );+}++export function ProjectsTable({+ projects,+ isLoading,+ isFiltered,+ onProjectClick,+ teamAliasMap,+ isTeamsLoading,+}: ProjectsTableProps) {+ const [sorting, setSorting] = useState<SortingState>([]);++ const columns = useMemo(() => {+ const deps = { onProjectClick, teamAliasMap, isTeamsLoading };+ return getProjectsTableColumns(deps);+ }, [onProjectClick, teamAliasMap, isTeamsLoading]);++ return (+ <DataTable+ data={projects}+ columns={columns}+ getRowId={(project, index) => project.project_id || String(index)}+ sortingMode="client"+ sorting={sorting}+ onSortingChange={setSorting}+ paginationMode="client"+ pageSizeOptions={PAGE_SIZE_OPTIONS}+ isLoading={isLoading}+ loadingMessage="Loading projects…"+ noDataMessage={<EmptyState isFiltered={isFiltered} />}+ size="compact"+ />+ );+}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTableColumns.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTableColumns.tsxnew file mode 100644index 00000000000..46fe259aed2--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectsTableColumns.tsx@@ -0,0 +1,144 @@+"use client";++import { ColumnDef } from "@tanstack/react-table";+import { LayersIcon } from "lucide-react";++import { ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";+import { DataTableSortHeader } from "@/components/shared/DataTable";+import { CellTooltip, DateCell, IdentityCell, StatusBadge } from "@/components/shared/table_cells";+import { Badge } from "@/components/ui/badge";+import { Skeleton } from "@/components/ui/skeleton";++function ProjectTeamCell({+ project,+ teamAliasMap,+ isTeamsLoading,+}: {+ project: ProjectResponse;+ teamAliasMap: Map<string, string>;+ isTeamsLoading: boolean;+}) {+ if (!project.team_id) return <span className="text-sm">—</span>;+ const alias = teamAliasMap.get(project.team_id);+ if (alias) {+ return (+ <span className="block max-w-60 truncate text-sm" title={alias}>+ {alias}+ </span>+ );+ }+ if (isTeamsLoading) return <Skeleton className="h-3.5 w-24" />;+ return (+ <span className="block max-w-60 truncate font-mono text-xs" title={project.team_id}>+ {project.team_id}+ </span>+ );+}++function ProjectModelsCell({ project }: { project: ProjectResponse }) {+ const models = project.models ?? [];+ return (+ <CellTooltip+ content={models.length > 0 ? models.join(", ") : "No models"}+ trigger={+ <Badge variant="outline" className="cursor-default gap-1.5 font-normal">+ <LayersIcon className="size-3.5" />+ {models.length}+ </Badge>+ }+ />+ );+}++interface ProjectsTableColumnsDeps {+ onProjectClick: (projectId: string) => void;+ teamAliasMap: Map<string, string>;+ isTeamsLoading: boolean;+}++export const getProjectsTableColumns = ({+ onProjectClick,+ teamAliasMap,+ isTeamsLoading,+}: ProjectsTableColumnsDeps): ColumnDef<ProjectResponse>[] => [+ {+ id: "project_id",+ accessorKey: "project_id",+ meta: { title: "ID" },+ header: "ID",+ size: 190,+ enableSorting: false,+ cell: ({ row }) => (+ <IdentityCell+ title={row.original.project_id}+ titleClassName="font-mono text-xs font-normal"+ onClick={() => onProjectClick(row.original.project_id)}+ />+ ),+ },+ {+ id: "project_alias",+ accessorFn: (row) => row.project_alias ?? "",+ meta: { title: "Name" },+ header: ({ column }) => <DataTableSortHeader column={column} title="Name" />,+ size: 200,+ enableSorting: true,+ cell: ({ row }) => (+ <span className="block max-w-60 truncate text-sm font-medium" title={row.original.project_alias ?? undefined}>+ {row.original.project_alias ?? "—"}+ </span>+ ),+ },+ {+ id: "team",+ accessorFn: (row) => teamAliasMap.get(row.team_id ?? "") ?? "",+ meta: { title: "Team" },+ header: ({ column }) => <DataTableSortHeader column={column} title="Team" />,+ size: 180,+ enableSorting: true,+ cell: ({ row }) => (+ <ProjectTeamCell project={row.original} teamAliasMap={teamAliasMap} isTeamsLoading={isTeamsLoading} />+ ),+ },+ {+ id: "models",+ meta: { title: "Models", skeleton: "badge" },+ header: "Models",+ size: 110,+ enableSorting: false,+ cell: ({ row }) => <ProjectModelsCell project={row.original} />,+ },+ {+ id: "status",+ accessorKey: "blocked",+ meta: { title: "Status", skeleton: "badge" },+ header: "Status",+ size: 110,+ enableSorting: false,+ cell: ({ row }) => (+ <StatusBadge+ tone={row.original.blocked ? "error" : "success"}+ label={row.original.blocked ? "Blocked" : "Active"}+ />+ ),+ },+ {+ id: "created_at",+ accessorKey: "created_at",+ sortingFn: "datetime",+ meta: { title: "Created" },+ header: ({ column }) => <DataTableSortHeader column={column} title="Created" />,+ size: 140,+ enableSorting: true,+ cell: ({ row }) => <DateCell value={row.original.created_at} precision="date" />,+ },+ {+ id: "updated_at",+ accessorKey: "updated_at",+ meta: { title: "Updated" },+ header: "Updated",+ size: 140,+ enableSorting: false,+ cell: ({ row }) => <DateCell value={row.original.updated_at} precision="date" />,+ },+];diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.test.tsxindex c2425c8d651..bbeef5c2216 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.test.tsx@@ -1,18 +1,10 @@-import { render, screen, fireEvent, act } from "@testing-library/react";-import { describe, it, expect, vi } from "vitest";-import DocumentsTable from "./DocumentsTable";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { DocumentUpload } from "@/components/vector_store_management/types";-// Mock antd message-vi.mock("antd", async () => {- const actual = await vi.importActual("antd");- return {- ...actual,- message: {- success: vi.fn(),- },- };-});+import DocumentsTable from "./DocumentsTable";describe("DocumentsTable", () => {const mockDocuments: DocumentUpload[] = [@@ -39,9 +31,12 @@ describe("DocumentsTable", () => {},];- it("should render the table successfully", () => {- const onRemove = vi.fn();- render(<DocumentsTable documents={mockDocuments} onRemove={onRemove} />);+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("should render every document row", () => {+ render(<DocumentsTable documents={mockDocuments} onRemove={vi.fn()} />);expect(screen.getByText("test1.pdf")).toBeInTheDocument();expect(screen.getByText("test2.txt")).toBeInTheDocument();@@ -49,8 +44,7 @@ describe("DocumentsTable", () => {});it("should display correct status badges", () => {- const onRemove = vi.fn();- render(<DocumentsTable documents={mockDocuments} onRemove={onRemove} />);+ render(<DocumentsTable documents={mockDocuments} onRemove={vi.fn()} />);expect(screen.getByText("Ready")).toBeInTheDocument();expect(screen.getByText("Uploading")).toBeInTheDocument();@@ -58,45 +52,46 @@ describe("DocumentsTable", () => {});it("should display file sizes", () => {- const onRemove = vi.fn();- render(<DocumentsTable documents={mockDocuments} onRemove={onRemove} />);+ render(<DocumentsTable documents={mockDocuments} onRemove={vi.fn()} />);expect(screen.getByText(/1000.00 KB/)).toBeInTheDocument();expect(screen.getByText(/1.95 MB/)).toBeInTheDocument();expect(screen.getByText(/500.00 KB/)).toBeInTheDocument();});- it("should call onRemove when delete button is clicked", () => {+ it("should call onRemove through the actions menu", async () => {+ const user = userEvent.setup();const onRemove = vi.fn();render(<DocumentsTable documents={mockDocuments} onRemove={onRemove} />);- const deleteButtons = screen.getAllByLabelText(/delete/i);-- act(() => {- fireEvent.click(deleteButtons[0]);- });+ await user.click(screen.getByTestId("document-actions-1"));+ await user.click(await screen.findByTestId("document-action-remove"));expect(onRemove).toHaveBeenCalledWith("1");});- it("should show empty state when no documents", () => {- const onRemove = vi.fn();- render(<DocumentsTable documents={[]} onRemove={onRemove} />);+ it("should copy the document ID through the actions menu", async () => {+ const user = userEvent.setup();+ render(<DocumentsTable documents={mockDocuments} onRemove={vi.fn()} />);- expect(screen.getByText(/No documents uploaded yet/)).toBeInTheDocument();+ await user.click(screen.getByTestId("document-actions-2"));+ await user.click(await screen.findByTestId("document-action-copy"));++ expect(await window.navigator.clipboard.readText()).toBe("2");});- it("should have action buttons for each document", () => {- const onRemove = vi.fn();- render(<DocumentsTable documents={mockDocuments} onRemove={onRemove} />);+ it("should show the empty state when no documents", () => {+ render(<DocumentsTable documents={[]} onRemove={vi.fn()} />);++ expect(screen.getByText("No documents uploaded yet")).toBeInTheDocument();+ expect(screen.getByText("Upload documents above to get started.")).toBeInTheDocument();+ });- // Each document should have 3 action buttons (view, copy, delete)- const viewButtons = screen.getAllByLabelText(/eye/i);- const copyButtons = screen.getAllByLabelText(/copy/i);- const deleteButtons = screen.getAllByLabelText(/delete/i);+ it("should render one actions menu per document", () => {+ render(<DocumentsTable documents={mockDocuments} onRemove={vi.fn()} />);- expect(viewButtons).toHaveLength(3);- expect(copyButtons).toHaveLength(3);- expect(deleteButtons).toHaveLength(3);+ for (const doc of mockDocuments) {+ expect(screen.getByTestId(`document-actions-${doc.uid}`)).toBeInTheDocument();+ }});});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.tsxindex d4c45a6b751..416fcb37a10 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTable.tsx@@ -1,95 +1,40 @@-import React from "react";-import { Table, Tooltip } from "antd";-import MessageManager from "@/components/molecules/message_manager";-import { EyeOutlined, CopyOutlined, DeleteOutlined } from "@ant-design/icons";-import { StatusBadge, type StatusTone } from "@/components/shared/table_cells";+"use client";++import { Inbox } from "lucide-react";+import React, { useMemo } from "react";++import { DataTable } from "@/components/shared/DataTable";import { DocumentUpload } from "@/components/vector_store_management/types";+import { getDocumentsTableColumns } from "./DocumentsTableColumns";+interface DocumentsTableProps {documents: DocumentUpload[];onRemove: (uid: string) => void;}-const DocumentsTable: React.FC<DocumentsTableProps> = ({ documents, onRemove }) => {- const handleCopyId = (uid: string) => {- navigator.clipboard.writeText(uid);- MessageManager.success("Document ID copied to clipboard");- };-- const getStatusBadge = (status: DocumentUpload["status"]) => {- const statusConfig: Record<DocumentUpload["status"], { tone: StatusTone; label: string }> = {- uploading: { tone: "info", label: "Uploading" },- done: { tone: "success", label: "Ready" },- error: { tone: "error", label: "Error" },- removed: { tone: "neutral", label: "Removed" },- };-- const config: { tone: StatusTone; label: string } = statusConfig[status] ?? { tone: "neutral", label: status };- return <StatusBadge tone={config.tone} label={config.label} />;- };-- const formatFileSize = (bytes?: number) => {- if (!bytes) return "-";- const kb = bytes / 1024;- if (kb < 1024) return `${kb.toFixed(2)} KB`;- return `${(kb / 1024).toFixed(2)} MB`;- };+function EmptyState() {+ return (+ <div className="flex flex-col items-center gap-1 py-6">+ <div className="mb-1 flex size-10 items-center justify-center rounded-lg bg-muted">+ <Inbox className="size-5 text-muted-foreground" />+ </div>+ <div className="text-sm font-medium text-foreground">No documents uploaded yet</div>+ <div className="text-sm text-muted-foreground">Upload documents above to get started.</div>+ </div>+ );+}- const columns = [- {- title: "Name",- dataIndex: "name",- key: "name",- render: (name: string, record: DocumentUpload) => (- <div className="flex items-center space-x-2">- <span className="text-sm">{name}</span>- {record.size && <span className="text-xs text-gray-400">({formatFileSize(record.size)})</span>}- </div>- ),- },- {- title: "Status",- dataIndex: "status",- key: "status",- width: 150,- render: (status: DocumentUpload["status"]) => getStatusBadge(status),- },- {- title: "Actions",- key: "actions",- width: 120,- render: (_: any, record: DocumentUpload) => (- <div className="flex items-center space-x-2">- <Tooltip title="View details">- <EyeOutlined className="cursor-pointer text-gray-600 hover:text-blue-500" onClick={() => {}} />- </Tooltip>- <Tooltip title="Copy ID">- <CopyOutlined- className="cursor-pointer text-gray-600 hover:text-blue-500"- onClick={() => handleCopyId(record.uid)}- />- </Tooltip>- <Tooltip title="Remove">- <DeleteOutlined- className="cursor-pointer text-gray-600 hover:text-red-500"- onClick={() => onRemove(record.uid)}- />- </Tooltip>- </div>- ),- },- ];+const DocumentsTable: React.FC<DocumentsTableProps> = ({ documents, onRemove }) => {+ const columns = useMemo(() => getDocumentsTableColumns({ onRemove }), [onRemove]);return (- <Table- dataSource={documents}+ <DataTable+ data={documents}columns={columns}- rowKey="uid"- pagination={false}- locale={{- emptyText: "No documents uploaded yet. Upload documents above to get started.",- }}- size="small"+ getRowId={(document, index) => document.uid || String(index)}+ noDataMessage={<EmptyState />}+ size="compact"/>);};diff --git a/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTableColumns.tsx b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTableColumns.tsxnew file mode 100644index 00000000000..9be9f806bf9--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/vector-stores/_components/DocumentsTableColumns.tsx@@ -0,0 +1,110 @@+"use client";++import { ColumnDef } from "@tanstack/react-table";+import { Copy, MoreHorizontal, Trash2 } from "lucide-react";++import { StatusBadge, type StatusTone } from "@/components/shared/table_cells";+import { buttonVariants } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { DocumentUpload } from "@/components/vector_store_management/types";+import { cn } from "@/lib/cva.config";+import { copyToClipboard } from "@/utils/dataUtils";++const STATUS_CONFIG: Record<DocumentUpload["status"], { tone: StatusTone; label: string }> = {+ uploading: { tone: "info", label: "Uploading" },+ done: { tone: "success", label: "Ready" },+ error: { tone: "error", label: "Error" },+ removed: { tone: "neutral", label: "Removed" },+};++function formatFileSize(bytes?: number): string {+ if (!bytes) return "-";+ const kb = bytes / 1024;+ if (kb < 1024) return `${kb.toFixed(2)} KB`;+ return `${(kb / 1024).toFixed(2)} MB`;+}++function DocumentRowActions({ document, onRemove }: { document: DocumentUpload; onRemove: (uid: string) => void }) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label="Open document actions"+ data-testid={`document-actions-${document.uid}`}+ className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }), "text-muted-foreground")}+ >+ <MoreHorizontal className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem+ data-testid="document-action-copy"+ onClick={() => void copyToClipboard(document.uid, "Document ID copied to clipboard")}+ >+ <Copy />+ Copy document ID+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ data-testid="document-action-remove"+ onClick={() => onRemove(document.uid)}+ >+ <Trash2 />+ Remove+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++interface DocumentsTableColumnsDeps {+ onRemove: (uid: string) => void;+}++export const getDocumentsTableColumns = ({ onRemove }: DocumentsTableColumnsDeps): ColumnDef<DocumentUpload>[] => [+ {+ id: "name",+ accessorKey: "name",+ meta: { title: "Name" },+ header: "Name",+ enableSorting: false,+ cell: ({ row }) => (+ <div className="flex items-center gap-2">+ <span className="block max-w-72 truncate text-sm" title={row.original.name}>+ {row.original.name}+ </span>+ {row.original.size ? (+ <span className="text-xs text-muted-foreground">({formatFileSize(row.original.size)})</span>+ ) : null}+ </div>+ ),+ },+ {+ id: "status",+ accessorKey: "status",+ meta: { title: "Status", skeleton: "badge" },+ header: "Status",+ size: 150,+ enableSorting: false,+ cell: ({ row }) => {+ const config = STATUS_CONFIG[row.original.status] ?? { tone: "neutral", label: row.original.status };+ return <StatusBadge tone={config.tone} label={config.label} />;+ },+ },+ {+ id: "actions",+ meta: { className: "text-right", headerClassName: "text-right" },+ header: () => <span className="sr-only">Actions</span>,+ size: 64,+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => (+ <div className="flex justify-end">+ <DocumentRowActions document={row.original} onRemove={onRemove} />+ </div>+ ),+ },+];diff --git a/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.test.tsx b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.test.tsxnew file mode 100644index 00000000000..040fa463f9c--- /dev/null+++ b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.test.tsx@@ -0,0 +1,130 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { PassThroughEndpointsTable } from "./PassThroughEndpointsTable";+import type { passThroughItem } from "./PassThroughSettings";++const endpoints: passThroughItem[] = [+ {+ id: "ep-1",+ path: "/v1/rerank",+ target: "https://api.cohere.com/v1/rerank",+ headers: { Authorization: "Bearer secret-value" },+ auth: true,+ methods: ["POST"],+ },+ {+ id: "ep-2",+ path: "/bria",+ target: "https://engine.prod.bria-api.com",+ headers: {},+ auth: false,+ },+];++const defaultProps = {+ endpoints,+ isLoading: false,+ onEndpointClick: vi.fn(),+ onDeleteClick: vi.fn(),+};++describe("PassThroughEndpointsTable", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("should render a row per endpoint with path and target", () => {+ render(<PassThroughEndpointsTable {...defaultProps} />);+ expect(screen.getByText("/v1/rerank")).toBeInTheDocument();+ expect(screen.getByText("https://api.cohere.com/v1/rerank")).toBeInTheDocument();+ expect(screen.getByText("/bria")).toBeInTheDocument();+ });++ it("should open the endpoint when its ID is clicked", async () => {+ const user = userEvent.setup();+ const onEndpointClick = vi.fn();+ render(<PassThroughEndpointsTable {...defaultProps} onEndpointClick={onEndpointClick} />);+ await user.click(screen.getByRole("button", { name: "ep-1" }));+ expect(onEndpointClick).toHaveBeenCalledWith("ep-1");+ });++ it("should show method chips, or ALL when no methods are set", () => {+ render(<PassThroughEndpointsTable {...defaultProps} />);+ expect(screen.getByText("POST")).toBeInTheDocument();+ expect(screen.getByText("ALL")).toBeInTheDocument();+ });++ it("should show authentication as Yes or No", () => {+ render(<PassThroughEndpointsTable {...defaultProps} />);+ expect(screen.getByText("Yes")).toBeInTheDocument();+ expect(screen.getByText("No")).toBeInTheDocument();+ });++ it("should mask headers until the visibility toggle is clicked", async () => {+ const user = userEvent.setup();+ render(<PassThroughEndpointsTable {...defaultProps} />);++ expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();+ const toggles = screen.getAllByRole("button", { name: "Show headers" });+ await user.click(toggles[0]);+ expect(screen.getByText(/secret-value/)).toBeInTheDocument();+ });++ it("should edit and delete an endpoint through the actions menu", async () => {+ const user = userEvent.setup();+ const onEndpointClick = vi.fn();+ const onDeleteClick = vi.fn();+ render(+ <PassThroughEndpointsTable {...defaultProps} onEndpointClick={onEndpointClick} onDeleteClick={onDeleteClick} />,+ );++ await user.click(screen.getByTestId("endpoint-actions-ep-1"));+ await user.click(await screen.findByTestId("endpoint-action-edit"));+ expect(onEndpointClick).toHaveBeenCalledWith("ep-1");++ await user.click(screen.getByTestId("endpoint-actions-ep-1"));+ await user.click(await screen.findByTestId("endpoint-action-delete"));+ expect(onDeleteClick).toHaveBeenCalledWith("ep-1");+ });++ it("should disable edit and delete for endpoints without an id", async () => {+ const user = userEvent.setup();+ const onEndpointClick = vi.fn();+ const onDeleteClick = vi.fn();+ const endpointWithoutId: passThroughItem = { path: "/legacy", target: "https://legacy.example.com", headers: {} };+ render(+ <PassThroughEndpointsTable+ {...defaultProps}+ endpoints={[endpointWithoutId]}+ onEndpointClick={onEndpointClick}+ onDeleteClick={onDeleteClick}+ />,+ );++ await user.click(screen.getByTestId("endpoint-actions-/legacy"));+ const editItem = await screen.findByTestId("endpoint-action-edit");+ const deleteItem = await screen.findByTestId("endpoint-action-delete");++ expect(editItem).toHaveAttribute("data-disabled");+ expect(deleteItem).toHaveAttribute("data-disabled");++ await user.click(editItem);+ await user.click(deleteItem);++ expect(onEndpointClick).not.toHaveBeenCalled();+ expect(onDeleteClick).not.toHaveBeenCalled();+ });++ it("should show the empty state when there are no endpoints", () => {+ render(<PassThroughEndpointsTable {...defaultProps} endpoints={[]} />);+ expect(screen.getByText("No pass-through endpoints configured")).toBeInTheDocument();+ });++ it("should show skeleton rows while loading", () => {+ render(<PassThroughEndpointsTable {...defaultProps} endpoints={[]} isLoading />);+ expect(screen.getAllByTestId("skeleton-row").length).toBeGreaterThan(0);+ expect(screen.queryByText("No pass-through endpoints configured")).not.toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.tsx b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.tsxnew file mode 100644index 00000000000..754e7ff68dd--- /dev/null+++ b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTable.tsx@@ -0,0 +1,52 @@+"use client";++import { Waypoints } from "lucide-react";+import { useMemo } from "react";++import { DataTable } from "@/components/shared/DataTable";++import { getPassThroughEndpointsTableColumns } from "./PassThroughEndpointsTableColumns";+import type { passThroughItem } from "./PassThroughSettings";++interface PassThroughEndpointsTableProps {+ endpoints: passThroughItem[];+ isLoading: boolean;+ onEndpointClick: (endpointId: string) => void;+ onDeleteClick: (endpointId: string) => void;+}++function EmptyState() {+ return (+ <div className="flex flex-col items-center gap-1 py-6">+ <div className="mb-1 flex size-10 items-center justify-center rounded-lg bg-muted">+ <Waypoints className="size-5 text-muted-foreground" />+ </div>+ <div className="text-sm font-medium text-foreground">No pass-through endpoints configured</div>+ <div className="text-sm text-muted-foreground">Add a pass-through endpoint to route custom paths.</div>+ </div>+ );+}++export function PassThroughEndpointsTable({+ endpoints,+ isLoading,+ onEndpointClick,+ onDeleteClick,+}: PassThroughEndpointsTableProps) {+ const columns = useMemo(+ () => getPassThroughEndpointsTableColumns({ onEndpointClick, onDeleteClick }),+ [onEndpointClick, onDeleteClick],+ );++ return (+ <DataTable+ data={endpoints}+ columns={columns}+ getRowId={(endpoint, index) => endpoint.id || endpoint.path || String(index)}+ isLoading={isLoading}+ loadingMessage="Loading pass-through endpoints…"+ noDataMessage={<EmptyState />}+ size="compact"+ />+ );+}diff --git a/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTableColumns.tsx b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTableColumns.tsxnew file mode 100644index 00000000000..d22b274861a--- /dev/null+++ b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughEndpointsTableColumns.tsx@@ -0,0 +1,203 @@+"use client";++import { ColumnDef } from "@tanstack/react-table";+import { Eye, EyeOff, Info, MoreHorizontal, Pencil, Trash2 } from "lucide-react";+import React, { useState } from "react";++import { CellTooltip, IdentityCell, StatusBadge } from "@/components/shared/table_cells";+import { Badge } from "@/components/ui/badge";+import { buttonVariants } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { cn } from "@/lib/cva.config";++import type { passThroughItem } from "./PassThroughSettings";++function HeaderWithTooltip({ title, tooltip }: { title: string; tooltip: string }) {+ return (+ <div className="flex items-center gap-1">+ <span>{title}</span>+ <CellTooltip content={tooltip} trigger={<Info className="size-3.5 cursor-help text-muted-foreground" />} />+ </div>+ );+}++function HeadersCell({ value }: { value: object }) {+ const [showHeaders, setShowHeaders] = useState(false);+ const headerString = JSON.stringify(value);++ return (+ <div className="flex items-center gap-2">+ <span className="block max-w-60 truncate font-mono text-xs">{showHeaders ? headerString : "••••••••"}</span>+ <button+ type="button"+ onClick={() => setShowHeaders(!showHeaders)}+ aria-label={showHeaders ? "Hide headers" : "Show headers"}+ className="rounded-sm p-1 hover:bg-muted"+ >+ {showHeaders ? (+ <EyeOff className="size-4 text-muted-foreground" />+ ) : (+ <Eye className="size-4 text-muted-foreground" />+ )}+ </button>+ </div>+ );+}++function MethodsCell({ methods }: { methods: string[] | undefined }) {+ if (!methods || methods.length === 0) {+ return <Badge variant="secondary">ALL</Badge>;+ }+ return (+ <div className="flex flex-wrap gap-1">+ {methods.map((method) => (+ <Badge key={method} variant="outline" className="font-mono text-xs font-normal">+ {method}+ </Badge>+ ))}+ </div>+ );+}++interface EndpointRowActionsProps {+ endpoint: passThroughItem;+ onEndpointClick: (endpointId: string) => void;+ onDeleteClick: (endpointId: string) => void;+}++function EndpointRowActions({ endpoint, onEndpointClick, onDeleteClick }: EndpointRowActionsProps) {+ const endpointId = endpoint.id;+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label="Open endpoint actions"+ data-testid={`endpoint-actions-${endpointId || endpoint.path}`}+ className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }), "text-muted-foreground")}+ >+ <MoreHorizontal className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem+ data-testid="endpoint-action-edit"+ disabled={!endpointId}+ onClick={() => endpointId && onEndpointClick(endpointId)}+ >+ <Pencil />+ Edit+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ data-testid="endpoint-action-delete"+ disabled={!endpointId}+ onClick={() => endpointId && onDeleteClick(endpointId)}+ >+ <Trash2 />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++interface PassThroughEndpointsTableColumnsDeps {+ onEndpointClick: (endpointId: string) => void;+ onDeleteClick: (endpointId: string) => void;+}++export const getPassThroughEndpointsTableColumns = ({+ onEndpointClick,+ onDeleteClick,+}: PassThroughEndpointsTableColumnsDeps): ColumnDef<passThroughItem>[] => [+ {+ id: "id",+ accessorKey: "id",+ meta: { title: "ID" },+ header: "ID",+ size: 190,+ enableSorting: false,+ cell: ({ row }) => {+ const endpointId = row.original.id;+ if (!endpointId) return <span className="font-mono text-xs text-muted-foreground">—</span>;+ return (+ <IdentityCell+ title={endpointId}+ titleClassName="font-mono text-xs font-normal"+ onClick={() => onEndpointClick(endpointId)}+ />+ );+ },+ },+ {+ id: "path",+ accessorKey: "path",+ meta: { title: "Path" },+ header: "Path",+ size: 200,+ enableSorting: false,+ cell: ({ row }) => (+ <span className="block max-w-60 truncate text-sm font-medium" title={row.original.path}>+ {row.original.path}+ </span>+ ),+ },+ {+ id: "target",+ accessorKey: "target",+ meta: { title: "Target" },+ header: "Target",+ size: 240,+ enableSorting: false,+ cell: ({ row }) => (+ <span className="block max-w-72 truncate text-sm" title={row.original.target}>+ {row.original.target}+ </span>+ ),+ },+ {+ id: "methods",+ meta: { title: "Methods", skeleton: "chips" },+ header: () => <HeaderWithTooltip title="Methods" tooltip="HTTP methods supported by this endpoint" />,+ size: 150,+ enableSorting: false,+ cell: ({ row }) => <MethodsCell methods={row.original.methods} />,+ },+ {+ id: "auth",+ accessorKey: "auth",+ meta: { title: "Authentication", skeleton: "badge" },+ header: () => <HeaderWithTooltip title="Authentication" tooltip="LiteLLM Virtual Key required to call endpoint" />,+ size: 140,+ enableSorting: false,+ cell: ({ row }) => (+ <StatusBadge tone={row.original.auth ? "success" : "neutral"} label={row.original.auth ? "Yes" : "No"} />+ ),+ },+ {+ id: "headers",+ meta: { title: "Headers" },+ header: "Headers",+ size: 180,+ enableSorting: false,+ cell: ({ row }) => <HeadersCell value={row.original.headers || {}} />,+ },+ {+ id: "actions",+ meta: { className: "text-right", headerClassName: "text-right" },+ header: () => <span className="sr-only">Actions</span>,+ size: 64,+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => (+ <div className="flex justify-end">+ <EndpointRowActions endpoint={row.original} onEndpointClick={onEndpointClick} onDeleteClick={onDeleteClick} />+ </div>+ ),+ },+];diff --git a/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.test.tsx b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.test.tsxnew file mode 100644index 00000000000..90269a916f7--- /dev/null+++ b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.test.tsx@@ -0,0 +1,120 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { deletePassThroughEndpointsCall, getPassThroughEndpointsCall } from "../networking";+import PassThroughSettings from "./PassThroughSettings";+import type { PassThroughEndpointsTable } from "./PassThroughEndpointsTable";++vi.mock("../networking", () => ({+ getPassThroughEndpointsCall: vi.fn(),+ deletePassThroughEndpointsCall: vi.fn(),+}));++vi.mock("../add_pass_through", () => ({+ default: () => <div data-testid="add-pass-through" />,+}));++vi.mock("../pass_through_info", () => ({+ default: ({ endpointData }: { endpointData: { id?: string } }) => (+ <div data-testid="endpoint-info">{endpointData.id}</div>+ ),+}));++vi.mock("../molecules/notifications_manager", () => ({+ __esModule: true,+ default: { success: vi.fn(), fromBackend: vi.fn() },+}));++vi.mock("./PassThroughEndpointsTable", () => ({+ PassThroughEndpointsTable: (props: React.ComponentProps<typeof PassThroughEndpointsTable>) => (+ <div data-testid="endpoints-table" data-loading={props.isLoading}>+ {props.endpoints.map((endpoint) => (+ <div key={endpoint.id}>+ <button type="button" onClick={() => endpoint.id && props.onEndpointClick(endpoint.id)}>+ open-{endpoint.id}+ </button>+ <button type="button" onClick={() => endpoint.id && props.onDeleteClick(endpoint.id)}>+ delete-{endpoint.id}+ </button>+ </div>+ ))}+ </div>+ ),+}));++const mockGetEndpoints = vi.mocked(getPassThroughEndpointsCall);+const mockDeleteEndpoint = vi.mocked(deletePassThroughEndpointsCall);++const defaultProps = {+ accessToken: "token",+ userRole: "Admin",+ userID: "user-1",+ premiumUser: false,+};++const endpoint = { id: "ep-1", path: "/v1/rerank", target: "https://example.com", headers: {} };++describe("PassThroughSettings", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetEndpoints.mockResolvedValue({ endpoints: [endpoint] });+ });++ it("should render nothing without an access token", () => {+ const { container } = render(<PassThroughSettings {...defaultProps} accessToken={null} />);+ expect(container).toBeEmptyDOMElement();+ });++ it("should hold the table in loading state until the fetch settles", async () => {+ let resolveEndpoints: (value: { endpoints: (typeof endpoint)[] }) => void = () => {};+ mockGetEndpoints.mockReturnValue(+ new Promise((resolve) => {+ resolveEndpoints = resolve;+ }),+ );++ render(<PassThroughSettings {...defaultProps} />);+ expect(screen.getByTestId("endpoints-table")).toHaveAttribute("data-loading", "true");++ await act(async () => {+ resolveEndpoints({ endpoints: [endpoint] });+ });++ await waitFor(() => {+ expect(screen.getByTestId("endpoints-table")).toHaveAttribute("data-loading", "false");+ });+ });++ it("should resolve loading without fetching when the user id is missing", async () => {+ render(<PassThroughSettings {...defaultProps} userID={null} />);++ await waitFor(() => {+ expect(screen.getByTestId("endpoints-table")).toHaveAttribute("data-loading", "false");+ });+ expect(mockGetEndpoints).not.toHaveBeenCalled();+ });++ it("should swap to the endpoint info view when an endpoint is opened", async () => {+ const user = userEvent.setup();+ render(<PassThroughSettings {...defaultProps} />);++ await user.click(await screen.findByText("open-ep-1"));+ expect(screen.getByTestId("endpoint-info")).toHaveTextContent("ep-1");+ });++ it("should confirm before deleting an endpoint", async () => {+ const user = userEvent.setup();+ mockDeleteEndpoint.mockResolvedValue(undefined);+ render(<PassThroughSettings {...defaultProps} />);++ await user.click(await screen.findByText("delete-ep-1"));+ expect(screen.getByText("Delete Pass-Through Endpoint")).toBeInTheDocument();+ expect(mockDeleteEndpoint).not.toHaveBeenCalled();++ await user.click(screen.getByRole("button", { name: "Delete" }));+ await waitFor(() => {+ expect(mockDeleteEndpoint).toHaveBeenCalledWith("token", "ep-1");+ });+ });+});diff --git a/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.tsx b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.tsxnew file mode 100644index 00000000000..975ba0b70e1--- /dev/null+++ b/ui/litellm-dashboard/src/components/PassThroughSettings/PassThroughSettings.tsx@@ -0,0 +1,176 @@+import React, { useState, useEffect } from "react";+import { Button } from "@/components/ui/button";+import { deletePassThroughEndpointsCall, getPassThroughEndpointsCall } from "../networking";+import AddPassThroughEndpoint from "../add_pass_through";+import PassThroughInfoView from "../pass_through_info";+import NotificationsManager from "../molecules/notifications_manager";+import { PassThroughEndpointsTable } from "./PassThroughEndpointsTable";++interface PassThroughSettingsProps {+ accessToken: string | null;+ userRole: string | null;+ userID: string | null;+ premiumUser?: boolean;+}++export interface passThroughItem {+ id?: string;+ path: string;+ target: string;+ headers: object;+ include_subpath?: boolean;+ cost_per_request?: number;+ timeout?: number;+ auth?: boolean;+ methods?: string[];+ guardrails?: Record<string, { request_fields?: string[]; response_fields?: string[] } | null>;+ default_query_params?: Record<string, string>;+}++const PassThroughSettings: React.FC<PassThroughSettingsProps> = ({ accessToken, userRole, userID, premiumUser }) => {+ const [generalSettings, setGeneralSettings] = useState<passThroughItem[]>([]);+ const [isLoading, setIsLoading] = useState(true);+ const [selectedEndpointId, setSelectedEndpointId] = useState<string | null>(null);+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);+ const [endpointToDelete, setEndpointToDelete] = useState<string | null>(null);++ useEffect(() => {+ const fetchEndpoints = async () => {+ if (!accessToken || !userRole || !userID) {+ setIsLoading(false);+ return;+ }+ try {+ const data = await getPassThroughEndpointsCall(accessToken);+ setGeneralSettings(data["endpoints"]);+ } finally {+ setIsLoading(false);+ }+ };+ fetchEndpoints();+ }, [accessToken, userRole, userID]);++ const handleEndpointUpdated = () => {+ if (accessToken) {+ getPassThroughEndpointsCall(accessToken).then((data) => {+ setGeneralSettings(data["endpoints"]);+ });+ }+ };++ const handleDelete = (endpointId: string) => {+ setEndpointToDelete(endpointId);+ setIsDeleteModalOpen(true);+ };++ const confirmDelete = async () => {+ if (endpointToDelete == null || !accessToken) {+ return;+ }++ try {+ await deletePassThroughEndpointsCall(accessToken, endpointToDelete);++ const updatedSettings = generalSettings.filter((setting) => setting.id !== endpointToDelete);+ setGeneralSettings(updatedSettings);++ NotificationsManager.success("Endpoint deleted successfully.");+ } catch (error) {+ console.error("Error deleting the endpoint:", error);+ NotificationsManager.fromBackend("Error deleting the endpoint: " + error);+ }++ setIsDeleteModalOpen(false);+ setEndpointToDelete(null);+ };++ const cancelDelete = () => {+ setIsDeleteModalOpen(false);+ setEndpointToDelete(null);+ };++ if (!accessToken) {+ return null;+ }++ if (selectedEndpointId) {+ const selectedEndpoint = generalSettings.find((endpoint) => endpoint.id === selectedEndpointId);++ if (!selectedEndpoint) {+ return <div>Endpoint not found</div>;+ }++ return (+ <PassThroughInfoView+ endpointData={selectedEndpoint}+ onClose={() => setSelectedEndpointId(null)}+ accessToken={accessToken}+ isAdmin={userRole === "Admin" || userRole === "admin"}+ premiumUser={premiumUser}+ onEndpointUpdated={handleEndpointUpdated}+ />+ );+ }++ return (+ <div>+ <div className="mb-4">+ <h2 className="text-lg font-semibold text-foreground">Pass Through Endpoints</h2>+ <p className="text-sm text-muted-foreground">Configure and manage your pass-through endpoints</p>+ </div>++ <AddPassThroughEndpoint+ accessToken={accessToken}+ setPassThroughItems={setGeneralSettings}+ passThroughItems={generalSettings}+ premiumUser={premiumUser}+ />++ <PassThroughEndpointsTable+ endpoints={generalSettings}+ isLoading={isLoading}+ onEndpointClick={setSelectedEndpointId}+ onDeleteClick={handleDelete}+ />++ {isDeleteModalOpen && (+ <div className="fixed z-10 inset-0 overflow-y-auto">+ <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">+ <div className="fixed inset-0 transition-opacity" aria-hidden="true">+ <div className="absolute inset-0 bg-gray-500 opacity-75"></div>+ </div>++ <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">+ ​+ </span>++ <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">+ <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">+ <div className="sm:flex sm:items-start">+ <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">+ <h3 className="text-lg leading-6 font-medium text-gray-900">Delete Pass-Through Endpoint</h3>+ <div className="mt-2">+ <p className="text-sm text-gray-500">+ Are you sure you want to delete this pass-through endpoint? This action cannot be undone.+ </p>+ </div>+ </div>+ </div>+ </div>+ <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">+ <Button variant="destructive" onClick={confirmDelete} className="ml-2">+ Delete+ </Button>+ <Button variant="outline" onClick={cancelDelete}>+ Cancel+ </Button>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++export default PassThroughSettings;diff --git a/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.test.tsx b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.test.tsxindex 0533b98b762..3ef7dee01b0 100644--- a/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.test.tsx+++ b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.test.tsx@@ -1,28 +1,43 @@-import { render } from "@testing-library/react";-import { describe, expect, it } from "vitest";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { LoggingCallbacksTable } from "./LoggingCallbacksTable";+const baseVars = {+ SLACK_WEBHOOK_URL: null,+ LANGFUSE_PUBLIC_KEY: null,+ LANGFUSE_SECRET_KEY: null,+ LANGFUSE_HOST: null,+ OPENMETER_API_KEY: null,+};+describe("LoggingCallbacksTable", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+it("should render", () => {- const { getByText } = render(<LoggingCallbacksTable callbacks={[]} availableCallbacks={{}} />);- expect(getByText("Active Logging Callbacks")).toBeInTheDocument();+ render(<LoggingCallbacksTable callbacks={[]} availableCallbacks={{}} />);+ expect(screen.getByText("Active Logging Callbacks")).toBeInTheDocument();+ });++ it("should show the empty state when there are no callbacks", () => {+ render(<LoggingCallbacksTable callbacks={[]} availableCallbacks={{}} />);+ expect(screen.getByText("No callbacks configured")).toBeInTheDocument();+ expect(screen.getByText("Add your first callback to start logging data to external services.")).toBeInTheDocument();+ });++ it("should show skeleton rows while loading", () => {+ render(<LoggingCallbacksTable callbacks={[]} availableCallbacks={{}} isLoading />);+ expect(screen.getAllByTestId("skeleton-row").length).toBeGreaterThan(0);+ expect(screen.queryByText("No callbacks configured")).not.toBeInTheDocument();});it('should map "otel" to "OpenTelemetry" on the table', () => {- const { getByText } = render(+ render(<LoggingCallbacksTable- callbacks={[- {- name: "otel",- variables: {- SLACK_WEBHOOK_URL: null,- LANGFUSE_PUBLIC_KEY: null,- LANGFUSE_SECRET_KEY: null,- LANGFUSE_HOST: null,- OPENMETER_API_KEY: null,- },- },- ]}+ callbacks={[{ name: "otel", variables: baseVars }]}availableCallbacks={{otel: {litellm_callback_name: "otel",@@ -32,28 +47,54 @@ describe("LoggingCallbacksTable", () => {}}/>,);- expect(getByText("OpenTelemetry")).toBeInTheDocument();+ expect(screen.getByText("OpenTelemetry")).toBeInTheDocument();});it("should fallback to original callback name when not in availableCallbacks", () => {- const { getByText } = render(+ render(<LoggingCallbacksTable- callbacks={[- {- name: "custom_callback_x",- variables: {- SLACK_WEBHOOK_URL: null,- LANGFUSE_PUBLIC_KEY: null,- LANGFUSE_SECRET_KEY: null,- LANGFUSE_HOST: null,- OPENMETER_API_KEY: null,- },- },- ]}+ callbacks={[{ name: "custom_callback_x", variables: baseVars }]}+ availableCallbacks={{}}+ />,+ );+ expect(screen.getByText("custom_callback_x")).toBeInTheDocument();+ });++ it("should call onAdd when the Add Callback button is clicked", async () => {+ const user = userEvent.setup();+ const onAdd = vi.fn();+ render(<LoggingCallbacksTable callbacks={[]} availableCallbacks={{}} onAdd={onAdd} />);+ await user.click(screen.getByRole("button", { name: /add callback/i }));+ expect(onAdd).toHaveBeenCalled();+ });++ it("should test, edit, and delete a callback through the actions menu", async () => {+ const user = userEvent.setup();+ const onTest = vi.fn();+ const onEdit = vi.fn();+ const onDelete = vi.fn();+ const callback = { name: "langfuse", type: "success" as const, variables: baseVars };+ render(+ <LoggingCallbacksTable+ callbacks={[callback]}availableCallbacks={{}}+ onTest={onTest}+ onEdit={onEdit}+ onDelete={onDelete}/>,);- expect(getByText("custom_callback_x")).toBeInTheDocument();++ await user.click(screen.getByTestId("callback-actions-langfuse-success"));+ await user.click(await screen.findByTestId("callback-action-test"));+ expect(onTest).toHaveBeenCalledWith(callback);++ await user.click(screen.getByTestId("callback-actions-langfuse-success"));+ await user.click(await screen.findByTestId("callback-action-edit"));+ expect(onEdit).toHaveBeenCalledWith(callback);++ await user.click(screen.getByTestId("callback-actions-langfuse-success"));+ await user.click(await screen.findByTestId("callback-action-delete"));+ expect(onDelete).toHaveBeenCalledWith(callback);});// Regression: `/get_callbacks` returns the same `name` twice when a@@ -61,16 +102,9 @@ describe("LoggingCallbacksTable", () => {// → POST to spend-log on both 200 and 4xx/5xx). The UI used to ignore// the `type` field and render every row as "Success", masking the// failure registration. Reading `record.type` fixes the badge AND- // composing the rowKey with type avoids React's duplicate-key warning.+ // composing the row id with type avoids React's duplicate-key warning.it("renders distinct Success and Failure badges for same-name dual registration", () => {- const baseVars = {- SLACK_WEBHOOK_URL: null,- LANGFUSE_PUBLIC_KEY: null,- LANGFUSE_SECRET_KEY: null,- LANGFUSE_HOST: null,- OPENMETER_API_KEY: null,- };- const { getAllByText, getByText } = render(+ render(<LoggingCallbacksTablecallbacks={[{ name: "generic_api", type: "success", variables: baseVars },@@ -85,9 +119,8 @@ describe("LoggingCallbacksTable", () => {}}/>,);- // Both rows show the same display name, but distinct mode badges.- expect(getAllByText("Custom Callback API")).toHaveLength(2);- expect(getByText("Success")).toBeInTheDocument();- expect(getByText("Failure")).toBeInTheDocument();+ expect(screen.getAllByText("Custom Callback API")).toHaveLength(2);+ expect(screen.getByText("Success")).toBeInTheDocument();+ expect(screen.getByText("Failure")).toBeInTheDocument();});});diff --git a/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.tsx b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.tsxindex 4f1889cbc99..d27b0cfd340 100644--- a/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.tsx+++ b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTable.tsx@@ -1,118 +1,75 @@-import { Button } from "@tremor/react";-import type { TableProps } from "antd";-import { Table } from "antd";-import Title from "antd/es/typography/Title";-import React from "react";-import { StatusBadge, type StatusTone } from "@/components/shared/table_cells";-import TableIconActionButton from "../../../common_components/IconActionButton/TableIconActionButtons/TableIconActionButton";+"use client";++import { Inbox, Plus } from "lucide-react";+import React, { useMemo } from "react";++import { DataTable } from "@/components/shared/DataTable";+import { Button } from "@/components/ui/button";++import {+ AvailableCallbacks,+ CallbackRow,+ callbackRowMode,+ getLoggingCallbacksTableColumns,+} from "./LoggingCallbacksTableColumns";import { AlertingObject } from "./types";type LoggingCallbacksProps = {callbacks: AlertingObject[];- availableCallbacks?: Record<- string,- {- litellm_callback_name: string;- litellm_callback_params: string[];- ui_callback_name: string;- }- >;+ availableCallbacks?: AvailableCallbacks;+ isLoading?: boolean;onTest?: (callback: AlertingObject) => void | Promise<void>;onEdit?: (callback: AlertingObject) => void;onDelete?: (callback: AlertingObject) => void;onAdd?: () => void;};-type CallbackRow = AlertingObject & {- id?: string;- mode?: "success" | "failure" | "info" | string;-};--const CALLBACK_MODES: { value: string; label: string }[] = [- { value: "success", label: "Success" },- { value: "failure", label: "Failure" },- { value: "success_and_failure", label: "Success & Failure" },-];+function EmptyState() {+ return (+ <div className="flex flex-col items-center gap-1 py-6">+ <div className="mb-1 flex size-10 items-center justify-center rounded-lg bg-muted">+ <Inbox className="size-5 text-muted-foreground" />+ </div>+ <div className="text-sm font-medium text-foreground">No callbacks configured</div>+ <div className="text-sm text-muted-foreground">+ Add your first callback to start logging data to external services.+ </div>+ </div>+ );+}export const LoggingCallbacksTable: React.FC<LoggingCallbacksProps> = ({callbacks,availableCallbacks = {},+ isLoading = false,onTest = () => {},onEdit = () => {},onDelete = () => {},onAdd = () => {},}) => {- const columns: TableProps<CallbackRow>["columns"] = [- {- title: <span className="font-medium text-gray-700">Callback Name</span>,- dataIndex: "name",- key: "name",- render: (_: string, record: CallbackRow) => {- const id = record.name;- const displayName = availableCallbacks[id]?.ui_callback_name || id;- return <div className="font-medium text-gray-800">{displayName}</div>;- },- },- {- title: <span className="font-medium text-gray-700">Mode</span>,- key: "mode",- render: (_: unknown, record: CallbackRow) => {- // Backend sends `type` (success | failure); legacy in-memory rows- // from add-callback flow set `mode`. Read both so newly-added rows- // and server-fetched rows both render correctly.- const mode = record.type || record.mode || "success";- const label = CALLBACK_MODES.find((m) => m.value === mode)?.label || mode;- const tone: StatusTone = mode === "success" ? "success" : mode === "failure" ? "error" : "info";- return <StatusBadge tone={tone} label={label} />;- },- width: 240,- },- {- title: <span className="font-medium text-gray-700 text-right w-full block">Actions</span>,- key: "actions",- align: "right",- render: (_: unknown, record: CallbackRow) => (- <div className="flex justify-end gap-2">- <TableIconActionButton variant="Test" tooltipText="Test Callback" onClick={() => onTest(record)} />- <TableIconActionButton variant="Edit" tooltipText="Edit Callback" onClick={() => onEdit(record)} />- <TableIconActionButton variant="Delete" tooltipText="Delete Callback" onClick={() => onDelete(record)} />- </div>- ),- width: 240,- },- ];+ const columns = useMemo(() => {+ const deps = { availableCallbacks, onTest, onEdit, onDelete };+ return getLoggingCallbacksTableColumns(deps);+ }, [availableCallbacks, onTest, onEdit, onDelete]);+return (- <>- <div className="w-full mt-4">- <Button onClick={onAdd} className="mx-auto">- + Add Callback+ <div className="mt-4 flex w-full flex-col gap-4">+ <h3 className="text-lg font-semibold tracking-tight text-foreground">Active Logging Callbacks</h3>+ <div>+ <Button onClick={onAdd}>+ <Plus />+ Add Callback</Button>- <div className="flex justify-between items-center my-2">- <Title level={4}>Active Logging Callbacks</Title>- </div>- {/* Empty state */}- {callbacks.length === 0 ? (- <div className="flex flex-col items-center justify-center p-8 bg-gray-50 border border-gray-200 rounded-lg">- <div className="text-center">- <h3 className="text-lg font-medium text-gray-700 mb-2">No callbacks configured</h3>- <p className="text-gray-500">Add your first callback to start logging data to external services.</p>- </div>- </div>- ) : (- <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">- <Table- columns={columns}- dataSource={callbacks as CallbackRow[]}- // `generic_api` can appear as both a success and a failure- // callback simultaneously — keying by `name` alone produced- // duplicate React keys. Compose with type to keep keys unique.- rowKey={(record) => `${record.name}-${record.type || record.mode || "success"}`}- pagination={false}- rowClassName={() => "hover:bg-gray-50"}- />- </div>- )}</div>- </>+ <DataTable+ data={callbacks as CallbackRow[]}+ columns={columns}+ getRowId={(callback, index) => `${callback.name || index}-${callbackRowMode(callback)}`}+ isLoading={isLoading}+ loadingMessage="Loading callbacks…"+ noDataMessage={<EmptyState />}+ size="compact"+ />+ </div>);};diff --git a/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTableColumns.tsx b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTableColumns.tsxnew file mode 100644index 00000000000..2263fe03b3d--- /dev/null+++ b/ui/litellm-dashboard/src/components/Settings/LoggingAndAlerts/LoggingCallbacks/LoggingCallbacksTableColumns.tsx@@ -0,0 +1,134 @@+"use client";++import { ColumnDef } from "@tanstack/react-table";+import { MoreHorizontal, Pencil, Play, Trash2 } from "lucide-react";++import { StatusBadge, type StatusTone } from "@/components/shared/table_cells";+import { buttonVariants } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { cn } from "@/lib/cva.config";++import { AlertingObject } from "./types";++export type CallbackRow = AlertingObject & {+ mode?: "success" | "failure" | "info" | string;+};++export interface AvailableCallbackMeta {+ litellm_callback_name: string;+ litellm_callback_params: string[];+ ui_callback_name: string;+}++export type AvailableCallbacks = Record<string, AvailableCallbackMeta>;++export const callbackRowMode = (record: CallbackRow): string => record.type || record.mode || "success";++const CALLBACK_MODE_LABELS: Record<string, string> = {+ success: "Success",+ failure: "Failure",+ success_and_failure: "Success & Failure",+};++function callbackModeTone(mode: string): StatusTone {+ if (mode === "success") return "success";+ if (mode === "failure") return "error";+ return "info";+}++interface CallbackRowActionsProps {+ callback: CallbackRow;+ onTest: (callback: AlertingObject) => void | Promise<void>;+ onEdit: (callback: AlertingObject) => void;+ onDelete: (callback: AlertingObject) => void;+}++function CallbackRowActions({ callback, onTest, onEdit, onDelete }: CallbackRowActionsProps) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label="Open callback actions"+ data-testid={`callback-actions-${callback.name}-${callbackRowMode(callback)}`}+ className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }), "text-muted-foreground")}+ >+ <MoreHorizontal className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem data-testid="callback-action-test" onClick={() => void onTest(callback)}>+ <Play />+ Test+ </DropdownMenuItem>+ <DropdownMenuItem data-testid="callback-action-edit" onClick={() => onEdit(callback)}>+ <Pencil />+ Edit+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" data-testid="callback-action-delete" onClick={() => onDelete(callback)}>+ <Trash2 />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++interface LoggingCallbacksTableColumnsDeps {+ availableCallbacks: AvailableCallbacks;+ onTest: (callback: AlertingObject) => void | Promise<void>;+ onEdit: (callback: AlertingObject) => void;+ onDelete: (callback: AlertingObject) => void;+}++export const getLoggingCallbacksTableColumns = ({+ availableCallbacks,+ onTest,+ onEdit,+ onDelete,+}: LoggingCallbacksTableColumnsDeps): ColumnDef<CallbackRow>[] => [+ {+ id: "name",+ accessorKey: "name",+ meta: { title: "Callback Name" },+ header: "Callback Name",+ enableSorting: false,+ cell: ({ row }) => {+ const id = row.original.name;+ const displayName = availableCallbacks[id]?.ui_callback_name || id;+ return (+ <span className="block max-w-72 truncate text-sm font-medium" title={displayName}>+ {displayName}+ </span>+ );+ },+ },+ {+ id: "mode",+ meta: { title: "Mode", skeleton: "badge" },+ header: "Mode",+ size: 240,+ enableSorting: false,+ cell: ({ row }) => {+ const mode = callbackRowMode(row.original);+ return <StatusBadge tone={callbackModeTone(mode)} label={CALLBACK_MODE_LABELS[mode] || mode} />;+ },+ },+ {+ id: "actions",+ meta: { className: "text-right", headerClassName: "text-right" },+ header: () => <span className="sr-only">Actions</span>,+ size: 64,+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => (+ <div className="flex justify-end">+ <CallbackRowActions callback={row.original} onTest={onTest} onEdit={onEdit} onDelete={onDelete} />+ </div>+ ),+ },+];diff --git a/ui/litellm-dashboard/src/components/add_pass_through.tsx b/ui/litellm-dashboard/src/components/add_pass_through.tsxindex af71d3f97fe..c0343e268a1 100644--- a/ui/litellm-dashboard/src/components/add_pass_through.tsx+++ b/ui/litellm-dashboard/src/components/add_pass_through.tsx@@ -11,7 +11,7 @@ import NumericalInput from "./shared/numerical_input";import { InfoCircleOutlined, ApiOutlined } from "@ant-design/icons";import KeyValueInput from "./key_value_input";import QueryParamInput from "./query_param_input";-import { passThroughItem } from "./pass_through_settings";+import { passThroughItem } from "./PassThroughSettings/PassThroughSettings";import RoutePreview from "./route_preview";import NotificationsManager from "./molecules/notifications_manager";import PassThroughSecuritySection from "./common_components/PassThroughSecuritySection";diff --git a/ui/litellm-dashboard/src/components/pass_through_settings.tsx b/ui/litellm-dashboard/src/components/pass_through_settings.tsxdeleted file mode 100644index 6c72b8a62ab..00000000000--- a/ui/litellm-dashboard/src/components/pass_through_settings.tsx+++ /dev/null@@ -1,304 +0,0 @@-import React, { useState, useEffect } from "react";-import { Text, Button, Icon, Title } from "@tremor/react";-import { deletePassThroughEndpointsCall, getPassThroughEndpointsCall } from "./networking";-import { Badge, Tooltip } from "antd";-import { PencilAltIcon, TrashIcon, InformationCircleIcon } from "@heroicons/react/outline";-import AddPassThroughEndpoint from "./add_pass_through";-import PassThroughInfoView from "./pass_through_info";-import { DataTable } from "./view_logs/table";-import { ColumnDef } from "@tanstack/react-table";-import { IdCell, StatusBadge } from "@/components/shared/table_cells";-import { Eye, EyeOff } from "lucide-react";-import NotificationsManager from "./molecules/notifications_manager";--interface GeneralSettingsPageProps {- accessToken: string | null;- userRole: string | null;- userID: string | null;- modelData: any;- premiumUser?: boolean;-}--interface routingStrategyArgs {- ttl?: number;- lowest_latency_buffer?: number;-}--interface nestedFieldItem {- field_name: string;- field_type: string;- field_value: any;- field_description: string;- stored_in_db: boolean | null;-}--export interface passThroughItem {- id?: string;- path: string;- target: string;- headers: object;- include_subpath?: boolean;- cost_per_request?: number;- timeout?: number;- auth?: boolean;- methods?: string[];- guardrails?: Record<string, { request_fields?: string[]; response_fields?: string[] } | null>;- default_query_params?: Record<string, string>;-}--// Password field component for headers-const PasswordField: React.FC<{ value: object }> = ({ value }) => {- const [showPassword, setShowPassword] = useState(false);- const headerString = JSON.stringify(value);-- return (- <div className="flex items-center space-x-2">- <span className="font-mono text-xs">{showPassword ? headerString : "••••••••"}</span>- <button onClick={() => setShowPassword(!showPassword)} className="p-1 hover:bg-gray-100 rounded-sm" type="button">- {showPassword ? <EyeOff className="w-4 h-4 text-gray-500" /> : <Eye className="w-4 h-4 text-gray-500" />}- </button>- </div>- );-};--const PassThroughSettings: React.FC<GeneralSettingsPageProps> = ({- accessToken,- userRole,- userID,- modelData,- premiumUser,-}) => {- const [generalSettings, setGeneralSettings] = useState<passThroughItem[]>([]);- const [selectedEndpointId, setSelectedEndpointId] = useState<string | null>(null);- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);- const [endpointToDelete, setEndpointToDelete] = useState<string | null>(null);-- useEffect(() => {- if (!accessToken || !userRole || !userID) {- return;- }- getPassThroughEndpointsCall(accessToken).then((data) => {- let general_settings = data["endpoints"];- setGeneralSettings(general_settings);- });- }, [accessToken, userRole, userID]);-- const handleEndpointUpdated = () => {- // Refresh the endpoints list when an endpoint is updated- if (accessToken) {- getPassThroughEndpointsCall(accessToken).then((data) => {- let general_settings = data["endpoints"];- setGeneralSettings(general_settings);- });- }- };-- const handleDelete = async (endpointId: string) => {- // Set the endpoint to delete and open the confirmation modal- setEndpointToDelete(endpointId);- setIsDeleteModalOpen(true);- };-- const confirmDelete = async () => {- if (endpointToDelete == null || !accessToken) {- return;- }-- try {- await deletePassThroughEndpointsCall(accessToken, endpointToDelete);-- const updatedSettings = generalSettings.filter((setting) => setting.id !== endpointToDelete);- setGeneralSettings(updatedSettings);-- NotificationsManager.success("Endpoint deleted successfully.");- } catch (error) {- console.error("Error deleting the endpoint:", error);- NotificationsManager.fromBackend("Error deleting the endpoint: " + error);- }-- // Close the confirmation modal and reset the endpointToDelete- setIsDeleteModalOpen(false);- setEndpointToDelete(null);- };-- const cancelDelete = () => {- // Close the confirmation modal and reset the endpointToDelete- setIsDeleteModalOpen(false);- setEndpointToDelete(null);- };-- const handleResetField = (endpointId: string, idx: number) => {- // Use handleDelete instead of direct deletion- handleDelete(endpointId);- };-- // Define columns for the DataTable- const columns: ColumnDef<passThroughItem>[] = [- {- header: "ID",- accessorKey: "id",- cell: (info: any) => <IdCell value={info.row.original.id} onClick={setSelectedEndpointId} />,- },- {- header: "Path",- accessorKey: "path",- },- {- header: "Target",- accessorKey: "target",- cell: (info: any) => <Text>{info.getValue()}</Text>,- },- {- header: () => (- <div className="flex items-center gap-1">- <span>Methods</span>- <Tooltip title="HTTP methods supported by this endpoint">- <InformationCircleIcon className="w-4 h-4 text-gray-400 cursor-help" />- </Tooltip>- </div>- ),- accessorKey: "methods",- cell: (info: any) => {- const methods = info.getValue();- if (!methods || methods.length === 0) {- return <Badge color="blue">ALL</Badge>;- }- return (- <div className="flex flex-wrap gap-1">- {methods.map((method: string) => (- <Badge key={method} color="indigo" className="text-xs">- {method}- </Badge>- ))}- </div>- );- },- },- {- header: () => (- <div className="flex items-center gap-1">- <span>Authentication</span>- <Tooltip title="LiteLLM Virtual Key required to call endpoint">- <InformationCircleIcon className="w-4 h-4 text-gray-400 cursor-help" />- </Tooltip>- </div>- ),- accessorKey: "auth",- cell: (info: any) => (- <StatusBadge tone={info.getValue() ? "success" : "neutral"} label={info.getValue() ? "Yes" : "No"} />- ),- },- {- header: "Headers",- accessorKey: "headers",- cell: (info: any) => <PasswordField value={info.getValue() || {}} />,- },- {- header: "Actions",- id: "actions",- cell: ({ row }) => (- <div className="flex space-x-1">- <Icon- icon={PencilAltIcon}- size="sm"- onClick={() => row.original.id && setSelectedEndpointId(row.original.id)}- title="Edit"- />- <Icon- icon={TrashIcon}- size="sm"- onClick={() => handleResetField(row.original.id!, row.index)}- title="Delete"- />- </div>- ),- },- ];-- if (!accessToken) {- return null;- }-- // If a specific endpoint is selected, show the info view- if (selectedEndpointId) {- // Find the endpoint by ID to get the endpoint data for the info view- const selectedEndpoint = generalSettings.find((endpoint) => endpoint.id === selectedEndpointId);-- if (!selectedEndpoint) {- return <div>Endpoint not found</div>;- }-- return (- <PassThroughInfoView- endpointData={selectedEndpoint}- onClose={() => setSelectedEndpointId(null)}- accessToken={accessToken}- isAdmin={userRole === "Admin" || userRole === "admin"}- premiumUser={premiumUser}- onEndpointUpdated={handleEndpointUpdated}- />- );- }-- return (- <div>- <div>- <Title>Pass Through Endpoints</Title>- <Text className="text-tremor-content">Configure and manage your pass-through endpoints</Text>- </div>-- <AddPassThroughEndpoint- accessToken={accessToken}- setPassThroughItems={setGeneralSettings}- passThroughItems={generalSettings}- premiumUser={premiumUser}- />-- <DataTable- data={generalSettings}- columns={columns}- isLoading={false}- noDataMessage="No pass-through endpoints configured"- />-- {isDeleteModalOpen && (- <div className="fixed z-10 inset-0 overflow-y-auto">- <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">- <div className="fixed inset-0 transition-opacity" aria-hidden="true">- <div className="absolute inset-0 bg-gray-500 opacity-75"></div>- </div>-- {/* Modal Panel */}- <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">- ​- </span>-- {/* Confirmation Modal Content */}- <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">- <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">- <div className="sm:flex sm:items-start">- <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">- <h3 className="text-lg leading-6 font-medium text-gray-900">Delete Pass-Through Endpoint</h3>- <div className="mt-2">- <p className="text-sm text-gray-500">- Are you sure you want to delete this pass-through endpoint? This action cannot be undone.- </p>- </div>- </div>- </div>- </div>- <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">- <Button onClick={confirmDelete} color="red" className="ml-2">- Delete- </Button>- <Button onClick={cancelDelete}>Cancel</Button>- </div>- </div>- </div>- </div>- )}- </div>- );-};--export default PassThroughSettings;diff --git a/ui/litellm-dashboard/src/components/settings.test.tsx b/ui/litellm-dashboard/src/components/settings.test.tsxindex 7776d0c7082..ebc1a5a7a6c 100644--- a/ui/litellm-dashboard/src/components/settings.test.tsx+++ b/ui/litellm-dashboard/src/components/settings.test.tsx@@ -1,4 +1,5 @@-import { act, fireEvent, render, waitFor } from "@testing-library/react";+import { act, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { alertingSettingsCall, getCallbackConfigsCall, getCallbacksCall } from "./networking";import Settings from "./settings";@@ -160,7 +161,8 @@ describe("Settings", () => {mockGetCallbackConfigsCall.mockResolvedValue([mockCallbackConfig]);- const { getByText, container } = render(<Settings {...defaultProps} />);+ const user = userEvent.setup();+ const { getByText } = render(<Settings {...defaultProps} />);await waitFor(() => {expect(getByText("Active Logging Callbacks")).toBeInTheDocument();@@ -170,18 +172,8 @@ describe("Settings", () => {expect(getByText("Langfuse")).toBeInTheDocument();});- const actionsCell = container.querySelector('[class*="flex justify-end gap-2"]');- expect(actionsCell).toBeTruthy();-- const icons = actionsCell?.querySelectorAll("svg");- expect(icons?.length).toBeGreaterThanOrEqual(2);-- const editIconParent = icons?.[1]?.closest('[class*="cursor-pointer"]');- expect(editIconParent).toBeTruthy();-- act(() => {- fireEvent.click(editIconParent!);- });+ await user.click(screen.getByTestId("callback-actions-langfuse-success"));+ await user.click(await screen.findByTestId("callback-action-edit"));await waitFor(() => {expect(getByText("Edit Callback Settings")).toBeInTheDocument();@@ -194,6 +186,42 @@ describe("Settings", () => {});});+ it("should hold the callbacks table in loading state until the fetch settles", async () => {+ let resolveCallbacks: (value: {+ callbacks: never[];+ available_callbacks: never[];+ alerts: never[];+ }) => void = () => {};+ mockGetCallbacksCall.mockReturnValue(+ new Promise((resolve) => {+ resolveCallbacks = resolve;+ }),+ );++ render(<Settings {...defaultProps} />);++ expect(screen.getAllByTestId("skeleton-row").length).toBeGreaterThan(0);++ await act(async () => {+ resolveCallbacks({ callbacks: [], available_callbacks: [], alerts: [] });+ });++ await waitFor(() => {+ expect(screen.queryByTestId("skeleton-row")).not.toBeInTheDocument();+ });+ expect(screen.getByText("No callbacks configured")).toBeInTheDocument();+ });++ it("should resolve loading without fetching when the user id is missing", async () => {+ render(<Settings {...defaultProps} userID={null as unknown as string} />);++ await waitFor(() => {+ expect(screen.queryByTestId("skeleton-row")).not.toBeInTheDocument();+ });+ expect(mockGetCallbacksCall).not.toHaveBeenCalled();+ expect(screen.getByText("No callbacks configured")).toBeInTheDocument();+ });+it("should display CloudZero Cost Tracking tab", async () => {const { getByText } = render(<Settings {...defaultProps} />);diff --git a/ui/litellm-dashboard/src/components/settings.tsx b/ui/litellm-dashboard/src/components/settings.tsxindex 46811e0106b..b3f33133a80 100644--- a/ui/litellm-dashboard/src/components/settings.tsx+++ b/ui/litellm-dashboard/src/components/settings.tsx@@ -217,6 +217,7 @@ const buildCallbackPayload = (formValues: Record<string, any>, callbackName: strconst Settings: React.FC<SettingsPageProps> = ({ accessToken, userRole, userID, premiumUser }) => {const [callbacks, setCallbacks] = useState<AlertingObject[]>([]);+ const [isLoadingCallbacks, setIsLoadingCallbacks] = useState(true);const [alerts, setAlerts] = useState<any[]>([]);const [isModalVisible, setIsModalVisible] = useState(false);const [addForm] = Form.useForm();@@ -293,29 +294,35 @@ const Settings: React.FC<SettingsPageProps> = ({ accessToken, userRole, userID,};useEffect(() => {- if (!accessToken || !userRole || !userID) {- return;- }- getCallbacksCall(accessToken, userID, userRole).then((data) => {- setCallbacks(data.callbacks);- setAllCallbacks(data.available_callbacks);- // setCallbacks(callbacks_data);-- let alerts_data = data.alerts;- if (alerts_data) {- if (alerts_data.length > 0) {- let _alert_info = alerts_data[0];- let catch_all_webhook = _alert_info.variables.SLACK_WEBHOOK_URL;-- let active_alerts = _alert_info.active_alerts;- setActiveAlerts(active_alerts);- setCatchAllWebhookURL(catch_all_webhook);- setAlertToWebhooks(_alert_info.alerts_to_webhook);- }+ const fetchCallbacks = async () => {+ if (!accessToken || !userRole || !userID) {+ setIsLoadingCallbacks(false);+ return;}+ try {+ const data = await getCallbacksCall(accessToken, userID, userRole);+ setCallbacks(data.callbacks);+ setAllCallbacks(data.available_callbacks);++ let alerts_data = data.alerts;+ if (alerts_data) {+ if (alerts_data.length > 0) {+ let _alert_info = alerts_data[0];+ let catch_all_webhook = _alert_info.variables.SLACK_WEBHOOK_URL;++ let active_alerts = _alert_info.active_alerts;+ setActiveAlerts(active_alerts);+ setCatchAllWebhookURL(catch_all_webhook);+ setAlertToWebhooks(_alert_info.alerts_to_webhook);+ }+ }- setAlerts(alerts_data);- });+ setAlerts(alerts_data);+ } finally {+ setIsLoadingCallbacks(false);+ }+ };+ fetchCallbacks();}, [accessToken, userRole, userID]);const isAlertOn = (alertName: string) => {@@ -581,6 +588,7 @@ const Settings: React.FC<SettingsPageProps> = ({ accessToken, userRole, userID,<LoggingCallbacksTablecallbacks={callbacks}availableCallbacks={allCallbacks}+ isLoading={isLoadingCallbacks}onAdd={() => setShowAddCallbacksModal(true)}onEdit={(cb) => {setSelectedEditCallback(cb);