From 035f8d5f8aff3946f14505152a332a1585218e64 Mon Sep 17 00:00:00 2001 From: Yuneng Jiang Date: Fri, 14 Aug 2026 09:36:16 -0700 Subject: [PATCH] refactor(ui): move the cost tracking components onto shadcn primitives Rebuilds the provider discount and margin tables, the pricing calculator and its multi-cost results on the in-repo shadcn layer, and swaps the imperative antd modal.confirm removals for AlertDialog. Row actions gained accessible names, which replace the Tremor stub mocks the tests used to drive. cost_tracking_settings keeps its two antd Modals and Forms, since they wrap the two add forms that stay on antd for now. --- ui/litellm-dashboard/eslint-suppressions.json | 14 +- .../cost_tracking_settings.test.tsx | 83 ++++- .../_components/cost_tracking_settings.tsx | 285 +++++++------- .../pricing_calculator/index.test.tsx | 39 +- .../_components/pricing_calculator/index.tsx | 227 ++++++------ .../multi_cost_results.test.tsx | 90 +++-- .../pricing_calculator/multi_cost_results.tsx | 349 +++++++++--------- .../provider_discount_table.test.tsx | 204 ++++++---- .../_components/provider_discount_table.tsx | 106 +++--- .../provider_margin_table.test.tsx | 158 +++++--- .../_components/provider_margin_table.tsx | 129 ++++--- 11 files changed, 982 insertions(+), 702 deletions(-) diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.json index 5e322598a10..7738a9e46d1 100644 --- a/ui/litellm-dashboard/eslint-suppressions.json +++ b/ui/litellm-dashboard/eslint-suppressions.json @@ -228,7 +228,7 @@ "count": 2 }, "no-restricted-imports": { - "count": 2 + "count": 1 } }, "src/app/(dashboard)/cost-tracking/_components/how_it_works.tsx": { @@ -239,9 +239,6 @@ "src/app/(dashboard)/cost-tracking/_components/pricing_calculator/index.tsx": { "local/filename-pascal-case": { "count": 1 - }, - "no-restricted-imports": { - "count": 1 } }, "src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx": { @@ -252,9 +249,6 @@ "src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx": { "local/filename-pascal-case": { "count": 1 - }, - "no-restricted-imports": { - "count": 2 } }, "src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_export_dropdown.tsx": { @@ -275,17 +269,11 @@ "src/app/(dashboard)/cost-tracking/_components/provider_discount_table.tsx": { "local/filename-pascal-case": { "count": 1 - }, - "no-restricted-imports": { - "count": 1 } }, "src/app/(dashboard)/cost-tracking/_components/provider_margin_table.tsx": { "local/filename-pascal-case": { "count": 1 - }, - "no-restricted-imports": { - "count": 1 } }, "src/app/(dashboard)/cost-tracking/_components/use_discount_config.ts": { diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.test.tsx index 0dae83ba808..c53b7b618b2 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.test.tsx @@ -8,25 +8,29 @@ import CostTrackingSettings from "./cost_tracking_settings"; // Mock sub-hooks so we can control their state without network calls const mockDiscountConfig = vi.fn(() => ({})); const mockMarginConfig = vi.fn(() => ({})); +const mockRemoveDiscount = vi.fn(); +const mockRemoveMargin = vi.fn(); + +const stableDiscountCallbacks = { + fetchDiscountConfig: vi.fn().mockResolvedValue(undefined), + handleAddProvider: vi.fn().mockResolvedValue(true), + handleRemoveProvider: mockRemoveDiscount, + handleDiscountChange: vi.fn().mockResolvedValue(undefined), +}; + +const stableMarginCallbacks = { + fetchMarginConfig: vi.fn().mockResolvedValue(undefined), + handleAddMargin: vi.fn().mockResolvedValue(true), + handleRemoveMargin: mockRemoveMargin, + handleMarginChange: vi.fn().mockResolvedValue(undefined), +}; vi.mock("./use_discount_config", () => ({ - useDiscountConfig: () => ({ - discountConfig: mockDiscountConfig(), - fetchDiscountConfig: vi.fn().mockResolvedValue(undefined), - handleAddProvider: vi.fn().mockResolvedValue(true), - handleRemoveProvider: vi.fn().mockResolvedValue(undefined), - handleDiscountChange: vi.fn().mockResolvedValue(undefined), - }), + useDiscountConfig: () => ({ discountConfig: mockDiscountConfig(), ...stableDiscountCallbacks }), })); vi.mock("./use_margin_config", () => ({ - useMarginConfig: () => ({ - marginConfig: mockMarginConfig(), - fetchMarginConfig: vi.fn().mockResolvedValue(undefined), - handleAddMargin: vi.fn().mockResolvedValue(true), - handleRemoveMargin: vi.fn().mockResolvedValue(undefined), - handleMarginChange: vi.fn().mockResolvedValue(undefined), - }), + useMarginConfig: () => ({ marginConfig: mockMarginConfig(), ...stableMarginCallbacks }), })); vi.mock("./pricing_calculator/index", () => ({ @@ -153,6 +157,57 @@ describe("CostTrackingSettings", () => { }); }); + describe("removing a configured provider", () => { + const expandAndRemove = async (section: string, actionName: string) => { + const user = userEvent.setup(); + renderWithProviders(); + + await user.click(screen.getByText(section).closest("button")!); + await user.click(await screen.findByRole("button", { name: actionName })); + + return user; + }; + + it("should ask to confirm before removing a discount", async () => { + mockDiscountConfig.mockReturnValue({ openai: 0.05 }); + + await expandAndRemove("Provider Discounts", "Remove discount for openai"); + + expect(await screen.findByRole("button", { name: "Remove" })).toBeInTheDocument(); + expect(screen.getByText(/are you sure you want to remove the discount for openai\?/i)).toBeInTheDocument(); + expect(mockRemoveDiscount).not.toHaveBeenCalled(); + }); + + it("should remove the discount once removal is confirmed", async () => { + mockDiscountConfig.mockReturnValue({ openai: 0.05 }); + + const user = await expandAndRemove("Provider Discounts", "Remove discount for openai"); + await user.click(await screen.findByRole("button", { name: "Remove" })); + + expect(mockRemoveDiscount).toHaveBeenCalledWith("openai"); + }); + + it("should leave the discount in place when the confirmation is cancelled", async () => { + mockDiscountConfig.mockReturnValue({ openai: 0.05 }); + + const user = await expandAndRemove("Provider Discounts", "Remove discount for openai"); + await user.click(await screen.findByRole("button", { name: "Cancel" })); + + expect(mockRemoveDiscount).not.toHaveBeenCalled(); + expect(screen.queryByRole("button", { name: "Remove" })).not.toBeInTheDocument(); + }); + + it("should remove the margin once removal is confirmed", async () => { + mockMarginConfig.mockReturnValue({ openai: 0.1 }); + + const user = await expandAndRemove("Fee/Price Margin", "Remove margin for openai"); + expect(screen.getByText(/are you sure you want to remove the margin for openai\?/i)).toBeInTheDocument(); + await user.click(await screen.findByRole("button", { name: "Remove" })); + + expect(mockRemoveMargin).toHaveBeenCalledWith("openai"); + }); + }); + describe("empty state messages", () => { it("should show the empty state message when no discount config is loaded", async () => { mockDiscountConfig.mockReturnValue({}); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx index b32e7afd756..ba2d830ae7b 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx @@ -1,25 +1,25 @@ import React, { useState, useEffect } from "react"; -import { - Title, - Text, - Button, - Accordion, - AccordionHeader, - AccordionBody, - TabGroup, - TabList, - Tab, - TabPanels, - TabPanel, -} from "@tremor/react"; +import { ChevronDown } from "lucide-react"; import { Modal, Form } from "antd"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { CostTrackingSettingsProps } from "./types"; import ProviderDiscountTable from "./provider_discount_table"; import AddProviderForm from "./add_provider_form"; import ProviderMarginTable from "./provider_margin_table"; import AddMarginForm from "./add_margin_form"; import PricingCalculator from "./pricing_calculator/index"; -import { ExclamationCircleOutlined } from "@ant-design/icons"; import { DocsMenu } from "@/components/HelpLink"; import HowItWorks from "./how_it_works"; import { useDiscountConfig } from "./use_discount_config"; @@ -31,6 +31,29 @@ const DOCS_LINKS = [ { label: "Spend tracking", href: "https://docs.litellm.ai/docs/proxy/cost_tracking" }, ]; +const REMOVAL_COPY = { + discount: { title: "Remove Provider Discount", noun: "discount" }, + margin: { title: "Remove Provider Margin", noun: "margin" }, +} as const; + +interface PendingRemoval { + kind: keyof typeof REMOVAL_COPY; + provider: string; + displayName: string; +} + +const SECTION_HEADER_CLASS = "group/section flex w-full items-center justify-between px-6 py-4 text-left"; + +const SectionHeader: React.FC<{ title: string; description: string }> = ({ title, description }) => ( + +
+ {title} + {description} +
+ +
+); + const CostTrackingSettings: React.FC = ({ userID, userRole, accessToken }) => { const [selectedProvider, setSelectedProvider] = useState(undefined); const [newDiscount, setNewDiscount] = useState(""); @@ -42,9 +65,9 @@ const CostTrackingSettings: React.FC = ({ userID, use const [percentageValue, setPercentageValue] = useState(""); const [fixedAmountValue, setFixedAmountValue] = useState(""); const [models, setModels] = useState([]); + const [pendingRemoval, setPendingRemoval] = useState(null); const [form] = Form.useForm(); const [marginForm] = Form.useForm(); - const [modal, contextHolder] = Modal.useModal(); const isProxyAdmin = userRole === "proxy_admin" || userRole === "Admin"; @@ -104,16 +127,18 @@ const CostTrackingSettings: React.FC = ({ userID, use handleAddProvider(); }; - const handleRemoveProvider = async (provider: string, providerDisplayName: string) => { - modal.confirm({ - title: "Remove Provider Discount", - icon: , - content: `Are you sure you want to remove the discount for ${providerDisplayName}?`, - okText: "Remove", - okType: "danger", - cancelText: "Cancel", - onOk: () => removeProvider(provider), - }); + const handleRemoveProvider = (provider: string, providerDisplayName: string) => { + setPendingRemoval({ kind: "discount", provider, displayName: providerDisplayName }); + }; + + const handleConfirmRemoval = () => { + if (!pendingRemoval) return; + if (pendingRemoval.kind === "discount") { + removeProvider(pendingRemoval.provider); + } else { + removeMargin(pendingRemoval.provider); + } + setPendingRemoval(null); }; const handleAddMargin = async () => { @@ -141,16 +166,8 @@ const CostTrackingSettings: React.FC = ({ userID, use setMarginType("percentage"); }; - const handleRemoveMargin = async (provider: string, providerDisplayName: string) => { - modal.confirm({ - title: "Remove Provider Margin", - icon: , - content: `Are you sure you want to remove the margin for ${providerDisplayName}?`, - okText: "Remove", - okType: "danger", - cancelText: "Cancel", - onOk: () => removeMargin(provider), - }); + const handleRemoveMargin = (provider: string, providerDisplayName: string) => { + setPendingRemoval({ kind: "margin", provider, displayName: providerDisplayName }); }; if (!accessToken) { @@ -159,18 +176,16 @@ const CostTrackingSettings: React.FC = ({ userID, use return (
- {contextHolder} - {/* Header Section - Outside the card */}
- Cost Tracking Settings +

Cost Tracking Settings

- +

Configure cost discounts and margins for different LLM providers. Changes are saved automatically. - +

@@ -178,90 +193,78 @@ const CostTrackingSettings: React.FC = ({ userID, use
{/* Accordion 1: Provider Discounts - Only for proxy admins */} {isProxyAdmin && ( - - -
- Provider Discounts - - Apply percentage-based discounts to reduce costs for specific providers - -
-
- - - - Discounts - Test It - - - -
-
- + + + + + + Discounts + Test It + + +
+
+ +
+ {isFetching ? ( +
+

Loading configuration...

- {isFetching ? ( -
- Loading configuration... -
- ) : Object.keys(discountConfig).length > 0 ? ( - - ) : ( -
- - - - No provider discounts configured - - Click "Add Provider Discount" to get started - -
- )} -
- - -
- -
-
- - - - + ) : Object.keys(discountConfig).length > 0 ? ( + + ) : ( +
+ + + +

No provider discounts configured

+

Click "Add Provider Discount" to get started

+
+ )} +
+ + +
+ +
+
+ + + )} {/* Accordion 2: Fee/Price Margin - Only for proxy admins */} {isProxyAdmin && ( - - -
- Fee/Price Margin - - Add fees or margins to LLM costs for internal billing and cost recovery - -
-
- + + +
{isFetching ? (
- Loading configuration... +

Loading configuration...

) : Object.keys(marginConfig).length > 0 ? ( = ({ userID, use d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> - No provider margins configured - Click "Add Provider Margin" to get started +

No provider margins configured

+

Click "Add Provider Margin" to get started

)}
-
-
+ + )} {/* Accordion 3: Pricing Calculator - Available to all roles */} - - -
- Pricing Calculator - - Estimate LLM costs based on expected token usage and request volume - -
-
- + + +
-
-
+ +
+ {pendingRemoval && ( + !open && setPendingRemoval(null)}> + + + {REMOVAL_COPY[pendingRemoval.kind].title} + + Are you sure you want to remove the {REMOVAL_COPY[pendingRemoval.kind].noun} for{" "} + {pendingRemoval.displayName}? + + + + Cancel + + Remove + + + + + )} + @@ -328,10 +347,10 @@ const CostTrackingSettings: React.FC = ({ userID, use }} >
- +

Select a provider and set its discount percentage. Enter a value between 0% and 100% (e.g., 5 for a 5% discount). - +

= ({ userID, use }} >
- +

Select a provider (or "Global" for all providers) and configure the margin. You can use percentage-based or fixed amount. - +

+ within(screen.getByRole("table")) + .getAllByRole("row") + .filter((row) => within(row).queryAllByRole("combobox").length > 0); + +const deleteButtonIn = (row: HTMLElement): HTMLElement => { + const cells = within(row).getAllByRole("cell"); + return within(cells[cells.length - 1]).getByRole("button"); +}; + describe("PricingCalculator", () => { beforeEach(() => { vi.clearAllMocks(); @@ -124,8 +134,31 @@ describe("PricingCalculator", () => { it("should render column headers for Model, Input Tokens, and Output Tokens", () => { renderWithProviders(); - expect(screen.getByText("Model")).toBeInTheDocument(); - expect(screen.getByText("Input Tokens")).toBeInTheDocument(); - expect(screen.getByText("Output Tokens")).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Model" })).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Input Tokens" })).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Output Tokens" })).toBeInTheDocument(); + }); + + it("should render a numeric field for input tokens, output tokens and requests", () => { + renderWithProviders(); + expect(screen.getAllByRole("spinbutton")).toHaveLength(3); + }); + + it("should offer a model picker per row", () => { + renderWithProviders(); + expect(screen.getAllByRole("combobox")).toHaveLength(1); + }); + + it("should remove a row when its delete button is clicked", async () => { + const user = userEvent.setup(); + renderWithProviders(); + + await user.click(screen.getByRole("button", { name: /add another model/i })); + const withTwoRows = dataRows(); + expect(withTwoRows).toHaveLength(2); + + await user.click(deleteButtonIn(withTwoRows[1])); + + expect(dataRows()).toHaveLength(1); }); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/index.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/index.tsx index 9b355e55c1c..f3bd74260ad 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/index.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/index.tsx @@ -1,6 +1,10 @@ import React, { useState, useCallback } from "react"; -import { Table, Select, InputNumber, Button, Radio } from "antd"; -import { DeleteOutlined, PlusOutlined } from "@ant-design/icons"; +import { Plus, Trash2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; +import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { SearchSelect } from "@/components/shared/SearchSelect"; import { PricingCalculatorProps, ModelEntry } from "./types"; import MultiCostResults from "./multi_cost_results"; import { useMultiCostEstimate } from "./use_multi_cost_estimate"; @@ -63,132 +67,115 @@ const PricingCalculator: React.FC = ({ accessToken, mode const multiModelResult = getMultiModelResult(entries); - const columns = [ - { - title: "Model", - dataIndex: "model", - key: "model", - width: "35%", - render: (_: string, record: ModelEntry) => ( - + handleEntryChange(record.id, "input_tokens", e.target.value === "" ? 0 : Number(e.target.value)) + } + /> + + + + handleEntryChange(record.id, "output_tokens", e.target.value === "" ? 0 : Number(e.target.value)) + } + /> + + + + handleEntryChange( + record.id, + requestsField, + e.target.value === "" ? undefined : Number(e.target.value), + ) + } + /> + + + + + + ))} + + + + + + + + +
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx index 04ef60469f0..b17dd2cb859 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx @@ -85,6 +85,14 @@ function emptyMultiResult(): MultiModelResult { }; } +const expandToggle = (): HTMLElement => screen.getByRole("button", { name: /cost breakdown for / }); + +const shownBreakdown = (): HTMLElement | null => { + const label = screen.queryByText("Total/Request"); + if (label === null) return null; + return label.closest("[style*='display: none']") === null ? label : null; +}; + describe("MultiCostResults", () => { beforeEach(() => { vi.clearAllMocks(); @@ -200,40 +208,78 @@ describe("MultiCostResults", () => { expect(screen.getByRole("button", { name: /export/i })).toBeInTheDocument(); }); + it("should render a column header for each summary column", () => { + renderWithProviders(); + + expect(screen.getByRole("columnheader", { name: "Model" })).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Per Request" })).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Margin Fee" })).toBeInTheDocument(); + expect(screen.getByRole("columnheader", { name: "Daily" })).toBeInTheDocument(); + }); + + it("should not show the model breakdown before the row is expanded", () => { + renderWithProviders(); + expect(shownBreakdown()).toBeNull(); + }); + it("should expand the model breakdown row when the expand button is clicked", async () => { const user = userEvent.setup(); renderWithProviders(); - // The expand column renders a button (RightOutlined icon) for rows without errors - const expandButtons = screen.getAllByRole("button"); - // Find the small expand button (not the Export button) - const expandButton = expandButtons.find((btn) => !btn.textContent?.toLowerCase().includes("export")); - expect(expandButton).toBeDefined(); + await user.click(expandToggle()); - await user.click(expandButton!); - - // After expanding, the SingleModelBreakdown should be visible - expect(screen.getByText("Total/Request")).toBeInTheDocument(); + expect(shownBreakdown()).toBeVisible(); + expect(screen.getByText("Daily Total (100 req)")).toBeInTheDocument(); }); - it("should show the collapse icon after expanding a row", async () => { + it("should collapse the model breakdown again on a second click", async () => { const user = userEvent.setup(); renderWithProviders(); - const getExpandButton = () => { - const allButtons = screen.getAllByRole("button"); - return allButtons.find((btn) => !btn.textContent?.toLowerCase().includes("export")); - }; + await user.click(expandToggle()); + expect(shownBreakdown()).toBeVisible(); - // Before expand: button has the "down" aria-label (RightOutlined renders as down in ant icons) - // Just verify clicking works and the breakdown content appears - await user.click(getExpandButton()!); - expect(screen.getByText("Total/Request")).toBeInTheDocument(); + await user.click(expandToggle()); + expect(shownBreakdown()).toBeNull(); + }); - // After a second click, the row collapses — content may be hidden or removed - await user.click(getExpandButton()!); - // The expanded content should no longer be visible - expect(screen.queryByText("Total/Request")).not.toBeVisible(); + it("should name the breakdown toggle and report its expanded state", async () => { + const user = userEvent.setup(); + renderWithProviders(); + + const toggle = screen.getByRole("button", { name: "Show cost breakdown for gpt-4" }); + expect(toggle).toHaveAttribute("aria-expanded", "false"); + + await user.click(toggle); + + const collapseToggle = screen.getByRole("button", { name: "Hide cost breakdown for gpt-4" }); + expect(collapseToggle).toHaveAttribute("aria-expanded", "true"); + }); + + it("should not offer an expand toggle for a row that failed", () => { + renderWithProviders( + , + ); + + expect(screen.getAllByRole("button", { name: /cost breakdown for / })).toHaveLength(1); }); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx index 3ea7ea58127..b8375b930c9 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx @@ -1,7 +1,11 @@ import React, { useState } from "react"; -import { Text, Button } from "@tremor/react"; -import { Card, Statistic, Row, Col, Divider, Spin, Table, Tag } from "antd"; -import { LoadingOutlined, DownOutlined, RightOutlined } from "@ant-design/icons"; +import { ChevronDown, ChevronRight } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Separator } from "@/components/ui/separator"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner"; import { CostEstimateResponse } from "../types"; import { formatNumberWithCommas } from "@/utils/dataUtils"; import { MultiModelResult } from "./types"; @@ -41,55 +45,57 @@ const SingleModelBreakdown: React.FC<{
{loading && (
- } size="small" /> + Updating...
)}
-
- Total/Request - {formatCost(result.cost_per_request)} +
+

Total/Request

+

{formatCost(result.cost_per_request)}

-
- Input Cost - {formatCost(result.input_cost_per_request)} +
+

Input Cost

+

{formatCost(result.input_cost_per_request)}

-
- Output Cost - {formatCost(result.output_cost_per_request)} +
+

Output Cost

+

{formatCost(result.output_cost_per_request)}

-
- Margin Fee - 0 ? "text-amber-600" : ""}`}> +
+

Margin Fee

+

0 ? "text-amber-600" : ""}`}> {formatCost(result.margin_cost_per_request)} - +

{periodCost !== null && (
-
- +
+

{periodLabel} Total ({formatRequests(periodRequests)} req) - - +

+

{formatCost(periodCost)} - +

-
- {periodLabel} Input - {formatCost(periodInputCost)} +
+

{periodLabel} Input

+

{formatCost(periodInputCost)}

-
- {periodLabel} Output - {formatCost(periodOutputCost)} +
+

{periodLabel} Output

+

{formatCost(periodOutputCost)}

-
- {periodLabel} Margin Fee - 0 ? "text-amber-600" : ""}`}> +
+

{periodLabel} Margin Fee

+

0 ? "text-amber-600" : ""}`}> {formatCost(periodMarginCost)} - +

)} @@ -124,7 +130,7 @@ const MultiCostResults: React.FC = ({ multiResult, timePe if (!hasAnyResult && !isAnyLoading && !hasAnyError) { return (
- Select models above to see cost estimates +

Select models above to see cost estimates

); } @@ -133,8 +139,8 @@ const MultiCostResults: React.FC = ({ multiResult, timePe if (!hasAnyResult && isAnyLoading && !hasAnyError) { return (
- } /> - Calculating costs... + +

Calculating costs...

); } @@ -143,10 +149,10 @@ const MultiCostResults: React.FC = ({ multiResult, timePe if (!hasAnyResult && hasAnyError) { return (
- +
- Cost Estimates - {isAnyLoading && } size="small" />} +

Cost Estimates

+ {isAnyLoading && }
{/* Error Messages */} {errorEntries.map((e) => ( @@ -174,102 +180,10 @@ const MultiCostResults: React.FC = ({ multiResult, timePe const hasMargin = multiResult.totals.margin_per_request > 0; const periodLabel = timePeriod === "day" ? "Daily" : "Monthly"; - const periodCostKey = timePeriod === "day" ? "daily_cost" : "monthly_cost"; - - const summaryColumns = [ - { - title: "Model", - dataIndex: "model", - key: "model", - render: ( - text: string, - record: { - id: string; - provider?: string | null; - error?: string | null; - loading?: boolean; - hasZeroCost?: boolean | null; - }, - ) => ( -
-
- {text} - {record.provider && ( - - {record.provider} - - )} - {record.loading && } size="small" />} -
- {record.error &&
⚠️ {record.error}
} - {record.hasZeroCost && !record.error && ( -
- ⚠️ No pricing data found for this model. Set base_model in config. -
- )} -
- ), - }, - { - title: "Per Request", - dataIndex: "cost_per_request", - key: "cost_per_request", - align: "right" as const, - render: (value: number | null, record: { error?: string | null }) => - record.error ? ( - - - ) : ( - {formatCost(value)} - ), - }, - { - title: "Margin Fee", - dataIndex: "margin_cost_per_request", - key: "margin_cost_per_request", - align: "right" as const, - render: (value: number | null, record: { error?: string | null }) => - record.error ? ( - - - ) : ( - 0 ? "text-amber-600" : "text-gray-400"}`}> - {formatCost(value)} - - ), - }, - { - title: periodLabel, - dataIndex: periodCostKey, - key: "period_cost", - align: "right" as const, - render: (value: number | null, record: { error?: string | null }) => - record.error ? ( - - - ) : ( - {formatCost(value)} - ), - }, - { - title: "", - key: "expand", - width: 40, - render: (_: unknown, record: { id: string; error?: string | null }) => - record.error ? null : ( - - ), - }, - ]; // Include both valid results and errors in the table data const allEntriesWithModels = multiResult.entries.filter((e) => e.entry.model); const summaryData = allEntriesWithModels.map((e) => ({ - key: e.entry.id, id: e.entry.id, model: e.result?.model || e.entry.model, provider: e.result?.provider, @@ -284,78 +198,153 @@ const MultiCostResults: React.FC = ({ multiResult, timePe return (
- +
- Cost Estimates +

Cost Estimates

- {isAnyLoading && } size="small" />} + {isAnyLoading && }
{/* Combined Totals - Always show when there are results */} - - - - Total Per Request} - value={formatCost(multiResult.totals.cost_per_request)} - valueStyle={{ color: "#1890ff", fontSize: "18px", fontFamily: "monospace" }} - /> - - - Total {periodLabel}} - value={formatCost(timePeriod === "day" ? multiResult.totals.daily_cost : multiResult.totals.monthly_cost)} - valueStyle={{ - color: timePeriod === "day" ? "#52c41a" : "#722ed1", - fontSize: "18px", - fontFamily: "monospace", - }} - /> - - + +
+
+ Total Per Request +
+ {formatCost(multiResult.totals.cost_per_request)} +
+
+
+ Total {periodLabel} +
+ {formatCost(timePeriod === "day" ? multiResult.totals.daily_cost : multiResult.totals.monthly_cost)} +
+
+
{hasMargin && ( - - +
+
Margin Fee/Request
-
+
{formatCost(multiResult.totals.margin_per_request)}
- - +
+
{periodLabel} Margin Fee
-
+
{formatCost(timePeriod === "day" ? multiResult.totals.daily_margin : multiResult.totals.monthly_margin)}
- - +
+
)} {/* Per-Model Table */} {summaryData.length > 0 && ( - { - const entry = validEntries.find((e) => e.entry.id === record.id); - if (!entry?.result) return null; +
+ + + Model + Per Request + Margin Fee + {periodLabel} + + Cost breakdown + + + + + {summaryData.map((record) => { + const isExpanded = expandedModels.has(record.id); + const periodCost = timePeriod === "day" ? record.daily_cost : record.monthly_cost; + const breakdownEntry = validEntries.find((e) => e.entry.id === record.id); return ( -
- -
+ + + +
+
+ {record.model} + {record.provider && ( + + {record.provider} + + )} + {record.loading && } +
+ {record.error && ( +
⚠️ {record.error}
+ )} + {record.hasZeroCost && !record.error && ( +
+ ⚠️ No pricing data found for this model. Set base_model in config. +
+ )} +
+
+ + {record.error ? ( + - + ) : ( + {formatCost(record.cost_per_request)} + )} + + + {record.error ? ( + - + ) : ( + 0 ? "text-amber-600" : "text-gray-400"}`} + > + {formatCost(record.margin_cost_per_request)} + + )} + + + {record.error ? ( + - + ) : ( + {formatCost(periodCost)} + )} + + + {!record.error && ( + + )} + +
+ {isExpanded && breakdownEntry?.result && ( + + +
+ +
+
+
+ )} +
); - }, - showExpandColumn: false, - }} - /> + })} +
+
)}
); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_discount_table.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_discount_table.test.tsx index f9a0a40f07d..24280873cf0 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_discount_table.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_discount_table.test.tsx @@ -5,49 +5,21 @@ import userEvent from "@testing-library/user-event"; import { renderWithProviders } from "../../../../../tests/test-utils"; import ProviderDiscountTable from "./provider_discount_table"; -vi.mock("@heroicons/react/outline", () => ({ - TrashIcon: function TrashIcon() { - return null; - }, - PencilAltIcon: function PencilAltIcon() { - return null; - }, - CheckIcon: function CheckIcon() { - return null; - }, - XIcon: function XIcon() { - return null; - }, -})); - -vi.mock("@tremor/react", () => ({ - Table: ({ children }: any) => {children}
, - TableHead: ({ children }: any) => {children}, - TableRow: ({ children }: any) => {children}, - TableHeaderCell: ({ children }: any) => {children}, - TableBody: ({ children }: any) => {children}, - TableCell: ({ children }: any) => {children}, - Text: ({ children }: any) => {children}, - TextInput: ({ value, onValueChange, onKeyDown, placeholder, ...rest }: any) => ( - onValueChange?.(e.target.value)} - onKeyDown={onKeyDown} - placeholder={placeholder} - {...rest} - /> - ), - Icon: ({ icon: IconComponent, onClick }: any) => { - const name = IconComponent?.displayName ?? IconComponent?.name ?? "icon"; - return + + + ) : ( + <> +

{(row.discount * 100).toFixed(1)}%

+ + + )} +
+ ); + }, width: "250px", }, { @@ -125,12 +138,15 @@ const ProviderDiscountTable: React.FC = ({ cell: (row) => { const { displayName } = getProviderLogoAndName(row.provider); return ( - onRemoveProvider(row.provider, displayName)} className="cursor-pointer hover:text-red-600" - /> + > + + ); }, width: "80px", diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_margin_table.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_margin_table.test.tsx index 170e61141b6..dd478571568 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_margin_table.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/provider_margin_table.test.tsx @@ -6,43 +6,15 @@ import { renderWithProviders } from "../../../../../tests/test-utils"; import ProviderMarginTable from "./provider_margin_table"; import { Providers, providerLogoMap } from "@/components/provider_info_helpers"; -vi.mock("@heroicons/react/outline", () => ({ - TrashIcon: function TrashIcon() { - return null; - }, - PencilAltIcon: function PencilAltIcon() { - return null; - }, - CheckIcon: function CheckIcon() { - return null; - }, - XIcon: function XIcon() { - return null; - }, -})); +const ROW_ACTION_NAME = { + edit: /^Edit margin for /, + save: /^Save margin for /, + cancel: /^Cancel editing margin for /, + remove: /^Remove margin for /, +} as const; -vi.mock("@tremor/react", () => ({ - Table: ({ children }: any) => {children}
, - TableHead: ({ children }: any) => {children}, - TableRow: ({ children }: any) => {children}, - TableHeaderCell: ({ children }: any) => {children}, - TableBody: ({ children }: any) => {children}, - TableCell: ({ children }: any) => {children}, - Text: ({ children }: any) => {children}, - TextInput: ({ value, onValueChange, placeholder, autoFocus, className }: any) => ( - onValueChange?.(e.target.value)} - placeholder={placeholder} - autoFocus={autoFocus} - className={className} - /> - ), - Icon: ({ icon: IconComponent, onClick }: any) => { - const name = IconComponent?.displayName ?? IconComponent?.name ?? "icon"; - return + + + ) : ( + <> +

{formatMargin(row.margin)}

+ + + )} +
+ ); + }, width: "350px", }, { header: "Actions", cell: (row) => { - const displayName = row.provider === "global" ? "Global" : getProviderLogoAndName(row.provider).displayName; + const displayName = marginRowDisplayName(row.provider); return ( - onRemoveProvider(row.provider, displayName)} className="cursor-pointer hover:text-red-600" - /> + > + + ); }, width: "80px",