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 models-and-endpoints to shadcn (#36648)
yuneng-jiang806564b14ce8
diff --git a/tests/e2e/ui/tests/modelsPage/responsiveHeader.spec.ts b/tests/e2e/ui/tests/modelsPage/responsiveHeader.spec.tsnew file mode 100644index 00000000000..6ad1ccb8451--- /dev/null+++ b/tests/e2e/ui/tests/modelsPage/responsiveHeader.spec.ts@@ -0,0 +1,33 @@+import { expect, test } from "@playwright/test";+import { ADMIN_STORAGE_PATH } from "../../constants";++test.describe("Models and Endpoints responsive header", () => {+ test.use({+ storageState: ADMIN_STORAGE_PATH,+ viewport: { width: 900, height: 720 },+ });++ test("keeps the refresh action on the same row as the tabs", async ({+ page,+ }) => {+ await page.goto("/ui");+ await page+ .getByRole("complementary")+ .getByRole("link", { name: "Models + Endpoints" })+ .click();++ const tabs = page.getByRole("tablist");+ const refresh = page.getByRole("button", { name: "Refresh models" });+ await expect(tabs).toBeVisible();+ await expect(refresh).toBeVisible();++ const tabsBox = await tabs.boundingBox();+ const refreshBox = await refresh.boundingBox();+ expect(tabsBox).not.toBeNull();+ expect(refreshBox).not.toBeNull();++ const tabsCenterY = tabsBox!.y + tabsBox!.height / 2;+ const refreshCenterY = refreshBox!.y + refreshBox!.height / 2;+ expect(Math.abs(tabsCenterY - refreshCenterY)).toBeLessThanOrEqual(2);+ });+});diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 0a7d87afd2f..86da17e8f19 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -1015,27 +1015,9 @@"count": 1}},- "src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.test.tsx": {- "react/display-name": {- "count": 1- }- },"src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx": {"no-nested-ternary": {"count": 1- },- "no-restricted-imports": {- "count": 2- }- },- "src/app/(dashboard)/models-and-endpoints/components/PriceDataManagementTab.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "src/app/(dashboard)/models-and-endpoints/page.tsx": {- "no-restricted-imports": {- "count": 1}},"src/app/(dashboard)/models-and-endpoints/panels/AddModelPanel.tsx": {@@ -2392,12 +2374,6 @@}},"src/components/add_model/RouterConfigBuilder.tsx": {- "no-restricted-imports": {- "count": 1- },- "react-hooks/purity": {- "count": 1- },"react-hooks/set-state-in-effect": {"count": 1}@@ -2434,9 +2410,6 @@"src/components/add_model/auto_router_connection_test.tsx": {"local/filename-pascal-case": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"src/components/add_model/cache_control_settings.tsx": {@@ -2501,9 +2474,6 @@},"no-nested-ternary": {"count": 2- },- "no-restricted-imports": {- "count": 1}},"src/components/add_model/provider_specific_fields.test.tsx": {@@ -2964,9 +2934,6 @@"src/components/key_value_input.tsx": {"local/filename-pascal-case": {"count": 1- },- "no-restricted-imports": {- "count": 2}},"src/components/leftnav.tsx": {@@ -3056,26 +3023,6 @@"count": 3}},- "src/components/model_add/CredentialsPanel.test.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "src/components/model_add/CredentialsPanel.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "src/components/model_add/credential_form_helpers.test.ts": {- "no-restricted-imports": {- "count": 1- }- },- "src/components/model_add/credential_form_helpers.ts": {- "no-restricted-imports": {- "count": 1- }- },"src/components/model_add/reuse_credentials.tsx": {"local/filename-pascal-case": {"count": 1@@ -3084,11 +3031,6 @@"count": 2}},- "src/components/model_dashboard/HealthCheckComponent.tsx": {- "no-restricted-imports": {- "count": 2- }- },"src/components/model_dashboard/ModelSettingsModal/ModelSettingsModal.tsx": {"no-restricted-imports": {"count": 1@@ -3308,12 +3250,6 @@"src/components/price_data_reload.tsx": {"local/filename-pascal-case": {"count": 1- },- "no-restricted-imports": {- "count": 1- },- "react-hooks/immutability": {- "count": 2}},"src/components/provider_info_helpers.tsx": {@@ -3338,17 +3274,11 @@"src/components/query_param_input.tsx": {"local/filename-pascal-case": {"count": 1- },- "no-restricted-imports": {- "count": 2}},"src/components/route_preview.tsx": {"local/filename-pascal-case": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"src/components/router_settings/LatencyBasedConfiguration.tsx": {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.test.tsxindex 13862094ba1..1d1af03dba6 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.test.tsx@@ -1,28 +1,8 @@-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import React from "react";import { describe, expect, it, vi } from "vitest";import ModelRetrySettingsTab from "./ModelRetrySettingsTab";-// TabPanel requires a parent Tabs context in Tremor. We stub it to render children-// directly so the component can be tested in isolation.-vi.mock("@tremor/react", async (importOriginal) => {- const actual = await importOriginal<typeof import("@tremor/react")>();- // Re-apply the global Button/Tooltip overrides from tests/setupTests.ts. A file-level- // vi.mock fully replaces the setup-level mock, so without this the real Tremor Button- // leaks through and its useTooltip(300) schedules a native setTimeout that can fire- // post-teardown -> "window is not defined".- return {- ...actual,- TabPanel: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),- Button: React.forwardRef<HTMLButtonElement, any>(({ children, variant, size, loading, ...props }, ref) =>- React.createElement("button", { ...props, ref }, children),- ),- Tooltip: ({ children }: { children?: React.ReactNode }) => React.createElement(React.Fragment, null, children),- // Keep Select/SelectItem as the real implementation so scope-switching is testable- };-});-type GlobalRetryPolicy = { [key: string]: number };type ModelGroupRetryPolicy = { [key: string]: { [key: string]: number } | undefined };@@ -71,7 +51,18 @@ describe("ModelRetrySettingsTab", () => {// All 6 spinbutton inputs should show the defaultRetry valueconst inputs = screen.getAllByRole("spinbutton");inputs.forEach((input) => {- expect(input).toHaveValue("3");+ expect(input).toHaveValue(3);+ });+ });++ it("should expose retry counts as nonnegative integer spinbuttons", () => {+ render(<ModelRetrySettingsTab {...buildProps()} />);++ screen.getAllByRole("spinbutton").forEach((input) => {+ expect(input).toHaveAttribute("type", "number");+ expect(input).toHaveAttribute("min", "0");+ expect(input).toHaveAttribute("step", "1");+ expect(input).toHaveAccessibleName(/retry count$/);});});@@ -84,10 +75,10 @@ describe("ModelRetrySettingsTab", () => {// The RateLimitError row is the 4th entry in the mapconst inputs = screen.getAllByRole("spinbutton");const rateLimitInput = inputs[3]; // 0-indexed: Bad(0), Auth(1), Timeout(2), Rate(3)- expect(rateLimitInput).toHaveValue("5");+ expect(rateLimitInput).toHaveValue(5);// Unset entries fall back to defaultRetry (0)- expect(inputs[0]).toHaveValue("0");+ expect(inputs[0]).toHaveValue(0);});it("should leave model-scope rows empty with the inherited value as placeholder when there is no override", () => {@@ -109,9 +100,9 @@ describe("ModelRetrySettingsTab", () => {// a placeholder -- this is what keeps 0 ("zero retries") distinct from// "inherit the global value".const inputs = screen.getAllByRole("spinbutton");- expect(inputs[2]).toHaveValue(""); // TimeoutError row+ expect(inputs[2]).toHaveValue(null); // TimeoutError rowexpect(inputs[2]).toHaveAttribute("placeholder", "7"); // inherited from global- expect(inputs[0]).toHaveValue(""); // BadRequestError row (no global)+ expect(inputs[0]).toHaveValue(null); // BadRequestError row (no global)expect(inputs[0]).toHaveAttribute("placeholder", "1"); // inherited from defaultRetry});@@ -140,6 +131,61 @@ describe("ModelRetrySettingsTab", () => {expect(result["gpt-4"]).not.toHaveProperty("BadRequestErrorRetries");});+ it("should clear a model-group override when its input is emptied", async () => {+ const user = userEvent.setup();+ const setModelGroupRetryPolicy = vi.fn();+ const overrides = {+ selectedModelGroup: "gpt-4",+ modelGroupRetryPolicy: { "gpt-4": { BadRequestErrorRetries: 5 } },+ setModelGroupRetryPolicy,+ defaultRetry: 0,+ };+ render(<ModelRetrySettingsTab {...buildProps(overrides)} />);++ await user.clear(screen.getAllByRole("spinbutton")[0]);++ const updater = setModelGroupRetryPolicy.mock.calls.at(-1)![0];+ const result = updater({ "gpt-4": { BadRequestErrorRetries: 5 } });+ expect(result["gpt-4"]).not.toHaveProperty("BadRequestErrorRetries");+ });++ it.each(["abc", "-1", "1.5"])("should reject an invalid retry count of %s", (invalidValue) => {+ const setGlobalRetryPolicy = vi.fn();+ render(+ <ModelRetrySettingsTab+ {...buildProps({+ selectedModelGroup: "global",+ globalRetryPolicy: { BadRequestErrorRetries: 0 },+ setGlobalRetryPolicy,+ })}+ />,+ );++ const input = screen.getAllByRole("spinbutton")[0];+ input.setAttribute("type", "text");+ fireEvent.change(input, { target: { value: invalidValue } });++ expect(setGlobalRetryPolicy).not.toHaveBeenCalled();+ });++ it("should accept zero as a retry count", () => {+ const setGlobalRetryPolicy = vi.fn();+ render(+ <ModelRetrySettingsTab+ {...buildProps({+ selectedModelGroup: "global",+ globalRetryPolicy: { BadRequestErrorRetries: 3 },+ setGlobalRetryPolicy,+ })}+ />,+ );++ fireEvent.change(screen.getAllByRole("spinbutton")[0], { target: { value: "0" } });++ const updater = setGlobalRetryPolicy.mock.calls.at(-1)![0];+ expect(updater({ BadRequestErrorRetries: 3 })).toMatchObject({ BadRequestErrorRetries: 0 });+ });+it("should disable the Save button while a save is in flight", () => {render(<ModelRetrySettingsTab {...buildProps({ isSaving: true })} />);@@ -166,7 +212,7 @@ describe("ModelRetrySettingsTab", () => {// The model-specific value (9) should win over global (3)const inputs = screen.getAllByRole("spinbutton");- expect(inputs[3]).toHaveValue("9");+ expect(inputs[3]).toHaveValue(9);});it("should show the global reference value text for each row in model-specific scope", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsxindex a4e3c4b958c..c55daeda593 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/ModelRetrySettingsTab.tsx@@ -1,7 +1,11 @@-import { Button, Select, SelectItem, Text, Title } from "@tremor/react";-import { InputNumber } from "antd";+import { LoaderCircle } from "lucide-react";import React from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+interface GlobalRetryPolicyObject {[retryPolicyKey: string]: number;}@@ -32,6 +36,8 @@ const retryPolicyMap: Record<string, string> = {"InternalServerError (500)": "InternalServerErrorRetries",};+const isValidRetryCount = (value: number) => Number.isFinite(value) && Number.isInteger(value) && value >= 0;+const ModelRetrySettingsTab = ({selectedModelGroup,setSelectedModelGroup,@@ -63,63 +69,80 @@ const ModelRetrySettingsTab = ({});};+ const handleRetryCountChange = (retryPolicyKey: string, rawValue: string) => {+ const value = rawValue === "" ? null : Number(rawValue);+ if (value !== null && !isValidRetryCount(value)) return;+ if (isGlobalScope) setGlobalValue(retryPolicyKey, value);+ else setModelOverride(retryPolicyKey, value);+ };+return (- <div>- <div className="flex items-center gap-4 mb-6">- <div className="flex items-center">- <Text>Retry Policy Scope:</Text>+ <div className="space-y-6">+ <div className="flex items-center gap-3">+ <Label htmlFor="retry-policy-scope">Retry Policy Scope:</Label>+ <div className="w-48"><Select- className="ml-2 w-48"value={isGlobalScope ? "global" : selectedModelGroup || availableModelGroups[0]}onValueChange={(value) => setSelectedModelGroup(value)}>- <SelectItem value="global">Global Default</SelectItem>- {availableModelGroups.map((group, idx) => (- <SelectItem key={idx} value={group}>- {group}- </SelectItem>- ))}+ <SelectTrigger id="retry-policy-scope" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="global">Global Default</SelectItem>+ {availableModelGroups.map((group) => (+ <SelectItem key={group} value={group}>+ {group}+ </SelectItem>+ ))}+ </SelectContent></Select></div></div>{isGlobalScope ? (- <>- <Title>Global Retry Policy</Title>- <Text className="mb-6">Default retry settings applied to all model groups unless overridden</Text>- </>+ <div>+ <h2 className="text-lg font-semibold">Global Retry Policy</h2>+ <p className="text-sm text-muted-foreground">+ Default retry settings applied to all model groups unless overridden+ </p>+ </div>) : (- <>- <Title>Retry Policy for {selectedModelGroup}</Title>- <Text className="mb-6">Model-specific retry settings. Falls back to global defaults if not set.</Text>- </>+ <div>+ <h2 className="text-lg font-semibold">Retry Policy for {selectedModelGroup}</h2>+ <p className="text-sm text-muted-foreground">+ Model-specific retry settings. Falls back to global defaults if not set.+ </p>+ </div>)}- <table>+ <table className="w-full"><tbody>- {Object.entries(retryPolicyMap).map(([exceptionType, retryPolicyKey], idx) => {+ {Object.entries(retryPolicyMap).map(([exceptionType, retryPolicyKey]) => {const inheritedValue = globalRetryPolicy?.[retryPolicyKey] ?? defaultRetry;const override = isGlobalScope ? undefined : modelGroupRetryPolicy?.[selectedModelGroup!]?.[retryPolicyKey];const hasOverride = override != null;return (- <tr key={idx} className="flex justify-between items-center mt-2">- <td>- <Text>{exceptionType}</Text>- {!isGlobalScope && <Text className="text-xs text-gray-500 ml-2">(Global: {inheritedValue})</Text>}+ <tr key={retryPolicyKey} className="flex items-center justify-between gap-4 border-b py-2 last:border-0">+ <td className="text-sm">+ <span>{exceptionType}</span>+ {!isGlobalScope && (+ <span className="ml-2 text-xs text-muted-foreground">(Global: {inheritedValue})</span>+ )}</td><td className="flex items-center gap-2">- <InputNumber- className="ml-5"- value={isGlobalScope ? inheritedValue : hasOverride ? override : null}- placeholder={isGlobalScope ? undefined : String(inheritedValue)}+ <Input+ className="w-28"+ type="number"+ aria-label={`${exceptionType} retry count`}min={0}step={1}- onChange={(value) =>- isGlobalScope ? setGlobalValue(retryPolicyKey, value) : setModelOverride(retryPolicyKey, value)- }+ value={isGlobalScope ? inheritedValue : hasOverride ? override : ""}+ placeholder={isGlobalScope ? undefined : String(inheritedValue)}+ onChange={(event) => handleRetryCountChange(retryPolicyKey, event.currentTarget.value)}/>{!isGlobalScope && hasOverride && (- <Button variant="light" size="xs" onClick={() => setModelOverride(retryPolicyKey, null)}>+ <Button variant="ghost" size="xs" onClick={() => setModelOverride(retryPolicyKey, null)}>Reset</Button>)}@@ -129,7 +152,8 @@ const ModelRetrySettingsTab = ({})}</tbody></table>- <Button className="mt-6 mr-8" onClick={handleSaveRetrySettings} loading={isSaving} disabled={isSaving}>+ <Button onClick={handleSaveRetrySettings} disabled={isSaving}>+ {isSaving && <LoaderCircle className="animate-spin" />}Save</Button></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/PriceDataManagementTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/PriceDataManagementTab.tsxindex 9420643578c..126f6970c2e 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/PriceDataManagementTab.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/components/PriceDataManagementTab.tsx@@ -1,4 +1,3 @@-import { Text, Title } from "@tremor/react";import PriceDataReload from "@/components/price_data_reload";import React from "react";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";@@ -12,10 +11,10 @@ const PriceDataManagementTab = () => {<div><div className="p-6"><div className="mb-6">- <Title>Price Data Management</Title>- <Text className="text-tremor-content">+ <h2 className="text-lg font-semibold">Price Data Management</h2>+ <p className="text-sm text-muted-foreground">Manage model pricing data and configure automatic reload schedules- </Text>+ </p></div><PriceDataReloadaccessToken={accessToken}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/page.tsxindex 22ffb6d6cc8..3fd4f0f8019 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/page.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/page.tsx@@ -1,8 +1,7 @@"use client";import { useMemo, useState } from "react";-import { Tabs } from "antd";-import { RefreshIcon } from "@heroicons/react/outline";+import { RefreshCw } from "lucide-react";import { useQueryClient } from "@tanstack/react-query";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";@@ -24,6 +23,8 @@ import HealthStatusPanel from "@/app/(dashboard)/models-and-endpoints/panels/Heaimport ModelRetrySettingsPanel from "@/app/(dashboard)/models-and-endpoints/panels/ModelRetrySettingsPanel";import ModelGroupAliasPanel from "@/app/(dashboard)/models-and-endpoints/panels/ModelGroupAliasPanel";import PriceDataPanel from "@/app/(dashboard)/models-and-endpoints/panels/PriceDataPanel";+import { Button } from "@/components/ui/button";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";type ModelTabSlug =| "add"@@ -108,7 +109,6 @@ export default function ModelsAndEndpointsPage() {);const allModelsLabel = isAdmin ? "All Models" : "Your Models";- // Auto-Routers carries a Beta badge; BetaBadge honours the admin setting that hides these.const tabLabel = (slug: "" | ModelTabSlug): React.ReactNode => {if (!slug) return allModelsLabel;if (slug === "auto-routers") {@@ -121,15 +121,6 @@ export default function ModelsAndEndpointsPage() {return TAB_LABELS[slug];};- const tabItems = visibleSlugs.map((slug) => {- const key = slug || BASE_TAB_KEY;- return {- key,- label: tabLabel(slug),- children: key === activeKey ? renderPanel(key) : null,- };- });-const handleRefreshClick = () => {setLastRefreshed(new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }));queryClient.invalidateQueries({ queryKey: ["models", "list"] });@@ -156,15 +147,15 @@ export default function ModelsAndEndpointsPage() {}return (- <div className="mx-4 h-[75vh]">- <div className="flex flex-col gap-2 p-8 w-full mt-2">- <div className="flex justify-between items-center mb-4">+ <div className="mx-4">+ <div className="mt-2 flex w-full flex-col gap-2 p-8">+ <div className="mb-4 flex items-center justify-between"><div><h2 className="text-lg font-semibold">Model Management</h2>{isAdmin ? (- <p className="text-sm text-gray-600">Add and manage models for the proxy</p>+ <p className="text-sm text-muted-foreground">Add and manage models for the proxy</p>) : (- <p className="text-sm text-gray-600">Add models for teams you are an admin for.</p>+ <p className="text-sm text-muted-foreground">Add models for teams you are an admin for.</p>)}</div></div>@@ -182,26 +173,36 @@ export default function ModelsAndEndpointsPage() {modelAccessGroups={availableModelAccessGroups}/>) : (- <Tabs- activeKey={activeKey}- onChange={setActiveKey}- items={tabItems}- tabBarExtraContent={{- right: (- <div className="flex items-center space-x-2 self-center">- {lastRefreshed && <span className="text-xs text-gray-500">Last Refreshed: {lastRefreshed}</span>}- <button- type="button"- onClick={handleRefreshClick}- aria-label="Refresh models"- className="cursor-pointer"- >- <RefreshIcon className="h-4 w-4 text-gray-500" />- </button>- </div>- ),- }}- />+ <Tabs value={activeKey} onValueChange={setActiveKey}>+ <div className="flex min-w-0 flex-nowrap items-center gap-3 border-b">+ <TabsList variant="line" className="min-w-0 flex-1 justify-start overflow-x-auto">+ {visibleSlugs.map((slug) => {+ const key = slug || BASE_TAB_KEY;+ return (+ <TabsTrigger key={key} value={key} className="flex-none">+ {tabLabel(slug)}+ </TabsTrigger>+ );+ })}+ </TabsList>+ <div className="flex shrink-0 items-center gap-2 pb-1">+ {lastRefreshed && (+ <span className="text-xs text-muted-foreground">Last Refreshed: {lastRefreshed}</span>+ )}+ <Button variant="ghost" size="icon-sm" onClick={handleRefreshClick} aria-label="Refresh models">+ <RefreshCw />+ </Button>+ </div>+ </div>+ {visibleSlugs.map((slug) => {+ const key = slug || BASE_TAB_KEY;+ return (+ <TabsContent key={key} value={key} className="pt-4">+ {renderPanel(key)}+ </TabsContent>+ );+ })}+ </Tabs>)}</div></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.test.tsnew file mode 100644index 00000000000..a1225ea84b0--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.test.ts@@ -0,0 +1,51 @@+import { waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import NotificationsManager from "@/components/molecules/notifications_manager";++import { vertexCredentialsUploadProps } from "./vertexCredentialsUpload";++vi.mock("@/components/molecules/notifications_manager", () => ({+ default: { success: vi.fn(), fromBackend: vi.fn() },+}));++const makeForm = () => ({ setFieldsValue: vi.fn() });++describe("vertexCredentialsUploadProps", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("reads a JSON credential file into the vertex_credentials field without uploading it", async () => {+ const form = makeForm();+ const props = vertexCredentialsUploadProps(form as never);+ const file = new File(['{"project_id":"example"}'], "vertex.json", { type: "application/json" });++ expect(props.beforeUpload?.(file as never, [file] as never)).toBe(false);++ await waitFor(() => {+ expect(form.setFieldsValue).toHaveBeenCalledWith({ vertex_credentials: '{"project_id":"example"}' });+ });+ });++ it("ignores non-JSON files", async () => {+ const form = makeForm();+ const props = vertexCredentialsUploadProps(form as never);+ const file = new File(["not json"], "vertex.txt", { type: "text/plain" });++ expect(props.beforeUpload?.(file as never, [file] as never)).toBe(false);++ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(form.setFieldsValue).not.toHaveBeenCalled();+ });++ it("reports completed and failed upload states", () => {+ const props = vertexCredentialsUploadProps(makeForm() as never);++ props.onChange?.({ file: { name: "vertex.json", status: "done" } } as never);+ props.onChange?.({ file: { name: "vertex.json", status: "error" } } as never);++ expect(NotificationsManager.success).toHaveBeenCalledWith("vertex.json file uploaded successfully");+ expect(NotificationsManager.fromBackend).toHaveBeenCalledWith("vertex.json file upload failed.");+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.ts b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.tsindex 61bfbd7a99f..1ec9807e6d5 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/vertexCredentialsUpload.ts@@ -1,7 +1,15 @@-import type { FormInstance, UploadProps } from "antd";+import type { ComponentProps } from "react";+import NotificationsManager from "@/components/molecules/notifications_manager";+import type CredentialsPanel from "@/components/model_add/CredentialsPanel";++interface VertexCredentialsForm {+ setFieldsValue: (values: { vertex_credentials: string }) => void;+}++type UploadProps = ComponentProps<typeof CredentialsPanel>["uploadProps"];-export function vertexCredentialsUploadProps(form: FormInstance): UploadProps {+export function vertexCredentialsUploadProps(form: VertexCredentialsForm): UploadProps {return {name: "file",accept: ".json",diff --git a/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.test.tsx b/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.test.tsxindex 2270d85ca0a..9932e812815 100644--- a/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.test.tsx@@ -194,6 +194,41 @@ describe("RouterConfigBuilder", () => {});});+ it("should preserve commas inside a single utterance", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const value = {+ routes: [{ name: "gpt-4", utterances: [], description: "", score_threshold: 0.5 }],+ };+ render(<RouterConfigBuilder modelInfo={MOCK_MODEL_INFO} value={value} onChange={onChange} />);++ const utteranceInput = await screen.findByRole("textbox", { name: "Example Utterances" });+ await user.type(utteranceInput, "Compare Paris, France{Enter}");++ await waitFor(() => {+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1];+ expect(lastCall[0].routes[0].utterances).toEqual(["Compare Paris, France"]);+ });+ });++ it("should deduplicate utterances within a multiline paste", async () => {+ const onChange = vi.fn();+ const value = {+ routes: [{ name: "gpt-4", utterances: ["hello"], description: "", score_threshold: 0.5 }],+ };+ render(<RouterConfigBuilder modelInfo={MOCK_MODEL_INFO} value={value} onChange={onChange} />);++ const utteranceInput = await screen.findByRole("textbox", { name: "Example Utterances" });+ fireEvent.paste(utteranceInput, {+ clipboardData: { getData: () => "hello\nworld\nworld" },+ });++ await waitFor(() => {+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1];+ expect(lastCall[0].routes[0].utterances).toEqual(["hello", "world"]);+ });+ });+it("should add multiple routes", async () => {const user = userEvent.setup();render(<RouterConfigBuilder modelInfo={MOCK_MODEL_INFO} />);@@ -207,26 +242,26 @@ describe("RouterConfigBuilder", () => {it("should toggle JSON preview visibility", async () => {const user = userEvent.setup();- const { container } = render(<RouterConfigBuilder modelInfo={MOCK_MODEL_INFO} />);+ render(<RouterConfigBuilder modelInfo={MOCK_MODEL_INFO} />);expect(screen.getByText("JSON Preview")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Show" })).toBeInTheDocument();- expect(container.querySelector("pre")).not.toBeInTheDocument();+ expect(screen.queryByText(/"routes":/)).not.toBeInTheDocument();await user.click(screen.getByRole("button", { name: "Show" }));expect(screen.getByRole("button", { name: "Hide" })).toBeInTheDocument();- expect(container.querySelector("pre")).toBeInTheDocument();+ expect(screen.getByText(/"routes":/)).toBeInTheDocument();await user.click(screen.getByRole("button", { name: "Hide" }));expect(screen.getByRole("button", { name: "Show" })).toBeInTheDocument();- expect(container.querySelector("pre")).not.toBeInTheDocument();+ expect(screen.queryByText(/"routes":/)).not.toBeInTheDocument();});it("should display JSON preview with route data when routes exist", async () => {const user = userEvent.setup();- const { container } = render(+ render(<RouterConfigBuildermodelInfo={MOCK_MODEL_INFO}value={{@@ -241,11 +276,9 @@ describe("RouterConfigBuilder", () => {await user.click(screen.getByRole("button", { name: "Show" }));- const preElement = container.querySelector("pre");- expect(preElement).toBeInTheDocument();- expect(preElement?.textContent).toContain("gpt-4");- expect(preElement?.textContent).toContain("hello");- expect(preElement?.textContent).toContain("0.8");+ const preview = screen.getByText(/"name": "gpt-4"/);+ expect(preview).toHaveTextContent('"utterances": [ "hello" ]');+ expect(preview).toHaveTextContent('"score_threshold": 0.8');});it("should display model selector with options from modelInfo", async () => {diff --git a/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.tsx b/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.tsxindex b28d402f116..6dfb9f32091 100644--- a/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.tsx+++ b/ui/litellm-dashboard/src/components/add_model/RouterConfigBuilder.tsx@@ -1,24 +1,17 @@-import { DeleteOutlined, InfoCircleOutlined, PlusOutlined } from "@ant-design/icons";-import {- Select as AntdSelect,- Button,- Card,- Collapse,- Divider,- Empty,- Flex,- Input,- InputNumber,- Space,- Tooltip,- Typography,-} from "antd";import React, { useEffect, useState } from "react";-import { ModelGroup } from "@/components/llm_calls/fetch_models";--const { Text } = Typography;+import { ChevronDown, CircleHelp, Plus, Trash2, X } from "lucide-react";-const { TextArea } = Input;+import { ModelGroup } from "@/components/llm_calls/fetch_models";+import { SearchSelect } from "@/components/shared/SearchSelect";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Card, CardContent } from "@/components/ui/card";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Separator } from "@/components/ui/separator";+import { Textarea } from "@/components/ui/textarea";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";interface Route {id: string;@@ -47,31 +40,109 @@ interface RouterConfigBuilderProps {onChange?: (config: any) => void;}+interface UtteranceInputProps {+ value: string[];+ onChange: (utterances: string[]) => void;+}++const UtteranceInput = ({ value, onChange }: UtteranceInputProps) => {+ const [draft, setDraft] = useState("");++ const addUtterances = (input: string) => {+ const normalizedUtterances = input+ .split("\n")+ .map((utterance) => utterance.trim())+ .filter((utterance) => utterance !== "");+ const updatedUtterances = Array.from(new Set([...value, ...normalizedUtterances]));++ if (updatedUtterances.length > value.length) {+ onChange(updatedUtterances);+ }+ setDraft("");+ };++ return (+ <div className="flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2.5 py-1.5 shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30">+ {value.map((utterance) => (+ <Badge key={utterance} variant="secondary" className="max-w-full gap-1 pr-1">+ <span className="truncate">{utterance}</span>+ <button+ type="button"+ aria-label={`Remove ${utterance}`}+ className="rounded-full p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"+ onClick={() => onChange(value.filter((item) => item !== utterance))}+ >+ <X className="size-3" />+ </button>+ </Badge>+ ))}+ <input+ aria-label="Example Utterances"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => draft.trim() && addUtterances(draft)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && draft.trim()) {+ event.preventDefault();+ addUtterances(draft);+ } else if (event.key === "Backspace" && draft === "" && value.length > 0) {+ onChange(value.slice(0, -1));+ }+ }}+ onPaste={(event) => {+ const pastedText = event.clipboardData.getData("text");+ if (pastedText.includes("\n")) {+ event.preventDefault();+ addUtterances(pastedText);+ }+ }}+ placeholder={value.length === 0 ? "Type an utterance and press Enter..." : undefined}+ className="min-w-48 flex-1 bg-transparent py-0.5 text-sm outline-none placeholder:text-muted-foreground"+ />+ </div>+ );+};++const HelpTooltip = ({ content }: { content: string }) => (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label={content}+ className="inline-flex rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ }+ >+ <CircleHelp className="size-4" />+ </TooltipTrigger>+ <TooltipContent>{content}</TooltipContent>+ </Tooltip>+);+const RouterConfigBuilder: React.FC<RouterConfigBuilderProps> = ({ modelInfo, value, onChange }) => {const [routes, setRoutes] = useState<Route[]>([]);- const [showJsonPreview, setShowJsonPreview] = useState<boolean>(false);+ const [showJsonPreview, setShowJsonPreview] = useState(false);const [expandedRoutes, setExpandedRoutes] = useState<string[]>([]);- // Initialize routes from value prop - preserve existing route IDs to avoid focus loss when parent re-rendersuseEffect(() => {const routesFromValue = value?.routes;if (routesFromValue) {const routeIds: string[] = [];- setRoutes((prevRoutes) => {- const initializedRoutes = routesFromValue.map((route: SavedRoute, index: number) => {+ setRoutes((prevRoutes) =>+ routesFromValue.map((route: SavedRoute, index: number) => {const existingRoute = prevRoutes[index];const id = existingRoute?.id || route.id || `route-${index}-${Date.now()}`;routeIds.push(id);return {id,- model: route.name || route.model || "", // handle both 'name' and 'model' fields+ model: route.name || route.model || "",utterances: route.utterances || [],description: route.description || "",score_threshold: route.score_threshold ?? 0.5,};- });- return initializedRoutes;- });+ }),+ );setExpandedRoutes(routeIds);} else {setRoutes([]);@@ -79,205 +150,188 @@ const RouterConfigBuilder: React.FC<RouterConfigBuilderProps> = ({ modelInfo, va}}, [value]);- // Handle adding a new route+ const updateConfig = (updatedRoutes: Route[]) => {+ onChange?.({+ routes: updatedRoutes.map((route) => ({+ name: route.model,+ utterances: route.utterances,+ description: route.description,+ score_threshold: route.score_threshold,+ })),+ });+ };+const addRoute = () => {const newRouteId = `route-${Date.now()}`;- const newRoute: Route = {- id: newRouteId,- model: "",- utterances: [],- description: "",- score_threshold: 0.5,- };- const updatedRoutes = [...routes, newRoute];+ const updatedRoutes = [+ ...routes,+ { id: newRouteId, model: "", utterances: [], description: "", score_threshold: 0.5 },+ ];setRoutes(updatedRoutes);updateConfig(updatedRoutes);- // Automatically expand the new route- setExpandedRoutes((prev) => [...prev, newRouteId]);+ setExpandedRoutes((previous) => [...previous, newRouteId]);};- // Handle removing a routeconst removeRoute = (routeId: string) => {const updatedRoutes = routes.filter((route) => route.id !== routeId);setRoutes(updatedRoutes);updateConfig(updatedRoutes);- // Remove from expanded routes as well- setExpandedRoutes((prev) => prev.filter((id) => id !== routeId));+ setExpandedRoutes((previous) => previous.filter((id) => id !== routeId));};- // Handle updating a route- const updateRoute = (routeId: string, field: keyof Route, value: any) => {- const updatedRoutes = routes.map((route) => (route.id === routeId ? { ...route, [field]: value } : route));+ const updateRoute = (routeId: string, field: keyof Route, fieldValue: Route[keyof Route]) => {+ const updatedRoutes = routes.map((route) => (route.id === routeId ? { ...route, [field]: fieldValue } : route));setRoutes(updatedRoutes);updateConfig(updatedRoutes);};- // Update the overall configuration- const updateConfig = (updatedRoutes: Route[]) => {- const config = {- routes: updatedRoutes.map((route) => ({- name: route.model,- utterances: route.utterances,- description: route.description,- score_threshold: route.score_threshold,- })),- };- onChange?.(config);- };-- // Handle utterances change (convert textarea string to array)-- // Prepare model options for dropdowns- const modelOptions = modelInfo.map((model) => ({- value: model.model_group,- label: model.model_group,- }));-- const generateConfig = () => {- return {- routes: routes.map((route) => ({- name: route.model,- utterances: route.utterances,- description: route.description,- score_threshold: route.score_threshold,- })),- };+ const modelOptions = modelInfo.map((model) => ({ value: model.model_group, label: model.model_group }));+ const generatedConfig = {+ routes: routes.map((route) => ({+ name: route.model,+ utterances: route.utterances,+ description: route.description,+ score_threshold: route.score_threshold,+ })),};return (- <div className="w-full max-w-none">- <Flex justify="space-between" align="center" gap="middle" style={{ width: "100%", marginBottom: 24 }}>- <Space align="center">- <Typography.Title level={4} style={{ margin: 0 }}>- Routes Configuration- </Typography.Title>- <Tooltip title="Configure routing logic to automatically select the best model based on user input patterns">- <InfoCircleOutlined className="text-gray-400" />- </Tooltip>- </Space>- <Button type="primary" icon={<PlusOutlined />} onClick={addRoute} className="bg-blue-600 hover:bg-blue-700">- Add Route- </Button>- </Flex>+ <TooltipProvider>+ <div className="w-full space-y-6">+ <div className="flex w-full flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <h3 className="text-lg font-semibold">Routes Configuration</h3>+ <HelpTooltip content="Configure routing logic to automatically select the best model based on user input patterns" />+ </div>+ <Button type="button" onClick={addRoute}>+ <Plus data-icon="inline-start" />+ Add Route+ </Button>+ </div>++ {routes.length === 0 ? (+ <Card>+ <CardContent className="py-8 text-center text-muted-foreground">+ No routes configured. Click "Add Route" to get started.+ </CardContent>+ </Card>+ ) : (+ <div className="space-y-3">+ {routes.map((route, index) => {+ const isExpanded = expandedRoutes.includes(route.id);+ return (+ <Collapsible+ key={route.id}+ open={isExpanded}+ onOpenChange={(open) =>+ setExpandedRoutes((previous) =>+ open ? [...previous, route.id] : previous.filter((id) => id !== route.id),+ )+ }+ className="overflow-hidden rounded-xl border bg-card shadow-xs"+ >+ <div className="flex items-center gap-2 px-4 py-3">+ <CollapsibleTrigger+ render={<button type="button" className="flex min-w-0 flex-1 items-center gap-2 text-left" />}+ >+ <ChevronDown+ className={`size-4 shrink-0 text-muted-foreground transition-transform ${isExpanded ? "rotate-180" : ""}`}+ />+ <span className="truncate text-base font-medium">+ Route {index + 1}: {route.model || "Unnamed"}+ </span>+ </CollapsibleTrigger>+ <Button+ type="button"+ aria-label="delete"+ variant="ghost"+ size="icon-sm"+ onClick={() => removeRoute(route.id)}+ >+ <Trash2 className="text-destructive" />+ </Button>+ </div>+ <CollapsibleContent>+ <Separator />+ <div className="space-y-4 p-4">+ <div className="space-y-2">+ <Label>Model</Label>+ <SearchSelect+ value={route.model}+ onValueChange={(model) => updateRoute(route.id, "model", model)}+ placeholder="Select model"+ options={modelOptions}+ />+ </div>- {/* Routes */}- {routes.length === 0 ? (- <Card>- <Empty description='No routes configured. Click "Add Route" to get started.' />- </Card>- ) : (- <Collapse- activeKey={expandedRoutes}- onChange={(keys) => setExpandedRoutes(Array.isArray(keys) ? keys : [keys].filter(Boolean))}- style={{ width: "100%" }}- items={routes.map((route, index) => ({- key: route.id,- label: (- <Text style={{ fontSize: 16 }}>- Route {index + 1}: {route.model || "Unnamed"}- </Text>- ),- extra: (- <Button- type="text"- danger- size="small"- icon={<DeleteOutlined />}- onClick={(e) => {- e.stopPropagation();- removeRoute(route.id);- }}- />- ),- children: (- <Card key={route.id}>- {/* Model Selection */}- <div className="mb-4 w-full">- <Text className="text-sm font-medium mb-2 block">Model</Text>- <AntdSelect- value={route.model}- onChange={(value) => updateRoute(route.id, "model", value)}- placeholder="Select model"- showSearch- style={{ width: "100%" }}- options={modelOptions}- />- </div>+ <div className="space-y-2">+ <Label htmlFor={`${route.id}-description`}>Description</Label>+ <Textarea+ id={`${route.id}-description`}+ value={route.description}+ onChange={(event) => updateRoute(route.id, "description", event.target.value)}+ placeholder="Describe when this route should be used..."+ rows={2}+ />+ </div>- {/* Description */}- <div className="mb-4 w-full">- <Text className="text-sm font-medium mb-2 block">Description</Text>- <TextArea- value={route.description}- onChange={(e) => updateRoute(route.id, "description", e.target.value)}- placeholder="Describe when this route should be used..."- rows={2}- style={{ width: "100%" }}- />- </div>+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <Label htmlFor={`${route.id}-threshold`}>Score Threshold</Label>+ <HelpTooltip content="Minimum similarity score to route to this model (0-1)" />+ </div>+ <Input+ id={`${route.id}-threshold`}+ type="number"+ value={route.score_threshold}+ onChange={(event) =>+ updateRoute(route.id, "score_threshold", Number(event.target.value) || 0)+ }+ min={0}+ max={1}+ step={0.1}+ placeholder="0.5"+ />+ </div>- {/* Score Threshold */}- <div className="mb-4 w-full">- <div className="flex items-center gap-2 mb-2">- <Text className="text-sm font-medium">Score Threshold</Text>- <Tooltip title="Minimum similarity score to route to this model (0-1)">- <InfoCircleOutlined className="text-gray-400" />- </Tooltip>- </div>- <InputNumber- value={route.score_threshold}- onChange={(value) => updateRoute(route.id, "score_threshold", value || 0)}- min={0}- max={1}- step={0.1}- style={{ width: "100%" }}- placeholder="0.5"- />- </div>+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <Label>Example Utterances</Label>+ <HelpTooltip content="Training examples for this route. Type an utterance and press Enter to add it." />+ </div>+ <p className="text-xs text-muted-foreground">+ Type an utterance and press Enter to add it. You can also paste multiple lines.+ </p>+ <UtteranceInput+ value={route.utterances}+ onChange={(utterances) => updateRoute(route.id, "utterances", utterances)}+ />+ </div>+ </div>+ </CollapsibleContent>+ </Collapsible>+ );+ })}+ </div>+ )}- {/* Example Utterances */}- <div className="w-full">- <div className="flex items-center gap-2 mb-2">- <Text className="text-sm font-medium">Example Utterances</Text>- <Tooltip title="Training examples for this route. Type an utterance and press Enter to add it.">- <InfoCircleOutlined className="text-gray-400" />- </Tooltip>- </div>- <Text className="text-xs text-gray-500 mb-2">- Type an utterance and press Enter to add it. You can also paste multiple lines.- </Text>- <AntdSelect- mode="tags"- value={route.utterances}- onChange={(utterances) => updateRoute(route.id, "utterances", utterances)}- placeholder="Type an utterance and press Enter..."- style={{ width: "100%" }}- tokenSeparators={["\n"]}- maxTagCount="responsive"- allowClear- />- </div>- </Card>- ),- }))}- />- )}+ <Separator />+ <div className="flex w-full items-center justify-between gap-3">+ <h3 className="text-lg font-semibold">JSON Preview</h3>+ <Button type="button" variant="link" onClick={() => setShowJsonPreview((visible) => !visible)}>+ {showJsonPreview ? "Hide" : "Show"}+ </Button>+ </div>- {/* JSON Preview */}- <Divider />- <div className="flex justify-between items-center mb-4 w-full">- <Text className="text-lg font-semibold">JSON Preview</Text>- <Button type="link" onClick={() => setShowJsonPreview(!showJsonPreview)} className="text-blue-600 p-0">- {showJsonPreview ? "Hide" : "Show"}- </Button>+ {showJsonPreview && (+ <Card className="bg-muted/40">+ <CardContent>+ <pre className="max-h-64 w-full overflow-auto text-sm">{JSON.stringify(generatedConfig, null, 2)}</pre>+ </CardContent>+ </Card>+ )}</div>-- {showJsonPreview && (- <Card className="bg-gray-50 w-full">- <pre className="text-sm overflow-auto max-h-64 w-full">{JSON.stringify(generateConfig(), null, 2)}</pre>- </Card>- )}- </div>+ </TooltipProvider>);};diff --git a/ui/litellm-dashboard/src/components/add_model/auto_router_connection_test.tsx b/ui/litellm-dashboard/src/components/add_model/auto_router_connection_test.tsxindex 5badd155da8..874f83b370f 100644--- a/ui/litellm-dashboard/src/components/add_model/auto_router_connection_test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/auto_router_connection_test.tsx@@ -1,11 +1,9 @@import React from "react";-import { Typography } from "antd";-import { CheckCircleTwoTone, CloseCircleTwoTone, LoadingOutlined } from "@ant-design/icons";+import { CircleCheck, CircleX, LoaderCircle } from "lucide-react";+import { testModelGroupConnection, ModelGroupConnectionResult } from "../networking";import { AutoRouterTestTarget } from "./build_auto_router_test_targets";-const { Text } = Typography;-interface AutoRouterConnectionTestProps {accessToken: string;targets: AutoRouterTestTarget[];@@ -48,53 +46,48 @@ const AutoRouterConnectionTest: React.FC<AutoRouterConnectionTestProps> = ({}, []);if (targets.length === 0) {- return <Text type="secondary">No complexity tiers are configured yet, so there is nothing to test.</Text>;+ return (+ <p className="text-sm text-muted-foreground">+ No complexity tiers are configured yet, so there is nothing to test.+ </p>+ );}return (<div className="space-y-3">- <Text type="secondary" style={{ display: "block", marginBottom: 8 }}>+ <p className="mb-2 text-sm text-muted-foreground">Each configured tier routes to a saved model group. Test Connection sends a minimal request through the proxy toeach one, exactly as the auto router would.- </Text>+ </p>{targets.map((target, index) => {const result = results[index] ?? { status: "pending" };return (<divkey={`${target.modelGroup}-${target.mode}`}data-testid="auto-router-test-row"- style={{- border: "1px solid #e5e7eb",- borderRadius: 8,- padding: "12px 16px",- display: "flex",- alignItems: "flex-start",- gap: 12,- }}+ className="flex items-start gap-3 rounded-lg border p-3">- <div style={{ fontSize: 18, lineHeight: "24px" }}>- {result.status === "pending" && <LoadingOutlined data-testid="test-status-pending" />}+ <div className="pt-0.5">+ {result.status === "pending" && (+ <LoaderCircle className="size-5 animate-spin text-muted-foreground" data-testid="test-status-pending" />+ )}{result.status === "success" && (- <CheckCircleTwoTone twoToneColor="#52c41a" data-testid="test-status-success" />+ <CircleCheck className="size-5 text-primary" data-testid="test-status-success" />)}{result.status === "error" && (- <CloseCircleTwoTone twoToneColor="#ff4d4f" data-testid="test-status-error" />+ <CircleX className="size-5 text-destructive" data-testid="test-status-error" />)}</div>- <div style={{ flex: 1 }}>- <Text strong>{target.labels.join(", ")}</Text>{" "}- <Text type="secondary">+ <div className="min-w-0 flex-1 text-sm">+ <span className="font-medium">{target.labels.join(", ")}</span>{" "}+ <span className="text-muted-foreground">{"->"} {target.modelGroup}{target.mode === "embedding" ? " (embedding)" : ""}- </Text>+ </span>{result.status === "error" && (- <Text- type="danger"- data-testid="test-error-message"- style={{ display: "block", marginTop: 4, fontSize: 13 }}- >+ <p className="mt-1 text-xs text-destructive" data-testid="test-error-message">{result.error}- </Text>+ </p>)}</div></div>diff --git a/ui/litellm-dashboard/src/components/add_model/model_connection_test.test.tsx b/ui/litellm-dashboard/src/components/add_model/model_connection_test.test.tsxnew file mode 100644index 00000000000..9c5527d7e74--- /dev/null+++ b/ui/litellm-dashboard/src/components/add_model/model_connection_test.test.tsx@@ -0,0 +1,108 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import NotificationsManager from "../molecules/notifications_manager";+import { testConnectionRequest } from "../networking";+import { prepareModelAddRequest } from "./handle_add_model_submit";+import ModelConnectionTest from "./model_connection_test";++vi.mock("../networking", () => ({ testConnectionRequest: vi.fn() }));+vi.mock("./handle_add_model_submit", () => ({ prepareModelAddRequest: vi.fn() }));+vi.mock("../molecules/notifications_manager", () => ({+ default: { success: vi.fn(), fromBackend: vi.fn() },+}));++const preparedRequest = [{ litellmParamsObj: { model: "openai/gpt-4o-mini" }, modelInfoObj: { mode: "chat" } }];++const finishConnectionTest = async () => {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });+};++describe("ModelConnectionTest", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ vi.mocked(prepareModelAddRequest).mockResolvedValue(preparedRequest as never);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("tests the prepared model and shows a successful result", async () => {+ const onTestComplete = vi.fn();+ vi.mocked(testConnectionRequest).mockResolvedValue({ status: "success" } as never);++ render(+ <ModelConnectionTest+ formValues={{ model: "gpt-4o-mini" }}+ accessToken="sk-test"+ testMode="chat"+ modelName="GPT-4o mini"+ onTestComplete={onTestComplete}+ />,+ );++ expect(screen.getByText("Testing connection to GPT-4o mini...")).toBeInTheDocument();+ await finishConnectionTest();++ expect(prepareModelAddRequest).toHaveBeenCalledWith({ model: "gpt-4o-mini" }, "sk-test", null);+ expect(testConnectionRequest).toHaveBeenCalledWith(+ "sk-test",+ { model: "openai/gpt-4o-mini" },+ { mode: "chat" },+ "chat",+ );+ expect(screen.getByTestId("connection-success-msg")).toHaveTextContent("Connection to GPT-4o mini successful!");+ expect(NotificationsManager.success).toHaveBeenCalledWith("Connection test successful!");+ expect(onTestComplete).toHaveBeenCalledTimes(1);+ });++ it("shows a cleaned provider error, request details, and copies the curl command", async () => {+ const writeText = vi.fn();+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });+ vi.mocked(testConnectionRequest).mockResolvedValue({+ status: "error",+ result: {+ error: "litellm.AuthenticationError: invalid api key stack trace: hidden",+ raw_request_typed_dict: {+ raw_request_api_base: "https://api.example.test/v1/chat/completions",+ raw_request_body: { model: "gpt-4o-mini" },+ raw_request_headers: { Authorization: "Bearer test" },+ },+ },+ } as never);++ render(+ <ModelConnectionTest+ formValues={{ model: "gpt-4o-mini" }}+ accessToken="sk-test"+ testMode="chat"+ modelName="GPT-4o mini"+ />,+ );+ await finishConnectionTest();++ expect(screen.getByTestId("connection-failure-msg")).toHaveTextContent("Connection to GPT-4o mini failed");+ expect(screen.getByText("invalid api key")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Show Details" }));+ expect(screen.getByText("Troubleshooting Details")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Copy to Clipboard/ }));++ expect(writeText).toHaveBeenCalledWith(expect.stringContaining("https://api.example.test/v1/chat/completions"));+ expect(NotificationsManager.success).toHaveBeenCalledWith("Copied to clipboard");+ });++ it("shows a preparation failure without sending a connection request", async () => {+ vi.mocked(prepareModelAddRequest).mockResolvedValue(null as never);++ render(<ModelConnectionTest formValues={{}} accessToken="sk-test" testMode="chat" />);+ await finishConnectionTest();++ expect(screen.getByText("Failed to prepare model data. Please check your form inputs.")).toBeInTheDocument();+ expect(testConnectionRequest).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/components/add_model/model_connection_test.tsx b/ui/litellm-dashboard/src/components/add_model/model_connection_test.tsxindex 62bb5975478..071890190d1 100644--- a/ui/litellm-dashboard/src/components/add_model/model_connection_test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/model_connection_test.tsx@@ -1,10 +1,12 @@import React from "react";-import { Typography, Button, Divider } from "antd";-import { WarningOutlined, InfoCircleOutlined, CopyOutlined } from "@ant-design/icons";+import { AlertTriangle, CircleCheck, Copy, ExternalLink, Info, LoaderCircle } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Separator } from "@/components/ui/separator";++import NotificationsManager from "../molecules/notifications_manager";import { testConnectionRequest } from "../networking";import { prepareModelAddRequest } from "./handle_add_model_submit";-import NotificationsManager from "../molecules/notifications_manager";-const { Text } = Typography;interface ModelConnectionTestProps {formValues: Record<string, any>;@@ -18,16 +20,16 @@ interface ModelConnectionTestProps {const ModelConnectionTest: React.FC<ModelConnectionTestProps> = ({formValues,accessToken,- testMode,+ testMode: _testMode,modelName = "this model",- onClose,+ onClose: _onClose,onTestComplete,}) => {const [error, setError] = React.useState<Error | string | null>(null);const [rawResponse, setRawResponse] = React.useState<any>(null);- const [isLoading, setIsLoading] = React.useState<boolean>(true);- const [isSuccess, setIsSuccess] = React.useState<boolean>(false);- const [showDetails, setShowDetails] = React.useState<boolean>(false);+ const [isLoading, setIsLoading] = React.useState(true);+ const [isSuccess, setIsSuccess] = React.useState(false);+ const [showDetails, setShowDetails] = React.useState(false);const testModelConnection = async () => {setIsLoading(true);@@ -36,7 +38,6 @@ const ModelConnectionTest: React.FC<ModelConnectionTestProps> = ({setRawResponse(null);setIsSuccess(false);- // Add a small delay to ensure form values are fully populatedawait new Promise((resolve) => setTimeout(resolve, 100));try {@@ -50,8 +51,8 @@ const ModelConnectionTest: React.FC<ModelConnectionTestProps> = ({}const { litellmParamsObj, modelInfoObj } = result[0];-const response = await testConnectionRequest(accessToken, litellmParamsObj, modelInfoObj, modelInfoObj?.mode);+if (response.status === "success") {NotificationsManager.success("Connection test successful!");setError(null);@@ -62,34 +63,31 @@ const ModelConnectionTest: React.FC<ModelConnectionTestProps> = ({setRawResponse(response.result?.raw_request_typed_dict);setIsSuccess(false);}- } catch (error) {- console.error("Test connection error:", error);- setError(error instanceof Error ? error.message : String(error));+ } catch (connectionError) {+ console.error("Test connection error:", connectionError);+ setError(connectionError instanceof Error ? connectionError.message : String(connectionError));setIsSuccess(false);} finally {setIsLoading(false);- if (onTestComplete) onTestComplete();+ onTestComplete?.();}};React.useEffect(() => {- // Run the test once when component mounts- // Add a small timeout to ensure form values are readyconst timer = setTimeout(() => {testModelConnection();}, 200);return () => clearTimeout(timer);- }, []); // Empty dependency array means this runs once on mount+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the parent remounts the component to start a fresh connection test+ }, []);const getCleanErrorMessage = (errorMsg: string) => {if (!errorMsg) return "Unknown error";-- const mainError = errorMsg.split("stack trace:")[0].trim();-- const cleanedError = mainError.replace(/^litellm\.(.*?)Error: /, "");-- return cleanedError;+ return errorMsg+ .split("stack trace:")[0]+ .trim()+ .replace(/^litellm\.(.*?)Error: /, "");};const errorMessage =@@ -115,7 +113,12 @@ const ModelConnectionTest: React.FC<ModelConnectionTestProps> = ({return `curl -X POST \\${apiBase} \\- ${headerString ? `${headerString} \\\n ` : ""}-H 'Content-Type: application/json' \\+ ${+ headerString+ ? `${headerString} \\+ `+ : ""+ }-H 'Content-Type: application/json' \\-d '{${formattedBody}}'`;@@ -130,158 +133,85 @@ ${formattedBody}: "";return (- <div style={{ padding: "24px", borderRadius: "8px", backgroundColor: "#fff" }}>+ <div className="rounded-lg bg-background p-6">{isLoading ? (- <div style={{ textAlign: "center", padding: "32px 20px" }}>- <div className="loading-spinner" style={{ marginBottom: "16px" }}>- {/* Simple CSS spinner */}- <div- style={{- border: "3px solid #f3f3f3",- borderTop: "3px solid #1890ff",- borderRadius: "50%",- width: "30px",- height: "30px",- animation: "spin 1s linear infinite",- margin: "0 auto",- }}- />- </div>- <Text style={{ fontSize: "16px" }}>Testing connection to {modelName}...</Text>- <style jsx>{`- @keyframes spin {- 0% {- transform: rotate(0deg);- }- 100% {- transform: rotate(360deg);- }- }- `}</style>+ <div aria-busy="true" className="flex flex-col items-center justify-center gap-4 px-5 py-8 text-center">+ <LoaderCircle className="size-8 animate-spin text-primary" />+ <p className="text-base">Testing connection to {modelName}...</p></div>) : isSuccess ? (- <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "32px 20px" }}>- <div style={{ color: "#52c41a", fontSize: "24px", display: "flex", alignItems: "center" }}>- <svg- viewBox="64 64 896 896"- focusable="false"- data-icon="check-circle"- width="1em"- height="1em"- fill="currentColor"- aria-hidden="true"- >- <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"></path>- </svg>- </div>- <Text- data-testid="connection-success-msg"- type="success"- style={{ fontSize: "18px", fontWeight: 500, marginLeft: "10px" }}- >+ <div className="flex items-center justify-center gap-2.5 px-5 py-8">+ <CircleCheck className="size-6 text-primary" />+ <p data-testid="connection-success-msg" className="text-lg font-medium">Connection to {modelName} successful!- </Text>+ </p></div>) : (- <>- <div>- <div style={{ display: "flex", alignItems: "center", marginBottom: "20px" }}>- <WarningOutlined style={{ color: "#ff4d4f", fontSize: "24px", marginRight: "12px" }} />- <Text data-testid="connection-failure-msg" type="danger" style={{ fontSize: "18px", fontWeight: 500 }}>- Connection to {modelName} failed- </Text>- </div>-- <div- style={{- backgroundColor: "#fff2f0",- border: "1px solid #ffccc7",- borderRadius: "8px",- padding: "16px",- marginBottom: "20px",- boxShadow: "0 1px 2px rgba(0, 0, 0, 0.03)",- }}- >- <Text strong style={{ display: "block", marginBottom: "8px" }}>- Error:{" "}- </Text>- <Text type="danger" style={{ fontSize: "14px", lineHeight: "1.5" }}>- {errorMessage}- </Text>-- {error && (- <div style={{ marginTop: "12px" }}>- <Button- type="link"- onClick={() => setShowDetails(!showDetails)}- style={{ paddingLeft: 0, height: "auto" }}- >- {showDetails ? "Hide Details" : "Show Details"}- </Button>- </div>- )}- </div>+ <div>+ <div className="mb-5 flex items-center gap-3">+ <AlertTriangle className="size-6 text-destructive" />+ <p data-testid="connection-failure-msg" className="text-lg font-medium text-destructive">+ Connection to {modelName} failed+ </p>+ </div>- {showDetails && (- <div style={{ marginBottom: "20px" }}>- <Text strong style={{ display: "block", marginBottom: "8px", fontSize: "15px" }}>- Troubleshooting Details- </Text>- <pre- style={{- backgroundColor: "#f5f5f5",- padding: "16px",- borderRadius: "8px",- fontSize: "13px",- maxHeight: "200px",- overflow: "auto",- border: "1px solid #e8e8e8",- lineHeight: "1.5",- }}- >- {typeof error === "string" ? error : JSON.stringify(error, null, 2)}- </pre>- </div>- )}+ <div className="mb-5 rounded-lg border border-destructive/30 bg-destructive/10 p-4 shadow-xs">+ <p className="mb-2 font-medium">Error:</p>+ <p className="text-sm leading-relaxed text-destructive">{errorMessage}</p>- <div>- <Text strong style={{ display: "block", marginBottom: "8px", fontSize: "15px" }}>- API Request- </Text>- <pre- style={{- backgroundColor: "#f5f5f5",- padding: "16px",- borderRadius: "8px",- fontSize: "13px",- maxHeight: "250px",- overflow: "auto",- border: "1px solid #e8e8e8",- lineHeight: "1.5",- }}- >- {curlCommand || "No request data available"}- </pre>+ {error && (<Button- style={{ marginTop: "8px" }}- icon={<CopyOutlined />}- onClick={() => {- navigator.clipboard.writeText(curlCommand || "");- NotificationsManager.success("Copied to clipboard");- }}+ type="button"+ variant="link"+ className="mt-3 h-auto px-0"+ onClick={() => setShowDetails((visible) => !visible)}>- Copy to Clipboard+ {showDetails ? "Hide Details" : "Show Details"}</Button>+ )}+ </div>++ {showDetails && (+ <div className="mb-5">+ <p className="mb-2 text-sm font-medium">Troubleshooting Details</p>+ <pre className="max-h-52 overflow-auto rounded-lg border bg-muted/50 p-4 text-xs leading-relaxed">+ {typeof error === "string" ? error : JSON.stringify(error, null, 2)}+ </pre></div>+ )}++ <div>+ <p className="mb-2 text-sm font-medium">API Request</p>+ <pre className="max-h-64 overflow-auto rounded-lg border bg-muted/50 p-4 text-xs leading-relaxed">+ {curlCommand || "No request data available"}+ </pre>+ <Button+ type="button"+ variant="outline"+ className="mt-2"+ onClick={() => {+ navigator.clipboard.writeText(curlCommand || "");+ NotificationsManager.success("Copied to clipboard");+ }}+ >+ <Copy data-icon="inline-start" />+ Copy to Clipboard+ </Button></div>- </>+ </div>)}- <Divider style={{ margin: "24px 0 16px" }} />- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <Button type="link" href="https://docs.litellm.ai/docs/providers" target="_blank" icon={<InfoCircleOutlined />}>- View Documentation- </Button>- </div>++ <Separator className="my-6" />+ <Button+ variant="link"+ className="px-0"+ nativeButton={false}+ render={<a href="https://docs.litellm.ai/docs/providers" target="_blank" rel="noopener noreferrer" />}+ >+ <Info data-icon="inline-start" />+ View Documentation+ <ExternalLink data-icon="inline-end" />+ </Button></div>);};diff --git a/ui/litellm-dashboard/src/components/atoms/Tooltip.test.tsx b/ui/litellm-dashboard/src/components/atoms/Tooltip.test.tsxindex 2d370a736b8..4e0b64ea6de 100644--- a/ui/litellm-dashboard/src/components/atoms/Tooltip.test.tsx+++ b/ui/litellm-dashboard/src/components/atoms/Tooltip.test.tsx@@ -1,16 +1,12 @@-import { describe, it, expect, vi } from "vitest";+import { describe, it, expect } from "vitest";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { Tooltip } from "./Tooltip";-vi.mock("@ant-design/icons", () => ({- QuestionCircleOutlined: (props: any) => <span data-testid="question-icon" {...props} />,-}));-describe("Tooltip", () => {it("should render", () => {render(<Tooltip content="Help text" />);- expect(screen.getByTestId("question-icon")).toBeInTheDocument();+ expect(screen.getByLabelText("question-circle")).toBeInTheDocument();});it("should render children instead of the default icon when provided", () => {@@ -20,14 +16,14 @@ describe("Tooltip", () => {</Tooltip>,);expect(screen.getByRole("button", { name: /info/i })).toBeInTheDocument();- expect(screen.queryByTestId("question-icon")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("question-circle")).not.toBeInTheDocument();});it("should show tooltip content on mouse enter", async () => {const user = userEvent.setup();render(<Tooltip content="Help text" />);- await user.hover(screen.getByTestId("question-icon"));+ await user.hover(screen.getByLabelText("question-circle"));expect(screen.getByText("Help text")).toBeInTheDocument();});@@ -36,10 +32,10 @@ describe("Tooltip", () => {const user = userEvent.setup();render(<Tooltip content="Help text" />);- await user.hover(screen.getByTestId("question-icon"));+ await user.hover(screen.getByLabelText("question-circle"));expect(screen.getByText("Help text")).toBeInTheDocument();- await user.unhover(screen.getByTestId("question-icon"));+ await user.unhover(screen.getByLabelText("question-circle"));expect(screen.queryByText("Help text")).not.toBeInTheDocument();});diff --git a/ui/litellm-dashboard/src/components/atoms/Tooltip.tsx b/ui/litellm-dashboard/src/components/atoms/Tooltip.tsxindex 5eebeaeec37..02b03b518bf 100644--- a/ui/litellm-dashboard/src/components/atoms/Tooltip.tsx+++ b/ui/litellm-dashboard/src/components/atoms/Tooltip.tsx@@ -1,5 +1,8 @@-import React, { useState, useRef } from "react";-import { QuestionCircleOutlined } from "@ant-design/icons";+import React from "react";+import { CircleHelp } from "lucide-react";++import { Tooltip as ShadcnTooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/cva.config";interface TooltipProps {content: React.ReactNode;@@ -8,63 +11,30 @@ interface TooltipProps {className?: string;}-export const Tooltip: React.FC<TooltipProps> = ({ content, children, width = "auto", className = "" }) => {- const [showTooltip, setShowTooltip] = useState(false);- const [tooltipPosition, setTooltipPosition] = useState<"top" | "bottom">("top");- const tooltipRef = useRef<HTMLDivElement>(null);-- // Function to check if tooltip would fit above- const checkTooltipPosition = () => {- if (tooltipRef.current) {- const rect = tooltipRef.current.getBoundingClientRect();- const tooltipHeight = 300; // Approximate height of the tooltip- const spaceAbove = rect.top;- const spaceBelow = window.innerHeight - rect.bottom;-- if (spaceAbove < tooltipHeight && spaceBelow > tooltipHeight) {- setTooltipPosition("bottom");- } else {- setTooltipPosition("top");- }- }- };+const widthClassNames: Record<string, string> = {+ "360px": "max-w-[360px]",+ "500px": "max-w-[500px]",+ auto: "max-w-xs",+};- return (- <div className="relative inline-block" ref={tooltipRef}>- {children || (- <QuestionCircleOutlined- className="ml-1 text-gray-500 cursor-help"- onMouseEnter={() => {- checkTooltipPosition();- setShowTooltip(true);- }}- onMouseLeave={() => setShowTooltip(false)}- />- )}- {showTooltip && (- <div- className={`absolute left-1/2 -translate-x-1/2 z-50 bg-black/90 text-white p-2 rounded-md text-sm font-normal shadow-lg ${className}`}- style={{- [tooltipPosition === "top" ? "bottom" : "top"]: "100%",- width: width,- marginBottom: tooltipPosition === "top" ? "8px" : "0",- marginTop: tooltipPosition === "bottom" ? "8px" : "0",- }}- >- {content}- <div- className="absolute left-1/2 -translate-x-1/2 w-0 h-0"- style={{- top: tooltipPosition === "top" ? "100%" : "auto",- bottom: tooltipPosition === "bottom" ? "100%" : "auto",- borderTop: tooltipPosition === "top" ? "6px solid rgba(0, 0, 0, 0.9)" : "6px solid transparent",- borderBottom: tooltipPosition === "bottom" ? "6px solid rgba(0, 0, 0, 0.9)" : "6px solid transparent",- borderLeft: "6px solid transparent",- borderRight: "6px solid transparent",- }}+export const Tooltip: React.FC<TooltipProps> = ({ content, children, width = "auto", className }) => (+ <TooltipProvider>+ <ShadcnTooltip>+ <TooltipTrigger+ render={+ <span+ className={cn(+ "inline-flex cursor-help items-center rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ className,+ )}/>- </div>- )}- </div>- );-};+ }+ >+ {children ?? <CircleHelp aria-label="question-circle" className="ml-1 size-4 text-muted-foreground" />}+ </TooltipTrigger>+ <TooltipContent className={cn("whitespace-normal", widthClassNames[width] ?? "max-w-xs")}>+ {content}+ </TooltipContent>+ </ShadcnTooltip>+ </TooltipProvider>+);diff --git a/ui/litellm-dashboard/src/components/key_value_input.test.tsx b/ui/litellm-dashboard/src/components/key_value_input.test.tsxnew file mode 100644index 00000000000..5ffe85cd2be--- /dev/null+++ b/ui/litellm-dashboard/src/components/key_value_input.test.tsx@@ -0,0 +1,26 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import KeyValueInput from "./key_value_input";++describe("KeyValueInput", () => {+ it("renders existing header pairs", () => {+ render(<KeyValueInput value={{ Authorization: "Bearer token" }} />);++ expect(screen.getByPlaceholderText("Header Name")).toHaveValue("Authorization");+ expect(screen.getByPlaceholderText("Header Value")).toHaveValue("Bearer token");+ });++ it("adds a header row and emits edits", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<KeyValueInput onChange={onChange} />);++ await user.click(screen.getByRole("button", { name: /Add Header$/ }));+ await user.type(screen.getByPlaceholderText("Header Name"), "X-Trace");+ await user.type(screen.getByPlaceholderText("Header Value"), "enabled");++ expect(onChange).toHaveBeenLastCalledWith({ "X-Trace": "enabled" });+ });+});diff --git a/ui/litellm-dashboard/src/components/key_value_input.tsx b/ui/litellm-dashboard/src/components/key_value_input.tsxindex db814f84037..a35968ce0e7 100644--- a/ui/litellm-dashboard/src/components/key_value_input.tsx+++ b/ui/litellm-dashboard/src/components/key_value_input.tsx@@ -1,7 +1,8 @@import React, { useState } from "react";-import { Button, Space } from "antd";-import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";-import { TextInput } from "@tremor/react";+import { Minus, Plus } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";interface KeyValueInputProps {value?: Record<string, string>;@@ -29,21 +30,24 @@ const KeyValueInput: React.FC<KeyValueInputProps> = ({ value = {}, onChange }) =};return (- <div>+ <div className="space-y-2">{pairs.map(([key, val], index) => (- <Space key={index} style={{ display: "flex", marginBottom: 8 }} align="center">- <TextInput placeholder="Header Name" value={key} onChange={(e) => handleChange(index, e.target.value, val)} />- <TextInput- placeholder="Header Value"- value={val}- onChange={(e) => handleChange(index, key, e.target.value)}- />- <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%" }}>- <MinusCircleOutlined onClick={() => handleRemove(index)} style={{ cursor: "pointer" }} />- </div>- </Space>+ <div key={index} className="flex items-center gap-2">+ <Input placeholder="Header Name" value={key} onChange={(e) => handleChange(index, e.target.value, val)} />+ <Input placeholder="Header Value" value={val} onChange={(e) => handleChange(index, key, e.target.value)} />+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={() => handleRemove(index)}+ aria-label={`Remove header ${index + 1}`}+ >+ <Minus />+ </Button>+ </div>))}- <Button type="dashed" onClick={handleAdd} icon={<PlusOutlined />}>+ <Button type="button" variant="outline" onClick={handleAdd}>+ <Plus />Add Header</Button></div>diff --git a/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.test.tsx b/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.test.tsxindex 93a015c8a36..19f6d883930 100644--- a/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.test.tsx+++ b/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.test.tsx@@ -1,7 +1,7 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { UploadProps } from "antd/es/upload";+import type { ComponentProps } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import { CredentialItem, credentialCreateCall, credentialUpdateCall } from "@/components/networking";@@ -9,7 +9,7 @@ import NotificationsManager from "@/components/molecules/notifications_manager";import CredentialsPanel from "./CredentialsPanel";-const DEFAULT_UPLOAD_PROPS = {} as UploadProps;+const DEFAULT_UPLOAD_PROPS = {} as ComponentProps<typeof CredentialsPanel>["uploadProps"];const mockUseAuthorized = vi.fn();const mockUseCredentials = vi.fn();diff --git a/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.tsx b/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.tsxindex 99ab9525966..d6109ea7655 100644--- a/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.tsx+++ b/ui/litellm-dashboard/src/components/model_add/CredentialsPanel.tsx@@ -1,8 +1,7 @@"use client";-import { UploadProps } from "antd/es/upload";import { Plus } from "lucide-react";-import { useState } from "react";+import { type ComponentProps, useState } from "react";import { useCredentials } from "@/app/(dashboard)/hooks/credentials/useCredentials";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";@@ -22,7 +21,7 @@ import CredentialModal from "./CredentialModal";import CredentialsTable from "./CredentialsTable";interface CredentialsPanelProps {- uploadProps: UploadProps;+ uploadProps: ComponentProps<typeof CredentialModal>["uploadProps"];}const restrictedFields = ["credential_name", "custom_llm_provider"];diff --git a/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.test.ts b/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.test.tsindex 8be839ee862..d7218f6f4d3 100644--- a/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.test.ts+++ b/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.test.ts@@ -1,4 +1,3 @@-import type { FormInstance } from "antd";import { describe, expect, it, vi } from "vitest";import { Providers } from "../provider_info_helpers";import { resetCredentialFormOnProviderChange } from "./credential_form_helpers";@@ -18,7 +17,7 @@ function makeFormStub(initialFields: Record<string, unknown> = {}) {Object.keys(fields).forEach((k) => delete fields[k]);}),};- return { stub: stub as unknown as FormInstance, fields, calls: stub };+ return { stub: stub as unknown as Parameters<typeof resetCredentialFormOnProviderChange>[0], fields, calls: stub };}describe("resetCredentialFormOnProviderChange", () => {diff --git a/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.ts b/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.tsindex 5fb06e8e921..7190c539c81 100644--- a/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.ts+++ b/ui/litellm-dashboard/src/components/model_add/credential_form_helpers.ts@@ -1,6 +1,11 @@-import type { FormInstance } from "antd";import { Providers } from "../provider_info_helpers";+interface CredentialFormAdapter {+ getFieldValue: (field: string) => unknown;+ resetFields: () => void;+ setFieldValue: (field: string, value: unknown) => void;+}+/*** Reset the credential form when the user switches providers.*@@ -19,7 +24,7 @@ import { Providers } from "../provider_info_helpers";* that shouldn't reset just because the admin re-selected a provider.*/export function resetCredentialFormOnProviderChange(- form: FormInstance,+ form: CredentialFormAdapter,newProvider: Providers,setSelectedProvider: (p: Providers) => void,): void {diff --git a/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsx b/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsxindex 46c4a726927..041c8718133 100644--- a/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsx+++ b/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsx@@ -1,13 +1,19 @@import { OnChangeFn, PaginationState, RowSelectionState } from "@tanstack/react-table";-import { Modal } from "antd";-import { Button as AntdButton } from "antd";import React, { useCallback, useEffect, useMemo, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import { errorPatterns } from "@/utils/errorPatterns";import { Team } from "../key_team_helpers/key_list";import { individualModelHealthCheckCall, latestHealthChecksCall } from "../networking";-import { Button } from "@/components/ui/button";import { HealthChecksTable } from "./HealthChecksTable";import type { HealthCheckData, HealthStatus } from "./HealthChecksTableColumns";@@ -541,71 +547,85 @@ const HealthCheckComponent: React.FC<HealthCheckComponentProps> = ({teams={teams}/>- {/* Error Modal */}- <Modal- title={selectedErrorDetails ? `Health Check Error - ${selectedErrorDetails.modelName}` : "Error Details"}+ <Dialogopen={errorModalVisible}- onCancel={closeErrorModal}- footer={[- <AntdButton key="close" onClick={closeErrorModal}>- Close- </AntdButton>,- ]}- width={800}+ onOpenChange={(open) => {+ if (!open) closeErrorModal();+ }}>- {selectedErrorDetails && (- <div className="space-y-4">- <div>- <span className="font-medium">Error:</span>- <div className="mt-2 rounded-md border border-red-200 bg-red-50 p-3">- <span className="text-red-800">{selectedErrorDetails.cleanedError}</span>+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">+ <DialogHeader>+ <DialogTitle>+ {selectedErrorDetails ? `Health Check Error - ${selectedErrorDetails.modelName}` : "Error Details"}+ </DialogTitle>+ <DialogDescription>Details returned by the model health check.</DialogDescription>+ </DialogHeader>+ {selectedErrorDetails && (+ <div className="space-y-4">+ <div>+ <span className="font-medium">Error:</span>+ <div className="mt-2 rounded-md border border-destructive/30 bg-destructive/10 p-3">+ <span className="text-destructive">{selectedErrorDetails.cleanedError}</span>+ </div></div>- </div>- <div>- <span className="font-medium">Full Error Details:</span>- <div className="mt-2 max-h-96 overflow-y-auto rounded-md border border-gray-200 bg-gray-50 p-3">- <pre className="text-sm whitespace-pre-wrap text-gray-800">{selectedErrorDetails.fullError}</pre>+ <div>+ <span className="font-medium">Full Error Details:</span>+ <div className="mt-2 max-h-96 overflow-y-auto rounded-md border bg-muted/50 p-3">+ <pre className="whitespace-pre-wrap text-sm text-foreground">{selectedErrorDetails.fullError}</pre>+ </div></div></div>- </div>- )}- </Modal>+ )}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={closeErrorModal}>+ Close+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>- {/* Success Modal */}- <Modal- title={- selectedSuccessDetails ? `Health Check Response - ${selectedSuccessDetails.modelName}` : "Response Details"- }+ <Dialogopen={successModalVisible}- onCancel={closeSuccessModal}- footer={[- <AntdButton key="close" onClick={closeSuccessModal}>- Close- </AntdButton>,- ]}- width={800}+ onOpenChange={(open) => {+ if (!open) closeSuccessModal();+ }}>- {selectedSuccessDetails && (- <div className="space-y-4">- <div>- <span className="font-medium">Status:</span>- <div className="mt-2 rounded-md border border-green-200 bg-green-50 p-3">- <span className="text-green-800">Health check passed successfully</span>+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">+ <DialogHeader>+ <DialogTitle>+ {selectedSuccessDetails+ ? `Health Check Response - ${selectedSuccessDetails.modelName}`+ : "Response Details"}+ </DialogTitle>+ <DialogDescription>Response returned by the successful model health check.</DialogDescription>+ </DialogHeader>+ {selectedSuccessDetails && (+ <div className="space-y-4">+ <div>+ <span className="font-medium">Status:</span>+ <div className="mt-2 rounded-md border border-primary/30 bg-primary/5 p-3">+ <span className="text-foreground">Health check passed successfully</span>+ </div></div>- </div>- <div>- <span className="font-medium">Response Details:</span>- <div className="mt-2 max-h-96 overflow-y-auto rounded-md border border-gray-200 bg-gray-50 p-3">- <pre className="text-sm whitespace-pre-wrap text-gray-800">- {JSON.stringify(selectedSuccessDetails.response, null, 2)}- </pre>+ <div>+ <span className="font-medium">Response Details:</span>+ <div className="mt-2 max-h-96 overflow-y-auto rounded-md border bg-muted/50 p-3">+ <pre className="whitespace-pre-wrap text-sm text-foreground">+ {JSON.stringify(selectedSuccessDetails.response, null, 2)}+ </pre>+ </div></div></div>- </div>- )}- </Modal>+ )}+ <DialogFooter>+ <Button type="button" variant="outline" onClick={closeSuccessModal}>+ Close+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></div>);};diff --git a/ui/litellm-dashboard/src/components/molecules/cost_optimization_feedback_banner.tsx b/ui/litellm-dashboard/src/components/molecules/cost_optimization_feedback_banner.tsxindex 9c8a561844e..176789db964 100644--- a/ui/litellm-dashboard/src/components/molecules/cost_optimization_feedback_banner.tsx+++ b/ui/litellm-dashboard/src/components/molecules/cost_optimization_feedback_banner.tsx@@ -1,5 +1,7 @@import React, { useState } from "react";-import { CommentOutlined } from "@ant-design/icons";+import { ExternalLink, MessageSquare, X } from "lucide-react";++import { Button } from "@/components/ui/button";const STORAGE_KEY = "hideCostOptimizationFeedbackBanner";const DISCUSSION_URL = "https://github.com/BerriAI/litellm/discussions/32172";@@ -17,58 +19,38 @@ const CostOptimizationFeedbackBanner: React.FC = () => {}return (- <div className="mb-4 px-4 py-3 bg-blue-50 rounded-lg border border-blue-100 flex items-center gap-4">- <div className="shrink-0 w-10 h-10 bg-white rounded-full flex items-center justify-center border border-blue-200">- <CommentOutlined style={{ fontSize: "18px", color: "#6366f1" }} />+ <div className="mb-4 flex items-center gap-4 rounded-lg border bg-muted/40 px-4 py-3">+ <div className="flex size-10 shrink-0 items-center justify-center rounded-full border bg-background">+ <MessageSquare className="size-4 text-muted-foreground" /></div>- <div className="flex-1 min-w-0">- <h4 className="text-gray-900 font-semibold text-sm m-0">Help shape cost optimization</h4>- <p className="text-gray-500 text-xs m-0 mt-0.5">+ <div className="min-w-0 flex-1">+ <h4 className="m-0 text-sm font-semibold text-foreground">Help shape cost optimization</h4>+ <p className="m-0 mt-0.5 text-xs text-muted-foreground">We're collecting suggestions for cost optimization improvements across routing, budgets, and more. Let usknow what you'd like to see.</p></div>- <a- href={DISCUSSION_URL}- target="_blank"- rel="noopener noreferrer"- className="shrink-0 inline-flex items-center gap-2 px-4 py-2 bg-[#6366f1] hover:bg-[#5558e3] text-white text-sm font-medium rounded-lg transition-colors"+ <Button+ className="shrink-0"+ nativeButton={false}+ render={<a href={DISCUSSION_URL} target="_blank" rel="noopener noreferrer" />}>Share Feedback- <svg- xmlns="http://www.w3.org/2000/svg"- className="h-4 w-4"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth={2}- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"- />- </svg>- </a>- <button+ <ExternalLink />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"onClick={() => {setDismissed(true);localStorage.setItem(STORAGE_KEY, "true");}}- className="shrink-0 p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-full transition-colors"+ className="shrink-0"aria-label="Dismiss banner">- <svg- xmlns="http://www.w3.org/2000/svg"- className="h-5 w-5"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth={2}- >- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>+ <X />+ </Button></div>);};diff --git a/ui/litellm-dashboard/src/components/price_data_reload.test.tsx b/ui/litellm-dashboard/src/components/price_data_reload.test.tsxnew file mode 100644index 00000000000..cbee2328478--- /dev/null+++ b/ui/litellm-dashboard/src/components/price_data_reload.test.tsx@@ -0,0 +1,123 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import NotificationsManager from "./molecules/notifications_manager";+import {+ cancelModelCostMapReload,+ getModelCostMapReloadStatus,+ getModelCostMapSource,+ reloadModelCostMap,+ scheduleModelCostMapReload,+} from "./networking";+import PriceDataReload from "./price_data_reload";++vi.mock("./networking", () => ({+ cancelModelCostMapReload: vi.fn(),+ getModelCostMapReloadStatus: vi.fn(),+ getModelCostMapSource: vi.fn(),+ reloadModelCostMap: vi.fn(),+ scheduleModelCostMapReload: vi.fn(),+}));+vi.mock("./molecules/notifications_manager", () => ({+ default: { success: vi.fn(), fromBackend: vi.fn() },+}));++const unscheduledStatus = { scheduled: false, interval_hours: null, last_run: null, next_run: null };+const scheduledStatus = {+ scheduled: true,+ interval_hours: 6,+ last_run: null,+ next_run: "2026-01-21T00:00:00Z",+};+const remoteSource = {+ source: "remote",+ url: "https://pricing.example.test/model_prices.json",+ is_env_forced: false,+ fallback_reason: null,+ model_count: 1234,+};++describe("PriceDataReload", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(getModelCostMapReloadStatus).mockResolvedValue(unscheduledStatus);+ vi.mocked(getModelCostMapSource).mockResolvedValue(remoteSource as never);+ });++ it("shows the pricing source and current reload status", async () => {+ render(<PriceDataReload accessToken="sk-test" />);++ expect(await screen.findByText("Pricing Data Source")).toBeInTheDocument();+ expect(screen.getByText("Remote")).toBeInTheDocument();+ expect(screen.getByText("1,234")).toBeInTheDocument();+ expect(screen.getByText("No periodic reload scheduled")).toBeInTheDocument();+ });++ it("confirms an immediate reload and refreshes dependent data", async () => {+ const user = userEvent.setup();+ const onReloadSuccess = vi.fn();+ vi.mocked(reloadModelCostMap).mockResolvedValue({ status: "success", models_count: 42 } as never);+ render(<PriceDataReload accessToken="sk-test" onReloadSuccess={onReloadSuccess} />);++ await user.click(screen.getByRole("button", { name: /Reload Price Data/ }));+ expect(screen.getByText("Hard Refresh Price Data")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Yes" }));++ await waitFor(() => expect(reloadModelCostMap).toHaveBeenCalledWith("sk-test"));+ expect(onReloadSuccess).toHaveBeenCalledTimes(1);+ expect(NotificationsManager.success).toHaveBeenCalledWith("Price data reloaded successfully! 42 models updated.");+ });++ it("schedules periodic reloads using the selected interval", async () => {+ const user = userEvent.setup();+ vi.mocked(scheduleModelCostMapReload).mockResolvedValue({ status: "success" } as never);+ render(<PriceDataReload accessToken="sk-test" />);++ await user.click(screen.getByRole("button", { name: /Set Up Periodic Reload/ }));+ expect(screen.getByRole("dialog", { name: "Set Up Periodic Reload" })).toBeInTheDocument();+ const hours = screen.getByRole("spinbutton", { name: "Reload interval in hours" });+ await user.clear(hours);+ await user.type(hours, "12");+ await user.click(screen.getByRole("button", { name: "Schedule" }));++ await waitFor(() => expect(scheduleModelCostMapReload).toHaveBeenCalledWith("sk-test", 12));+ expect(NotificationsManager.success).toHaveBeenCalledWith("Periodic reload scheduled for every 12 hours");+ });++ it.each(["-1", "1.5", "169"])("should reject an invalid periodic reload interval of %s hours", async (interval) => {+ const user = userEvent.setup();+ render(<PriceDataReload accessToken="sk-test" />);++ await user.click(screen.getByRole("button", { name: /Set Up Periodic Reload/ }));+ fireEvent.change(screen.getByRole("spinbutton"), { target: { value: interval } });+ await user.click(screen.getByRole("button", { name: "Schedule" }));++ expect(scheduleModelCostMapReload).not.toHaveBeenCalled();+ expect(NotificationsManager.fromBackend).toHaveBeenCalledWith("Hours must be a whole number between 1 and 168");+ });++ it.each([1, 168])("should schedule a periodic reload at the inclusive %s-hour boundary", async (interval) => {+ const user = userEvent.setup();+ vi.mocked(scheduleModelCostMapReload).mockResolvedValue({ status: "success" } as never);+ render(<PriceDataReload accessToken="sk-test" />);++ await user.click(screen.getByRole("button", { name: /Set Up Periodic Reload/ }));+ fireEvent.change(screen.getByRole("spinbutton"), { target: { value: String(interval) } });+ await user.click(screen.getByRole("button", { name: "Schedule" }));++ await waitFor(() => expect(scheduleModelCostMapReload).toHaveBeenCalledWith("sk-test", interval));+ });++ it("cancels an active periodic reload", async () => {+ const user = userEvent.setup();+ vi.mocked(getModelCostMapReloadStatus).mockResolvedValue(scheduledStatus);+ vi.mocked(cancelModelCostMapReload).mockResolvedValue({ status: "success" } as never);+ render(<PriceDataReload accessToken="sk-test" />);++ await user.click(await screen.findByRole("button", { name: /Cancel Periodic Reload/ }));++ await waitFor(() => expect(cancelModelCostMapReload).toHaveBeenCalledWith("sk-test"));+ expect(NotificationsManager.success).toHaveBeenCalledWith("Periodic reload cancelled successfully");+ });+});diff --git a/ui/litellm-dashboard/src/components/price_data_reload.tsx b/ui/litellm-dashboard/src/components/price_data_reload.tsxindex f56387d283c..a60bc2e8ec8 100644--- a/ui/litellm-dashboard/src/components/price_data_reload.tsx+++ b/ui/litellm-dashboard/src/components/price_data_reload.tsx@@ -1,24 +1,41 @@-import React, { useState, useEffect } from "react";-import { Button, Popconfirm, Modal, InputNumber, Space, Typography, Tag, Card, Tooltip, Divider } from "antd";+import React, { useEffect, useState } from "react";+import { Ban, Clock3, Cloud, Database, Info, LoaderCircle, RefreshCw, TriangleAlert } from "lucide-react";+import {- ReloadOutlined,- ClockCircleOutlined,- StopOutlined,- CloudOutlined,- DatabaseOutlined,- InfoCircleOutlined,- WarningOutlined,-} from "@ant-design/icons";+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Card, CardContent } from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";+import { Separator } from "@/components/ui/separator";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/cva.config";++import NotificationsManager from "./molecules/notifications_manager";import {- reloadModelCostMap,- scheduleModelCostMapReload,cancelModelCostMapReload,getModelCostMapReloadStatus,getModelCostMapSource,+ reloadModelCostMap,+ scheduleModelCostMapReload,} from "./networking";-import NotificationsManager from "./molecules/notifications_manager";--const { Text } = Typography;interface ReloadStatus {scheduled: boolean;@@ -35,6 +52,13 @@ interface CostMapSourceInfo {model_count: number;}+const EMPTY_RELOAD_STATUS: ReloadStatus = {+ scheduled: false,+ interval_hours: null,+ last_run: null,+ next_run: null,+};+interface PriceDataReloadProps {accessToken: string;onReloadSuccess?: () => void;@@ -45,6 +69,26 @@ interface PriceDataReloadProps {className?: string;}+const buttonVariants = {+ primary: "default",+ default: "outline",+ dashed: "outline",+ link: "link",+ text: "ghost",+} as const;++const buttonSizes = {+ small: "sm",+ middle: "default",+ large: "lg",+} as const;++const isValidReloadInterval = (value: number) => {+ if (!Number.isFinite(value)) return false;+ if (!Number.isInteger(value)) return false;+ return value >= 1 && value <= 168;+};+const PriceDataReload: React.FC<PriceDataReloadProps> = ({accessToken,onReloadSuccess,@@ -58,24 +102,10 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({const [isScheduling, setIsScheduling] = useState(false);const [isCancelling, setIsCancelling] = useState(false);const [showScheduleModal, setShowScheduleModal] = useState(false);- const [hours, setHours] = useState<number>(6);+ const [hours, setHours] = useState<number | "">(6);const [reloadStatus, setReloadStatus] = useState<ReloadStatus | null>(null);const [sourceInfo, setSourceInfo] = useState<CostMapSourceInfo | null>(null);- // Fetch status on component mount and periodically- useEffect(() => {- fetchReloadStatus();- fetchSourceInfo();-- // Refresh status every 30 seconds to keep it up to date- const interval = setInterval(() => {- fetchReloadStatus();- fetchSourceInfo();- }, 30000);-- return () => clearInterval(interval);- }, [accessToken]);-const fetchReloadStatus = async () => {if (!accessToken) return;@@ -84,13 +114,7 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({setReloadStatus(status);} catch (error) {console.error("Failed to fetch reload status:", error);- // Set a default status to prevent UI issues- setReloadStatus({- scheduled: false,- interval_hours: null,- last_run: null,- next_run: null,- });+ setReloadStatus(EMPTY_RELOAD_STATUS);}};@@ -98,13 +122,30 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({if (!accessToken) return;try {- const info = await getModelCostMapSource(accessToken);- setSourceInfo(info);+ setSourceInfo(await getModelCostMapSource(accessToken));} catch (error) {console.error("Failed to fetch cost map source info:", error);}};+ useEffect(() => {+ const initialRefresh = window.setTimeout(() => {+ fetchReloadStatus();+ fetchSourceInfo();+ }, 0);++ const interval = setInterval(() => {+ fetchReloadStatus();+ fetchSourceInfo();+ }, 30000);++ return () => {+ clearTimeout(initialRefresh);+ clearInterval(interval);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- refresh functions intentionally follow the current access token+ }, [accessToken]);+const handleHardRefresh = async () => {if (!accessToken) {NotificationsManager.fromBackend("No access token available");@@ -118,7 +159,6 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({if (response.status === "success") {NotificationsManager.success(`Price data reloaded successfully! ${response.models_count || 0} models updated.`);onReloadSuccess?.();- // Refresh status and source info after successful reloadawait fetchReloadStatus();await fetchSourceInfo();} else {@@ -131,23 +171,25 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({setIsLoading(false);}};+const handleScheduleReload = async () => {if (!accessToken) {NotificationsManager.fromBackend("No access token available");return;}- if (hours <= 0) {- NotificationsManager.fromBackend("Hours must be greater than 0");+ const intervalHours = Number(hours);+ if (!isValidReloadInterval(intervalHours)) {+ NotificationsManager.fromBackend("Hours must be a whole number between 1 and 168");return;}setIsScheduling(true);try {- const response = await scheduleModelCostMapReload(accessToken, hours);+ const response = await scheduleModelCostMapReload(accessToken, intervalHours);if (response.status === "success") {- NotificationsManager.success(`Periodic reload scheduled for every ${hours} hours`);+ NotificationsManager.success(`Periodic reload scheduled for every ${intervalHours} hours`);setShowScheduleModal(false);await fetchReloadStatus();} else {@@ -200,304 +242,190 @@ const PriceDataReload: React.FC<PriceDataReloadProps> = ({return "Active";};- const getStatusColor = () => {- if (!reloadStatus?.scheduled) return "default";- if (!reloadStatus.last_run) return "processing";- return "success";- };-return (- <div className={className}>- {/* Action Buttons */}- <Space direction="horizontal" size="middle" style={{ marginBottom: 16 }}>- {/* Hard Refresh Button - Always visible */}- <Popconfirm- title="Hard Refresh Price Data"- description="This will immediately fetch the latest pricing information from the remote source. Continue?"- onConfirm={handleHardRefresh}- okText="Yes"- cancelText="No"- okButtonProps={{- style: {- backgroundColor: "#6366f1",- borderColor: "#6366f1",- color: "white",- fontWeight: "500",- borderRadius: "0.375rem",- padding: "0.375rem 0.75rem",- height: "auto",- fontSize: "0.875rem",- lineHeight: "1.25rem",- transition: "all 0.2s ease-in-out",- },- onMouseEnter: (e) => {- e.currentTarget.style.backgroundColor = "#4f46e5";- },- onMouseLeave: (e) => {- e.currentTarget.style.backgroundColor = "#6366f1";- },- }}- >- <Button- type={type}- size={size}- loading={isLoading}- icon={showIcon ? <ReloadOutlined /> : undefined}- style={{- backgroundColor: "#6366f1",- borderColor: "#6366f1",- color: "white",- fontWeight: "500",- borderRadius: "0.375rem",- padding: "0.375rem 0.75rem",- height: "auto",- fontSize: "0.875rem",- lineHeight: "1.25rem",- transition: "all 0.2s ease-in-out",- }}- onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = "#4f46e5";- }}- onMouseLeave={(e) => {- e.currentTarget.style.backgroundColor = "#6366f1";- }}- >- {buttonText}- </Button>- </Popconfirm>-- {/* Periodic Reload Controls */}- {!reloadStatus?.scheduled ? (- <Button- type="default"- size={size}- icon={<ClockCircleOutlined />}- onClick={() => setShowScheduleModal(true)}- style={{- borderColor: "#d9d9d9",- color: "#6366f1",- fontWeight: "500",- borderRadius: "0.375rem",- padding: "0.375rem 0.75rem",- height: "auto",- fontSize: "0.875rem",- lineHeight: "1.25rem",- }}- >- Set Up Periodic Reload- </Button>- ) : (- <Button- type="default"- size={size}- danger- icon={<StopOutlined />}- loading={isCancelling}- onClick={handleCancelReload}- style={{- borderColor: "#ff4d4f",- color: "#ff4d4f",- fontWeight: "500",- borderRadius: "0.375rem",- padding: "0.375rem 0.75rem",- height: "auto",- fontSize: "0.875rem",- lineHeight: "1.25rem",- }}- >- Cancel Periodic Reload- </Button>- )}- </Space>-- {/* Cost Map Source Info Card */}- {sourceInfo && (- <Card- size="small"- style={{- backgroundColor: sourceInfo.source === "remote" ? "#f0f7ff" : "#fff8f0",- border: `1px solid ${sourceInfo.source === "remote" ? "#bae0ff" : "#ffd591"}`,- borderRadius: 8,- marginBottom: 12,- }}- >- <Space direction="vertical" size="small" style={{ width: "100%" }}>- {/* Header row */}- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>- {sourceInfo.source === "remote" ? (- <CloudOutlined style={{ color: "#1677ff", fontSize: 16 }} />+ <TooltipProvider>+ <div className={className}>+ <div className="mb-4 flex flex-wrap gap-3">+ <AlertDialog>+ <AlertDialogTrigger+ render={+ <Button+ type="button"+ variant={buttonVariants[type]}+ size={buttonSizes[size]}+ className={cn(type === "dashed" && "border-dashed")}+ disabled={isLoading}+ />+ }+ >+ {isLoading ? (+ <LoaderCircle className="animate-spin" data-icon="inline-start" />) : (- <DatabaseOutlined style={{ color: "#fa8c16", fontSize: 16 }} />+ showIcon && <RefreshCw data-icon="inline-start" />)}- <Text strong style={{ fontSize: "13px" }}>- Pricing Data Source- </Text>- <Tag- color={sourceInfo.source === "remote" ? "blue" : "orange"}- style={{ marginLeft: "auto", fontWeight: 600, textTransform: "uppercase", fontSize: "11px" }}- >- {sourceInfo.source === "remote" ? "Remote" : "Local"}- </Tag>- </div>+ {buttonText}+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Hard Refresh Price Data</AlertDialogTitle>+ <AlertDialogDescription>+ This will immediately fetch the latest pricing information from the remote source. Continue?+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>No</AlertDialogCancel>+ <AlertDialogAction onClick={handleHardRefresh}>Yes</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ {!reloadStatus?.scheduled ? (+ <Button type="button" variant="outline" size={buttonSizes[size]} onClick={() => setShowScheduleModal(true)}>+ <Clock3 data-icon="inline-start" />+ Set Up Periodic Reload+ </Button>+ ) : (+ <Button+ type="button"+ variant="destructive"+ size={buttonSizes[size]}+ disabled={isCancelling}+ onClick={handleCancelReload}+ >+ {isCancelling ? (+ <LoaderCircle className="animate-spin" data-icon="inline-start" />+ ) : (+ <Ban data-icon="inline-start" />+ )}+ Cancel Periodic Reload+ </Button>+ )}+ </div>- <Divider style={{ margin: "6px 0" }} />+ {sourceInfo && (+ <Card size="sm" className="mb-3 bg-muted/30">+ <CardContent className="space-y-2">+ <div className="flex items-center gap-2">+ {sourceInfo.source === "remote" ? <Cloud className="size-4" /> : <Database className="size-4" />}+ <span className="text-sm font-medium">Pricing Data Source</span>+ <Badge variant="secondary" className="ml-auto uppercase">+ {sourceInfo.source === "remote" ? "Remote" : "Local"}+ </Badge>+ </div>- {/* Model count */}- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <Text type="secondary" style={{ fontSize: "12px" }}>- Models loaded:- </Text>- <Text strong style={{ fontSize: "12px" }}>- {sourceInfo.model_count.toLocaleString()}- </Text>- </div>+ <Separator />- {/* URL (when remote or attempted) */}- {sourceInfo.url && (- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>- <Text type="secondary" style={{ fontSize: "12px", whiteSpace: "nowrap" }}>- {sourceInfo.source === "remote" ? "Loaded from:" : "Attempted URL:"}- </Text>- <Tooltip title={sourceInfo.url}>- <Text- style={{- fontSize: "11px",- maxWidth: 240,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- display: "block",- color: "#1677ff",- cursor: "default",- }}- >- {sourceInfo.url}- </Text>- </Tooltip>+ <div className="flex items-center justify-between text-xs">+ <span className="text-muted-foreground">Models loaded:</span>+ <span className="font-medium">{sourceInfo.model_count.toLocaleString()}</span></div>- )}-- {/* Env forced notice */}- {sourceInfo.is_env_forced && (- <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 2 }}>- <InfoCircleOutlined style={{ color: "#fa8c16", fontSize: 12 }} />- <Text type="secondary" style={{ fontSize: "11px" }}>- Local mode forced via <code>LITELLM_LOCAL_MODEL_COST_MAP=True</code>- </Text>- </div>- )}-- {/* Fallback reason */}- {sourceInfo.fallback_reason && (- <div- style={{- display: "flex",- alignItems: "flex-start",- gap: 6,- backgroundColor: "#fff7e6",- border: "1px solid #ffd591",- borderRadius: 4,- padding: "4px 8px",- marginTop: 2,- }}- >- <WarningOutlined style={{ color: "#fa8c16", fontSize: 12, marginTop: 2 }} />- <Text style={{ fontSize: "11px", color: "#614700" }}>- Fell back to local: {sourceInfo.fallback_reason}- </Text>- </div>- )}- </Space>- </Card>- )}-- {/* Reload Schedule Status Card */}- {reloadStatus && (- <Card- size="small"- style={{- backgroundColor: "#f8f9fa",- border: "1px solid #e9ecef",- borderRadius: 8,- }}- >- <Space direction="vertical" size="small" style={{ width: "100%" }}>- {reloadStatus.scheduled ? (- <div>- <Tag color="green" icon={<ClockCircleOutlined />}>++ {sourceInfo.url && (+ <div className="flex items-start justify-between gap-2 text-xs">+ <span className="shrink-0 text-muted-foreground">+ {sourceInfo.source === "remote" ? "Loaded from:" : "Attempted URL:"}+ </span>+ <Tooltip>+ <TooltipTrigger render={<span className="max-w-60 truncate text-primary" />}>+ {sourceInfo.url}+ </TooltipTrigger>+ <TooltipContent>{sourceInfo.url}</TooltipContent>+ </Tooltip>+ </div>+ )}++ {sourceInfo.is_env_forced && (+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Info className="size-3.5 shrink-0" />+ <span>+ Local mode forced via <code>LITELLM_LOCAL_MODEL_COST_MAP=True</code>+ </span>+ </div>+ )}++ {sourceInfo.fallback_reason && (+ <div className="flex items-start gap-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-xs">+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-destructive" />+ <span>Fell back to local: {sourceInfo.fallback_reason}</span>+ </div>+ )}+ </CardContent>+ </Card>+ )}++ {reloadStatus && (+ <Card size="sm" className="bg-muted/30">+ <CardContent className="space-y-2">+ {reloadStatus.scheduled ? (+ <Badge variant="secondary">+ <Clock3 />Scheduled every {reloadStatus.interval_hours} hours- </Tag>+ </Badge>+ ) : (+ <p className="text-sm text-muted-foreground">No periodic reload scheduled</p>+ )}++ <div className="flex items-center justify-between text-xs">+ <span className="text-muted-foreground">Last run:</span>+ <span>{formatDateTime(reloadStatus.last_run)}</span></div>- ) : (- <Text type="secondary">No periodic reload scheduled</Text>- )}-- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <Text type="secondary" style={{ fontSize: "12px" }}>- Last run:- </Text>- <Text style={{ fontSize: "12px" }}>{formatDateTime(reloadStatus.last_run)}</Text>- </div>- {reloadStatus.scheduled && (- <>- {reloadStatus.next_run && (- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <Text type="secondary" style={{ fontSize: "12px" }}>- Next run:- </Text>- <Text style={{ fontSize: "12px" }}>{formatDateTime(reloadStatus.next_run)}</Text>+ {reloadStatus.scheduled && (+ <>+ {reloadStatus.next_run && (+ <div className="flex items-center justify-between text-xs">+ <span className="text-muted-foreground">Next run:</span>+ <span>{formatDateTime(reloadStatus.next_run)}</span>+ </div>+ )}+ <div className="flex items-center justify-between text-xs">+ <span className="text-muted-foreground">Status:</span>+ <Badge variant="outline">{getStatusText()}</Badge></div>- )}- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>- <Text type="secondary" style={{ fontSize: "12px" }}>- Status:- </Text>- <Tag color={getStatusColor()}>{getStatusText()}</Tag>- </div>- </>- )}- </Space>- </Card>- )}-- {/* Schedule Modal */}- <Modal- title="Set Up Periodic Reload"- open={showScheduleModal}- onOk={handleScheduleReload}- onCancel={() => setShowScheduleModal(false)}- confirmLoading={isScheduling}- okText="Schedule"- cancelText="Cancel"- okButtonProps={{- style: {- backgroundColor: "#6366f1",- borderColor: "#6366f1",- color: "white",- },- }}- >- <div style={{ marginBottom: 16 }}>- <Text>Set up automatic reload of price data every:</Text>- </div>- <div style={{ marginBottom: 16 }}>- <InputNumber- min={1}- max={168} // 1 week max- value={hours}- onChange={(value) => setHours(value || 6)}- addonAfter="hours"- style={{ width: "100%" }}- />- </div>- <div>- <Text type="secondary">- This will automatically fetch the latest pricing data from the remote source every {hours} hours.- </Text>- </div>- </Modal>- </div>+ </>+ )}+ </CardContent>+ </Card>+ )}++ <Dialog open={showScheduleModal} onOpenChange={setShowScheduleModal}>+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Set Up Periodic Reload</DialogTitle>+ <DialogDescription>+ Set how often LiteLLM should fetch the latest pricing data from the remote source.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <p className="text-sm">Set up automatic reload of price data every:</p>+ <InputGroup>+ <InputGroupInput+ type="number"+ aria-label="Reload interval in hours"+ min={1}+ max={168}+ value={hours}+ onChange={(event) => setHours(event.target.value === "" ? "" : Number(event.target.value))}+ />+ <InputGroupAddon align="inline-end">hours</InputGroupAddon>+ </InputGroup>+ <p className="text-sm text-muted-foreground">+ This will automatically fetch the latest pricing data from the remote source every {hours} hours.+ </p>+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setShowScheduleModal(false)}>+ Cancel+ </Button>+ <Button type="button" disabled={isScheduling} onClick={handleScheduleReload}>+ {isScheduling && <LoaderCircle className="animate-spin" data-icon="inline-start" />}+ Schedule+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ </TooltipProvider>);};diff --git a/ui/litellm-dashboard/src/components/query_param_input.test.tsx b/ui/litellm-dashboard/src/components/query_param_input.test.tsxnew file mode 100644index 00000000000..a9bd1dc6cb9--- /dev/null+++ b/ui/litellm-dashboard/src/components/query_param_input.test.tsx@@ -0,0 +1,26 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import QueryParamInput from "./query_param_input";++describe("QueryParamInput", () => {+ it("renders existing query parameter pairs", () => {+ render(<QueryParamInput value={{ version: "v1" }} />);++ expect(screen.getByPlaceholderText("Parameter Name (e.g., version)")).toHaveValue("version");+ expect(screen.getByPlaceholderText("Parameter Value (e.g., v1)")).toHaveValue("v1");+ });++ it("adds a query parameter row and emits edits", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<QueryParamInput onChange={onChange} />);++ await user.click(screen.getByRole("button", { name: /Add Query Parameter$/ }));+ await user.type(screen.getByPlaceholderText("Parameter Name (e.g., version)"), "region");+ await user.type(screen.getByPlaceholderText("Parameter Value (e.g., v1)"), "us-west");++ expect(onChange).toHaveBeenLastCalledWith({ region: "us-west" });+ });+});diff --git a/ui/litellm-dashboard/src/components/query_param_input.tsx b/ui/litellm-dashboard/src/components/query_param_input.tsxindex 344d77f3af5..1c7a67b35ea 100644--- a/ui/litellm-dashboard/src/components/query_param_input.tsx+++ b/ui/litellm-dashboard/src/components/query_param_input.tsx@@ -1,7 +1,8 @@import React, { useState } from "react";-import { Button, Space } from "antd";-import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";-import { TextInput } from "@tremor/react";+import { Minus, Plus } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";interface QueryParamInputProps {value?: Record<string, string>;@@ -29,25 +30,32 @@ const QueryParamInput: React.FC<QueryParamInputProps> = ({ value = {}, onChange};return (- <div>+ <div className="space-y-2">{pairs.map(([key, val], index) => (- <Space key={index} style={{ display: "flex", marginBottom: 8 }} align="center">- <TextInput+ <div key={index} className="flex items-center gap-2">+ <Inputplaceholder="Parameter Name (e.g., version)"value={key}onChange={(e) => handleChange(index, e.target.value, val)}/>- <TextInput+ <Inputplaceholder="Parameter Value (e.g., v1)"value={val}onChange={(e) => handleChange(index, key, e.target.value)}/>- <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%" }}>- <MinusCircleOutlined onClick={() => handleRemove(index)} style={{ cursor: "pointer" }} />- </div>- </Space>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={() => handleRemove(index)}+ aria-label={`Remove query parameter ${index + 1}`}+ >+ <Minus />+ </Button>+ </div>))}- <Button type="dashed" onClick={handleAdd} icon={<PlusOutlined />}>+ <Button type="button" variant="outline" onClick={handleAdd}>+ <Plus />Add Query Parameter</Button></div>diff --git a/ui/litellm-dashboard/src/components/route_preview.test.tsx b/ui/litellm-dashboard/src/components/route_preview.test.tsxnew file mode 100644index 00000000000..79b2d55b0c4--- /dev/null+++ b/ui/litellm-dashboard/src/components/route_preview.test.tsx@@ -0,0 +1,30 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import RoutePreview from "./route_preview";++vi.mock("./networking", () => ({ getProxyBaseUrl: () => "http://proxy.test" }));++describe("RoutePreview", () => {+ it("stays hidden until both route values are provided", () => {+ render(<RoutePreview pathValue="/images" targetValue="" includeSubpath={false} />);++ expect(screen.queryByText("Route Preview")).not.toBeInTheDocument();+ });++ it("shows the proxy route and forwarding target", () => {+ render(<RoutePreview pathValue="/images" targetValue="https://upstream.test" includeSubpath={false} />);++ expect(screen.getByText("http://proxy.test/images")).toBeInTheDocument();+ expect(screen.getByText("https://upstream.test")).toBeInTheDocument();+ expect(screen.getByText(/Not seeing the routing you wanted/)).toBeInTheDocument();+ });++ it("previews appended subpaths when enabled", () => {+ render(<RoutePreview pathValue="/images" targetValue="https://upstream.test" includeSubpath />);++ expect(screen.getByText("With subpaths:")).toBeInTheDocument();+ expect(screen.getAllByText("/v1/text-to-image/base/model")).toHaveLength(2);+ expect(screen.getByText(/Any path after \/images will be appended/)).toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/route_preview.tsx b/ui/litellm-dashboard/src/components/route_preview.tsxindex 712684af5fc..bdf193961f8 100644--- a/ui/litellm-dashboard/src/components/route_preview.tsx+++ b/ui/litellm-dashboard/src/components/route_preview.tsx@@ -1,8 +1,8 @@import React from "react";-import { Card, Typography } from "antd";-import { RightOutlined, InfoCircleOutlined } from "@ant-design/icons";+import { ArrowRight, Info } from "lucide-react";++import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";-const { Title, Text } = Typography;import { getProxyBaseUrl } from "./networking";interface RoutePreviewProps {@@ -11,103 +11,66 @@ interface RoutePreviewProps {includeSubpath: boolean;}+const Endpoint = ({ label, children }: { label: string; children: React.ReactNode }) => (+ <div className="min-w-0 flex-1 rounded-lg border bg-muted/40 p-3">+ <div className="mb-2 text-sm text-muted-foreground">{label}</div>+ <code className="block overflow-x-auto font-mono text-sm text-foreground">{children}</code>+ </div>+);+const RoutePreview: React.FC<RoutePreviewProps> = ({ pathValue, targetValue, includeSubpath }) => {const proxyBaseUrl = getProxyBaseUrl();- const getLiteLLMProxyUrl = () => {- return pathValue ? `${proxyBaseUrl}${pathValue}` : "";- };-- // Only show if both path and target are providedif (!pathValue || !targetValue) {return null;}return (- <Card className="p-5">- <Title level={5} className="text-lg font-semibold text-gray-900 mb-2">- Route Preview- </Title>- <Text type="secondary" className="text-gray-600 mb-5" style={{ display: "block" }}>- How your requests will be routed- </Text>-- <div className="space-y-5">- {/* Basic routing */}+ <Card>+ <CardHeader>+ <CardTitle className="text-lg">Route Preview</CardTitle>+ <CardDescription>How your requests will be routed</CardDescription>+ </CardHeader>+ <CardContent className="space-y-5"><div>- <div className="text-base font-semibold text-gray-900 mb-3">Basic routing:</div>- <div className="flex items-center gap-4">- {/* Your endpoint */}- <div className="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3">- <div className="text-sm text-gray-600 mb-2">Your endpoint</div>- <code className="font-mono text-sm text-gray-900">{getLiteLLMProxyUrl()}</code>- </div>-- {/* Arrow */}- <div className="text-gray-400">- <RightOutlined className="text-lg" />- </div>-- {/* Forwards to */}- <div className="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3">- <div className="text-sm text-gray-600 mb-2">Forwards to</div>- <code className="font-mono text-sm text-gray-900">{targetValue}</code>- </div>+ <h4 className="mb-3 text-base font-semibold">Basic routing:</h4>+ <div className="flex flex-col items-stretch gap-4 sm:flex-row sm:items-center">+ <Endpoint label="Your endpoint">{`${proxyBaseUrl}${pathValue}`}</Endpoint>+ <ArrowRight className="size-5 shrink-0 self-center text-muted-foreground max-sm:rotate-90" />+ <Endpoint label="Forwards to">{targetValue}</Endpoint></div></div>- {includeSubpath && (- <>- {/* With subpaths */}- <div>- <div className="text-base font-semibold text-gray-900 mb-3">With subpaths:</div>- <div className="flex items-center gap-4">- {/* Your endpoint + subpath */}- <div className="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3">- <div className="text-sm text-gray-600 mb-2">Your endpoint + subpath</div>- <code className="font-mono text-sm text-gray-900">- {pathValue && `${proxyBaseUrl}${pathValue}`}- <span className="text-blue-600">/v1/text-to-image/base/model</span>- </code>- </div>-- {/* Arrow */}- <div className="text-gray-400">- <RightOutlined className="text-lg" />- </div>-- {/* Forwards to with subpath */}- <div className="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3">- <div className="text-sm text-gray-600 mb-2">Forwards to</div>- <code className="font-mono text-sm text-gray-900">- {targetValue}- <span className="text-blue-600">/v1/text-to-image/base/model</span>- </code>- </div>- </div>-- {/* Note */}- <div className="mt-3 text-sm text-gray-600">- Any path after {pathValue} will be appended to the target URL- </div>- </div>- </>- )}-- {!includeSubpath && (- <div className="mt-4 p-3 bg-blue-50 rounded-md border border-blue-200">- <div className="flex items-start">- <InfoCircleOutlined className="text-blue-500 mt-0.5 mr-2 shrink-0" />- <div className="text-sm text-blue-700">- <span className="font-medium">Not seeing the routing you wanted?</span> Try enabling - Include Subpaths- - above - this allows subroutes like{" "}- <code className="bg-blue-100 px-1 py-0.5 rounded-sm font-mono text-xs">/api/v1/models</code> to be- forwarded automatically.- </div>+ {includeSubpath ? (+ <div>+ <h4 className="mb-3 text-base font-semibold">With subpaths:</h4>+ <div className="flex flex-col items-stretch gap-4 sm:flex-row sm:items-center">+ <Endpoint label="Your endpoint + subpath">+ {`${proxyBaseUrl}${pathValue}`}+ <span className="text-primary">/v1/text-to-image/base/model</span>+ </Endpoint>+ <ArrowRight className="size-5 shrink-0 self-center text-muted-foreground max-sm:rotate-90" />+ <Endpoint label="Forwards to">+ {targetValue}+ <span className="text-primary">/v1/text-to-image/base/model</span>+ </Endpoint></div>+ <p className="mt-3 text-sm text-muted-foreground">+ Any path after {pathValue} will be appended to the target URL+ </p>+ </div>+ ) : (+ <div className="flex items-start gap-2 rounded-md border border-primary/20 bg-primary/5 p-3 text-sm">+ <Info className="mt-0.5 size-4 shrink-0 text-primary" />+ <p>+ <span className="font-medium">Not seeing the routing you wanted?</span> Try enabling - Include Subpaths -+ above - this allows subroutes like{" "}+ <code className="rounded-sm bg-primary/10 px-1 py-0.5 font-mono text-xs">/api/v1/models</code> to be+ forwarded automatically.+ </p></div>)}- </div>+ </CardContent></Card>);};