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 the caching, cost tracking, alerting and user detail forms to react-hook-form and shadcn (#37350)
yuneng-jiang85333b286dcd
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFieldSection.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFieldSection.tsxindex 96106869009..93ddc682134 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFieldSection.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFieldSection.tsx@@ -31,7 +31,7 @@ const CacheFieldSection: React.FC<CacheFieldSectionProps> = ({return (<div className="space-y-6">- <Heading className="text-sm font-medium text-gray-900">{title}</Heading>+ <Heading className="text-sm font-medium text-foreground">{title}</Heading><div className={`grid ${gridCols}`}>{fields.map((field) => (<CacheFormFielddiff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFormField.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFormField.tsxindex dbd8c32d18d..24ec9043d21 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFormField.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/CacheFormField.tsx@@ -1,6 +1,21 @@-import { Form, Input, Select, Switch } from "antd";import React from "react";+import { useFormContext } from "react-hook-form";+import { FormField } from "@/components/shared/form/FormField";+import { PasswordInput } from "@/components/shared/PasswordInput";+import {+ Combobox,+ ComboboxClear,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+} from "@/components/ui/combobox";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";import { CacheField } from "./cacheSettingsFields";+import type { CacheFormValues } from "./cacheSettingsUtils";export interface EmbeddingModelOption {value: string;@@ -15,47 +30,81 @@ interface CacheFormFieldProps {isSecretConfigured?: boolean;}-const renderControl = (- field: CacheField,- embeddingModels: EmbeddingModelOption[],- placeholder: string,-): React.ReactNode => {- switch (field.type) {- case "boolean":- return <Switch />;- case "password":- return <Input.Password placeholder={placeholder} autoComplete="new-password" />;- case "integer":- case "float":- return <Input inputMode="decimal" placeholder={placeholder} />;- case "list":- return <Input.TextArea rows={4} placeholder={placeholder} />;- case "model-select":- return (- <Select- showSearch- allowClear- placeholder="Search and select a model..."- options={embeddingModels}- optionFilterProp="label"- style={{ width: "100%" }}- />- );- default:- return <Input placeholder={placeholder} />;- }-};+const CacheFormField: React.FC<CacheFormFieldProps> = ({ field, embeddingModels, isSecretConfigured = false }) => {+ const form = useFormContext<CacheFormValues>();+ const placeholder = isSecretConfigured ? SECRET_ALREADY_SET_PLACEHOLDER : field.helpText;-const CacheFormField: React.FC<CacheFormFieldProps> = ({ field, embeddingModels, isSecretConfigured = false }) => (- <Form.Item- name={field.name}- label={field.label}- extra={field.helpText}- rules={field.rules}- valuePropName={field.type === "boolean" ? "checked" : "value"}- >- {renderControl(field, embeddingModels, isSecretConfigured ? SECRET_ALREADY_SET_PLACEHOLDER : field.helpText)}- </Form.Item>-);+ return (+ <FormField control={form.control} name={field.name} label={field.label} description={field.helpText}>+ {({ ref, value, onChange, ...rest }) => {+ if (field.type === "boolean") {+ return <Switch {...rest} checked={value === true} onCheckedChange={(checked) => onChange(checked)} />;+ }+ if (field.type === "password") {+ return (+ <PasswordInput+ {...rest}+ ref={ref}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ autoComplete="new-password"+ />+ );+ }+ if (field.type === "list") {+ return (+ <Textarea+ {...rest}+ ref={ref}+ rows={4}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ />+ );+ }+ if (field.type === "model-select") {+ const selected = embeddingModels.find((model) => model.value === value) ?? null;+ return (+ <Combobox+ items={embeddingModels}+ value={selected}+ onValueChange={(model: EmbeddingModelOption | null) => onChange(model?.value ?? "")}+ itemToStringLabel={(model: EmbeddingModelOption) => model.label}+ isItemEqualToValue={(model: EmbeddingModelOption, other: EmbeddingModelOption) =>+ model.value === other.value+ }+ >+ <ComboboxInput {...rest} placeholder="Search and select a model..." className="w-full">+ <ComboboxClear />+ </ComboboxInput>+ <ComboboxContent>+ <ComboboxEmpty>No models found</ComboboxEmpty>+ <ComboboxList>+ {(model: EmbeddingModelOption) => (+ <ComboboxItem key={model.value} value={model} title={model.label}>+ {model.label}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ );+ }+ return (+ <Input+ {...rest}+ ref={ref}+ inputMode={field.type === "integer" || field.type === "float" ? "decimal" : undefined}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ />+ );+ }}+ </FormField>+ );+};export default CacheFormField;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/cacheSettingsFields.ts b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/cacheSettingsFields.tsindex e33b525c3ef..04dd6ff6038 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/cacheSettingsFields.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/cacheSettingsFields.ts@@ -1,12 +1,10 @@-import type { FormItemProps } from "antd";-export type CacheFieldType = "string" | "password" | "integer" | "float" | "boolean" | "list" | "model-select";export type RedisType = "node" | "cluster" | "sentinel" | "semantic";export type CacheSection = "connection" | "cluster" | "sentinel" | "semantic" | "ssl" | "cacheManagement" | "gcp";-export type CacheFieldRule = NonNullable<FormItemProps["rules"]>[number];+export type CacheFieldRule = (value: unknown) => string | null;// Marker the backend returns for a configured credential and maps back to the// stored secret on save, so the plaintext never round-trips through the form.@@ -35,60 +33,42 @@ export const REDIS_TYPE_DESCRIPTIONS: Readonly<Record<RedisType, string>> = {semantic: "Semantic caching that reuses responses for similar prompts",};-const portRule: CacheFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- const port = Number(value);- if (!Number.isInteger(port) || port < 1 || port > 65535) {- return Promise.reject(new Error("Port must be an integer between 1 and 65535"));- }- return Promise.resolve();- },+const isBlank = (value: unknown): boolean => value === undefined || value === null || String(value).trim() === "";++const portRule: CacheFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ const port = Number(value);+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? null : "Port must be an integer between 1 and 65535";};-const jsonListRule: CacheFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- let parsed: unknown;- try {- parsed = JSON.parse(String(value));- } catch {- return Promise.reject(new Error("Must be a valid JSON array (use double quotes)"));- }- if (!Array.isArray(parsed)) {- return Promise.reject(new Error("Must be a JSON array"));- }- return Promise.resolve();- },+const jsonListRule: CacheFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(String(value));+ } catch {+ return "Must be a valid JSON array (use double quotes)";+ }+ return Array.isArray(parsed) ? null : "Must be a JSON array";};-const nonNegativeIntegerRule: CacheFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- const parsed = Number(value);- if (!Number.isInteger(parsed) || parsed < 0) {- return Promise.reject(new Error("Must be a non-negative integer"));- }- return Promise.resolve();- },+const nonNegativeIntegerRule: CacheFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ const parsed = Number(value);+ return Number.isInteger(parsed) && parsed >= 0 ? null : "Must be a non-negative integer";};-const numberRule: CacheFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- if (Number.isNaN(Number(value))) {- return Promise.reject(new Error("Must be a number"));- }- return Promise.resolve();- },+const numberRule: CacheFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ return Number.isNaN(Number(value)) ? "Must be a number" : null;};export const CACHE_FIELDS: readonly CacheField[] = [diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.integration.test.tsxnew file mode 100644index 00000000000..bcbc3acc7d8--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.integration.test.tsx@@ -0,0 +1,144 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import CacheSettings from "./index";++const { getCacheSettingsCall, testCacheConnectionCall, updateCacheSettingsCall } = vi.hoisted(() => ({+ getCacheSettingsCall: vi.fn(),+ testCacheConnectionCall: vi.fn(),+ updateCacheSettingsCall: vi.fn(),+}));++vi.mock("@/components/networking", () => ({+ getCacheSettingsCall,+ testCacheConnectionCall,+ updateCacheSettingsCall,+}));++vi.mock("@/components/llm_calls/fetch_models", () => ({+ fetchAvailableModels: vi.fn().mockResolvedValue([]),+}));++const LOADED_WITH_ADVANCED = {+ current_values: {+ host: "redis.internal",+ namespace: "prod-ns",+ ttl: "300",+ max_connections: "50",+ ssl: true,+ },+};++const renderSettings = () => render(<CacheSettings accessToken="sk-test" userRole="Admin" userID="u1" />);++const save = async (user: ReturnType<typeof userEvent.setup>) =>+ user.click(screen.getByRole("button", { name: /save changes/i }));++describe("CacheSettings advanced settings round-trip", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getCacheSettingsCall.mockResolvedValue(LOADED_WITH_ADVANCED);+ updateCacheSettingsCall.mockResolvedValue({ status: "success" });+ testCacheConnectionCall.mockResolvedValue({ status: "success" });+ });++ it("keeps loaded advanced values in the payload when the section is never opened", async () => {+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("Connection Settings");++ expect(screen.queryByLabelText("Namespace")).not.toBeInTheDocument();+ await save(user);++ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(1));+ expect(updateCacheSettingsCall.mock.calls[0][1]).toEqual({+ type: "redis",+ host: "redis.internal",+ port: "6379",+ ssl: true,+ ssl_check_hostname: false,+ namespace: "prod-ns",+ ttl: 300,+ max_connections: 50,+ });+ });++ it("sends the same payload whether or not the advanced section was expanded", async () => {+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("Connection Settings");+ await save(user);+ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(1));+ const whileCollapsed = updateCacheSettingsCall.mock.calls[0][1];++ await user.click(screen.getByText("Advanced Settings"));+ await screen.findByLabelText("Namespace");+ await save(user);++ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(2));+ expect(updateCacheSettingsCall.mock.calls[1][1]).toEqual(whileCollapsed);+ });++ it("preserves a value typed into the advanced section after it is collapsed again", async () => {+ getCacheSettingsCall.mockResolvedValue({ current_values: { host: "redis.internal" } });+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("Connection Settings");++ await user.click(screen.getByText("Advanced Settings"));+ await user.type(await screen.findByLabelText("Namespace"), "typed-ns");+ await user.click(screen.getByText("Advanced Settings"));+ await waitFor(() => expect(screen.queryByLabelText("Namespace")).not.toBeInTheDocument());++ await save(user);++ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(1));+ expect(updateCacheSettingsCall.mock.calls[0][1]).toMatchObject({ namespace: "typed-ns" });+ });++ it("restores a value typed into the advanced section when it is expanded again", async () => {+ getCacheSettingsCall.mockResolvedValue({ current_values: { host: "redis.internal" } });+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("Connection Settings");++ await user.click(screen.getByText("Advanced Settings"));+ await user.type(await screen.findByLabelText("Namespace"), "typed-ns");+ await user.click(screen.getByText("Advanced Settings"));+ await waitFor(() => expect(screen.queryByLabelText("Namespace")).not.toBeInTheDocument());+ await user.click(screen.getByText("Advanced Settings"));++ expect(await screen.findByLabelText("Namespace")).toHaveValue("typed-ns");+ });++ it("keeps a hidden section's fields out of the payload when the redis type does not use them", async () => {+ getCacheSettingsCall.mockResolvedValue({+ current_values: { redis_type: "sentinel", service_name: "mymaster", host: "redis.internal" },+ });+ const user = userEvent.setup();+ renderSettings();+ await screen.findByLabelText("Service Name");+ await save(user);++ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(1));+ expect(updateCacheSettingsCall.mock.calls[0][1]).toMatchObject({ service_name: "mymaster" });+ expect(updateCacheSettingsCall.mock.calls[0][1]).not.toHaveProperty("redis_startup_nodes");+ });++ it("does not block the save on a malformed value inside a collapsed advanced section", async () => {+ getCacheSettingsCall.mockResolvedValue({ current_values: { host: "redis.internal" } });+ const user = userEvent.setup();+ renderSettings();+ await screen.findByText("Connection Settings");++ await user.click(screen.getByText("Advanced Settings"));+ await user.type(await screen.findByLabelText("TTL (seconds)"), "not-a-number");+ await user.click(screen.getByText("Advanced Settings"));+ await waitFor(() => expect(screen.queryByLabelText("TTL (seconds)")).not.toBeInTheDocument());++ await save(user);++ await waitFor(() => expect(updateCacheSettingsCall).toHaveBeenCalledTimes(1));+ expect(updateCacheSettingsCall.mock.calls[0][1]).not.toHaveProperty("ttl");+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.tsxindex ad3341bc171..76ec1b2c4cc 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_settings/index.tsx@@ -1,14 +1,24 @@import React, { useState, useEffect, useCallback } from "react";-import { Button, Accordion, AccordionHeader, AccordionBody } from "@tremor/react";-import { Form } from "antd";+import { ChevronRight } from "lucide-react";+import { FormProvider, useForm } from "react-hook-form";+import { Button } from "@tremor/react";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";import { getCacheSettingsCall, testCacheConnectionCall, updateCacheSettingsCall } from "@/components/networking";import { fetchAvailableModels, ModelGroup } from "@/components/llm_calls/fetch_models";import { toast } from "@/lib/toast";import RedisTypeSelector from "./RedisTypeSelector";import CacheFieldSection from "./CacheFieldSection";import { EmbeddingModelOption } from "./CacheFormField";-import { REDIS_TYPES, REDIS_TYPE_DESCRIPTIONS, RedisType } from "./cacheSettingsFields";-import { buildCachePayload, buildInitialValues, CacheFormValues, configuredSecretFields } from "./cacheSettingsUtils";+import { CACHE_FIELDS, REDIS_TYPES, REDIS_TYPE_DESCRIPTIONS, RedisType } from "./cacheSettingsFields";+import {+ buildCachePayload,+ buildInitialValues,+ CacheFormValues,+ configuredSecretFields,+ isFieldVisible,+} from "./cacheSettingsUtils";++const ADVANCED_SECTIONS = ["ssl", "cacheManagement", "gcp"] as const;interface CacheSettingsProps {accessToken: string | null;@@ -20,8 +30,9 @@ const toRedisType = (value: unknown): RedisType =>REDIS_TYPES.includes(value as RedisType) ? (value as RedisType) : "node";const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken }) => {- const [form] = Form.useForm<CacheFormValues>();+ const form = useForm<CacheFormValues>({ defaultValues: buildInitialValues({}) });const [redisType, setRedisType] = useState<RedisType>("node");+ const [advancedOpen, setAdvancedOpen] = useState(false);const [embeddingModels, setEmbeddingModels] = useState<EmbeddingModelOption[]>([]);const [isTesting, setIsTesting] = useState<boolean>(false);const [isSaving, setIsSaving] = useState<boolean>(false);@@ -34,7 +45,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken }) => {try {const data = (await getCacheSettingsCall(accessToken)) as { current_values?: Record<string, unknown> };const currentValues = data.current_values ?? {};- form.setFieldsValue(buildInitialValues(currentValues));+ form.reset(buildInitialValues(currentValues));setConfiguredSecrets(configuredSecretFields(currentValues));setRedisType(toRedisType(currentValues.redis_type));} catch (error) {@@ -62,19 +73,27 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken }) => {.catch((error) => console.error("Error fetching embedding models:", error));}, [accessToken]);- const validate = async (): Promise<CacheFormValues | null> => {- try {- return await form.validateFields();- } catch {- return null;- }+ const validate = (): CacheFormValues | null => {+ const values = form.getValues();+ const failures = CACHE_FIELDS.filter(+ (field) =>+ isFieldVisible(field, redisType) &&+ (advancedOpen || !ADVANCED_SECTIONS.some((section) => section === field.section)),+ ).flatMap((field) => {+ const message = field.rules?.map((rule) => rule(values[field.name])).find((result) => result !== null);+ return message === undefined || message === null ? [] : [[field.name, message] as const];+ });++ form.clearErrors();+ failures.forEach(([name, message]) => form.setError(name, { message }));+ return failures.length > 0 ? null : values;};const handleTestConnection = async () => {if (!accessToken) {return;}- const values = await validate();+ const values = validate();if (values === null) {return;}@@ -102,7 +121,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken }) => {if (!accessToken) {return;}- const values = await validate();+ const values = validate();if (values === null) {return;}@@ -126,96 +145,99 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken }) => {return (<div className="w-full space-y-8 py-2">- <Form form={form} layout="vertical" requiredMark={false} className="space-y-6">- <div className="max-w-3xl">- <h3 className="text-sm font-medium text-gray-900">Cache Settings</h3>- <p className="text-xs text-gray-500 mt-1">Configure Redis cache for LiteLLM</p>- </div>-- <RedisTypeSelector- redisType={redisType}- redisTypeDescriptions={REDIS_TYPE_DESCRIPTIONS}- onTypeChange={(type) => setRedisType(toRedisType(type))}- />-- <div className="pt-4 border-t border-gray-200">- <CacheFieldSection- title="Connection Settings"- section="connection"+ <FormProvider {...form}>+ <form onSubmit={(event) => event.preventDefault()} className="space-y-6">+ <div className="max-w-3xl">+ <h3 className="text-sm font-medium text-foreground">Cache Settings</h3>+ <p className="text-xs text-muted-foreground mt-1">Configure Redis cache for LiteLLM</p>+ </div>++ <RedisTypeSelectorredisType={redisType}- embeddingModels={embeddingModels}- configuredSecrets={configuredSecrets}+ redisTypeDescriptions={REDIS_TYPE_DESCRIPTIONS}+ onTypeChange={(type) => setRedisType(toRedisType(type))}/>- </div>-- {redisType === "cluster" && (- <div className="pt-4 border-t border-gray-200">- <CacheFieldSection- title="Cluster Configuration"- section="cluster"- redisType={redisType}- embeddingModels={embeddingModels}- gridCols="grid-cols-1 gap-6"- />- </div>- )}- {redisType === "sentinel" && (- <div className="pt-4 border-t border-gray-200">+ <div className="pt-4 border-t border-border"><CacheFieldSection- title="Sentinel Configuration"- section="sentinel"+ title="Connection Settings"+ section="connection"redisType={redisType}embeddingModels={embeddingModels}configuredSecrets={configuredSecrets}/></div>- )}- {redisType === "semantic" && (- <div className="pt-4 border-t border-gray-200">- <CacheFieldSection- title="Semantic Configuration"- section="semantic"- redisType={redisType}- embeddingModels={embeddingModels}- />- </div>- )}-- <Accordion className="mt-4">- <AccordionHeader>- <span className="text-sm font-medium text-gray-900">Advanced Settings</span>- </AccordionHeader>- <AccordionBody>- <div className="space-y-6">+ {redisType === "cluster" && (+ <div className="pt-4 border-t border-border"><CacheFieldSection- title="SSL Settings"- section="ssl"+ title="Cluster Configuration"+ section="cluster"redisType={redisType}embeddingModels={embeddingModels}- headingLevel="h5"+ gridCols="grid-cols-1 gap-6"/>+ </div>+ )}++ {redisType === "sentinel" && (+ <div className="pt-4 border-t border-border"><CacheFieldSection- title="Cache Management"- section="cacheManagement"+ title="Sentinel Configuration"+ section="sentinel"redisType={redisType}embeddingModels={embeddingModels}- headingLevel="h5"+ configuredSecrets={configuredSecrets}/>+ </div>+ )}++ {redisType === "semantic" && (+ <div className="pt-4 border-t border-border"><CacheFieldSection- title="GCP Authentication"- section="gcp"+ title="Semantic Configuration"+ section="semantic"redisType={redisType}embeddingModels={embeddingModels}- headingLevel="h5"/></div>- </AccordionBody>- </Accordion>- </Form>-- <div className="border-t border-gray-200 pt-6 flex justify-end gap-3">+ )}++ <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen} className="mt-4">+ <CollapsibleTrigger className="group flex w-full items-center justify-between py-2 text-left">+ <span className="text-sm font-medium text-foreground">Advanced Settings</span>+ <ChevronRight className="size-4 text-muted-foreground transition-transform group-data-panel-open:rotate-90" />+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="space-y-6">+ <CacheFieldSection+ title="SSL Settings"+ section="ssl"+ redisType={redisType}+ embeddingModels={embeddingModels}+ headingLevel="h5"+ />+ <CacheFieldSection+ title="Cache Management"+ section="cacheManagement"+ redisType={redisType}+ embeddingModels={embeddingModels}+ headingLevel="h5"+ />+ <CacheFieldSection+ title="GCP Authentication"+ section="gcp"+ redisType={redisType}+ embeddingModels={embeddingModels}+ headingLevel="h5"+ />+ </div>+ </CollapsibleContent>+ </Collapsible>+ </form>+ </FormProvider>++ <div className="border-t border-border pt-6 flex justify-end gap-3"><Button variant="secondary" size="sm" onClick={handleTestConnection} disabled={isTesting} className="text-sm">{isTesting ? "Testing..." : "Test Connection"}</Button>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFieldSection.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFieldSection.tsxindex af807926ed5..39d7f8b6dd0 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFieldSection.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFieldSection.tsx@@ -29,7 +29,7 @@ const CoordinationRedisFieldSection: React.FC<CoordinationRedisFieldSectionPropsreturn (<div className="space-y-6">- <Heading className="text-sm font-medium text-gray-900">{title}</Heading>+ <Heading className="text-sm font-medium text-foreground">{title}</Heading><div className={`grid ${gridCols}`}>{fields.map((field) => (<CoordinationRedisFormFielddiff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFormField.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFormField.tsxindex 50c2a39567a..dc4fae83200 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFormField.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/CoordinationRedisFormField.tsx@@ -1,6 +1,12 @@-import { Form, Input, Switch } from "antd";import React from "react";+import { useFormContext } from "react-hook-form";+import { FormField } from "@/components/shared/form/FormField";+import { PasswordInput } from "@/components/shared/PasswordInput";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";import { CoordinationField } from "./coordinationRedisFields";+import type { CoordinationFormValues } from "./coordinationRedisUtils";export const SECRET_ALREADY_SET_PLACEHOLDER = "Already set. Enter a new value to replace it.";@@ -9,31 +15,53 @@ interface CoordinationRedisFormFieldProps {isSecretConfigured: boolean;}-const renderControl = (field: CoordinationField, placeholder: string): React.ReactNode => {- switch (field.type) {- case "boolean":- return <Switch />;- case "password":- return <Input.Password placeholder={placeholder} autoComplete="new-password" />;- case "integer":- return <Input inputMode="numeric" placeholder={placeholder} />;- case "list":- return <Input.TextArea rows={4} placeholder={placeholder} />;- default:- return <Input placeholder={placeholder} />;- }-};+const CoordinationRedisFormField: React.FC<CoordinationRedisFormFieldProps> = ({ field, isSecretConfigured }) => {+ const form = useFormContext<CoordinationFormValues>();+ const placeholder = isSecretConfigured ? SECRET_ALREADY_SET_PLACEHOLDER : field.helpText;-const CoordinationRedisFormField: React.FC<CoordinationRedisFormFieldProps> = ({ field, isSecretConfigured }) => (- <Form.Item- name={field.name}- label={field.label}- extra={field.helpText}- rules={field.rules}- valuePropName={field.type === "boolean" ? "checked" : "value"}- >- {renderControl(field, isSecretConfigured ? SECRET_ALREADY_SET_PLACEHOLDER : field.helpText)}- </Form.Item>-);+ return (+ <FormField control={form.control} name={field.name} label={field.label} description={field.helpText}>+ {({ ref, value, onChange, ...rest }) => {+ if (field.type === "boolean") {+ return <Switch {...rest} checked={value === true} onCheckedChange={(checked) => onChange(checked)} />;+ }+ if (field.type === "password") {+ return (+ <PasswordInput+ {...rest}+ ref={ref}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ autoComplete="new-password"+ />+ );+ }+ if (field.type === "list") {+ return (+ <Textarea+ {...rest}+ ref={ref}+ rows={4}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ />+ );+ }+ return (+ <Input+ {...rest}+ ref={ref}+ inputMode={field.type === "integer" ? "numeric" : undefined}+ value={typeof value === "string" ? value : ""}+ onChange={onChange}+ placeholder={placeholder}+ />+ );+ }}+ </FormField>+ );+};export default CoordinationRedisFormField;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/coordinationRedisFields.ts b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/coordinationRedisFields.tsindex 180ece188e4..9e885be2601 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/coordinationRedisFields.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/coordinationRedisFields.ts@@ -1,12 +1,10 @@-import type { FormItemProps } from "antd";-export type CoordinationFieldType = "string" | "password" | "integer" | "boolean" | "list";export type CoordinationRedisType = "node" | "cluster" | "sentinel";export type CoordinationSection = "connection" | "cluster" | "sentinel" | "ssl";-export type CoordinationFieldRule = NonNullable<FormItemProps["rules"]>[number];+export type CoordinationFieldRule = (value: unknown) => string | null;export interface CoordinationField {readonly name: string;@@ -34,35 +32,27 @@ export const COORDINATION_REDIS_TYPE_LABELS: Readonly<Record<CoordinationRedisTysentinel: "Sentinel",};-const portRule: CoordinationFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- const port = Number(value);- if (!Number.isInteger(port) || port < 1 || port > 65535) {- return Promise.reject(new Error("Port must be an integer between 1 and 65535"));- }- return Promise.resolve();- },+const isBlank = (value: unknown): boolean => value === undefined || value === null || String(value).trim() === "";++const portRule: CoordinationFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ const port = Number(value);+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? null : "Port must be an integer between 1 and 65535";};-const jsonListRule: CoordinationFieldRule = {- validator: (_rule, value) => {- if (value === undefined || value === null || String(value).trim() === "") {- return Promise.resolve();- }- let parsed: unknown;- try {- parsed = JSON.parse(String(value));- } catch {- return Promise.reject(new Error("Must be a valid JSON array (use double quotes)"));- }- if (!Array.isArray(parsed)) {- return Promise.reject(new Error("Must be a JSON array"));- }- return Promise.resolve();- },+const jsonListRule: CoordinationFieldRule = (value) => {+ if (isBlank(value)) {+ return null;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(String(value));+ } catch {+ return "Must be a valid JSON array (use double quotes)";+ }+ return Array.isArray(parsed) ? null : "Must be a JSON array";};export const COORDINATION_FIELDS: readonly CoordinationField[] = [diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.integration.test.tsxnew file mode 100644index 00000000000..e2b78edb7e0--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.integration.test.tsx@@ -0,0 +1,82 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import userEvent from "@testing-library/user-event";+import CoordinationRedisSettings from "./index";+import * as networking from "@/components/networking";+import { toast } from "@/lib/toast";++vi.mock("@/components/networking", () => ({+ getCoordinationRedisSettingsCall: vi.fn(),+ testCoordinationRedisConnectionCall: vi.fn(),+ updateCoordinationRedisSettingsCall: vi.fn(),+}));++vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: () => ({ accessToken: "sk-test" }),+}));++const getSettings = vi.mocked(networking.getCoordinationRedisSettingsCall);+const updateSettings = vi.mocked(networking.updateCoordinationRedisSettingsCall);+const testConnection = vi.mocked(networking.testCoordinationRedisConnectionCall);+const notifications = vi.mocked(toast);++const settingsResponse = (+ values: Record<string, unknown>,+ source: "coordination_redis" | "cache_backend" | "environment" | null = null,+) => ({ values, fields: [], source });++const wrapper = ({ children }: { children: React.ReactNode }) => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+};++const renderSettings = () => render(<CoordinationRedisSettings />, { wrapper });++const clickSave = async (user: ReturnType<typeof userEvent.setup>) =>+ user.click(screen.getByRole("button", { name: /save changes/i }));+describe("CoordinationRedisSettings value retention across redis types", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue(settingsResponse({}));+ updateSettings.mockResolvedValue(undefined);+ });++ const pickRedisType = async (user: ReturnType<typeof userEvent.setup>, name: RegExp) => {+ await user.click(screen.getAllByRole("combobox")[0]);+ await user.click(await screen.findByRole("option", { name }));+ };++ it("keeps a value typed into a sentinel-only field when the type is switched away and back", async () => {+ const user = userEvent.setup();+ renderSettings();+ await screen.findByLabelText("Host");++ await pickRedisType(user, /sentinel/i);+ await user.type(await screen.findByLabelText("Service Name"), "mymaster");++ await pickRedisType(user, /node/i);+ await waitFor(() => expect(screen.queryByLabelText("Service Name")).not.toBeInTheDocument());++ await pickRedisType(user, /sentinel/i);++ expect(await screen.findByLabelText("Service Name")).toHaveValue("mymaster");+ });++ it("leaves a sentinel-only value out of the payload once the type is no longer sentinel", async () => {+ const user = userEvent.setup();+ renderSettings();+ await screen.findByLabelText("Host");++ await pickRedisType(user, /sentinel/i);+ await user.type(await screen.findByLabelText("Service Name"), "mymaster");++ await pickRedisType(user, /node/i);+ await waitFor(() => expect(screen.queryByLabelText("Service Name")).not.toBeInTheDocument());++ await clickSave(user);++ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ expect(JSON.stringify(updateSettings.mock.calls[0])).not.toContain("mymaster");+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.tsxindex 2ed1727eece..a9721e33c9b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/coordination_redis_settings/index.tsx@@ -1,5 +1,7 @@import React, { useEffect, useMemo, useState } from "react";-import { Button, Form } from "antd";+import { FormProvider, useForm } from "react-hook-form";+import { Button } from "@/components/ui/button";+import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";import { toast } from "@/lib/toast";import { StatusBadge } from "@/components/shared/table_cells/status_badge";import {@@ -9,18 +11,19 @@ import {} from "@/app/(dashboard)/hooks/coordinationRedis/useCoordinationRedisSettings";import CoordinationRedisFieldSection from "./CoordinationRedisFieldSection";import CoordinationRedisTypeSelector from "./CoordinationRedisTypeSelector";-import { CoordinationRedisType } from "./coordinationRedisFields";+import { COORDINATION_FIELDS, CoordinationRedisType } from "./coordinationRedisFields";import {buildCoordinationPayload,buildInitialValues,configuredSecretFields,CoordinationFormValues,inferRedisType,+ isFieldVisible,sourceBadge,} from "./coordinationRedisUtils";const CoordinationRedisSettings: React.FC = () => {- const [form] = Form.useForm<CoordinationFormValues>();+ const form = useForm<CoordinationFormValues>({ defaultValues: buildInitialValues({}) });const [selectedRedisType, setSelectedRedisType] = useState<CoordinationRedisType | null>(null);const { data, isLoading, isError } = useCoordinationRedisSettings();@@ -31,7 +34,7 @@ const CoordinationRedisSettings: React.FC = () => {useEffect(() => {if (data) {- form.setFieldsValue(buildInitialValues(data.values));+ form.reset(buildInitialValues(data.values));}}, [data, form]);@@ -41,16 +44,20 @@ const CoordinationRedisSettings: React.FC = () => {}}, [isError]);- const validate = async (): Promise<CoordinationFormValues | null> => {- try {- return await form.validateFields();- } catch {- return null;- }+ const validate = (): CoordinationFormValues | null => {+ const values = form.getValues();+ const failures = COORDINATION_FIELDS.filter((field) => isFieldVisible(field, redisType)).flatMap((field) => {+ const message = field.rules?.map((rule) => rule(values[field.name])).find((result) => result !== null);+ return message === undefined || message === null ? [] : [[field.name, message] as const];+ });++ form.clearErrors();+ failures.forEach(([name, message]) => form.setError(name, { message }));+ return failures.length > 0 ? null : values;};const handleTestConnection = async () => {- const values = await validate();+ const values = validate();if (values === null) {return;}@@ -68,7 +75,7 @@ const CoordinationRedisSettings: React.FC = () => {};const handleSaveChanges = async () => {- const values = await validate();+ const values = validate();if (values === null) {return;}@@ -86,69 +93,75 @@ const CoordinationRedisSettings: React.FC = () => {return (<div className="w-full space-y-8 py-2">- <Form form={form} layout="vertical" requiredMark={false} className="space-y-6">- <div className="max-w-3xl space-y-2">- <div className="flex items-center gap-3">- <h3 className="text-sm font-medium text-gray-900">Coordination Redis</h3>- {!isLoading && <StatusBadge tone={badge.tone} label={badge.label} dataTestId="coordination-redis-source" />}+ <FormProvider {...form}>+ <form onSubmit={(event) => event.preventDefault()} className="space-y-6">+ <div className="max-w-3xl space-y-2">+ <div className="flex items-center gap-3">+ <h3 className="text-sm font-medium text-foreground">Coordination Redis</h3>+ {!isLoading && (+ <StatusBadge tone={badge.tone} label={badge.label} dataTestId="coordination-redis-source" />+ )}+ </div>+ <p className="text-xs text-muted-foreground">+ Redis used to coordinate work across proxy pods: cross-pod rate limits, spend tracking, and the pod lock+ manager. It is configured independently of the response cache.+ </p>+ <p className="text-xs text-muted-foreground">{badge.tooltip}</p>+ <p className="text-xs text-amber-600 dark:text-amber-400">Saved changes take effect on proxy restart.</p></div>- <p className="text-xs text-gray-500">- Redis used to coordinate work across proxy pods: cross-pod rate limits, spend tracking, and the pod lock- manager. It is configured independently of the response cache.- </p>- <p className="text-xs text-gray-500">{badge.tooltip}</p>- <p className="text-xs text-amber-600">Saved changes take effect on proxy restart.</p>- </div>-- <CoordinationRedisTypeSelector redisType={redisType} onTypeChange={setSelectedRedisType} />-- <div className="pt-4 border-t border-gray-200">- <CoordinationRedisFieldSection- title="Connection Settings"- section="connection"- redisType={redisType}- configuredSecrets={configuredSecrets}- />- </div>-- {redisType === "cluster" && (- <div className="pt-4 border-t border-gray-200">++ <CoordinationRedisTypeSelector redisType={redisType} onTypeChange={setSelectedRedisType} />++ <div className="pt-4 border-t border-border"><CoordinationRedisFieldSection- title="Cluster Configuration"- section="cluster"+ title="Connection Settings"+ section="connection"redisType={redisType}configuredSecrets={configuredSecrets}- gridCols="grid-cols-1 gap-6"/></div>- )}- {redisType === "sentinel" && (- <div className="pt-4 border-t border-gray-200">+ {redisType === "cluster" && (+ <div className="pt-4 border-t border-border">+ <CoordinationRedisFieldSection+ title="Cluster Configuration"+ section="cluster"+ redisType={redisType}+ configuredSecrets={configuredSecrets}+ gridCols="grid-cols-1 gap-6"+ />+ </div>+ )}++ {redisType === "sentinel" && (+ <div className="pt-4 border-t border-border">+ <CoordinationRedisFieldSection+ title="Sentinel Configuration"+ section="sentinel"+ redisType={redisType}+ configuredSecrets={configuredSecrets}+ />+ </div>+ )}++ <div className="pt-4 border-t border-border"><CoordinationRedisFieldSection- title="Sentinel Configuration"- section="sentinel"+ title="SSL Settings"+ section="ssl"redisType={redisType}configuredSecrets={configuredSecrets}/></div>- )}-- <div className="pt-4 border-t border-gray-200">- <CoordinationRedisFieldSection- title="SSL Settings"- section="ssl"- redisType={redisType}- configuredSecrets={configuredSecrets}- />- </div>- </Form>-- <div className="border-t border-gray-200 pt-6 flex justify-end gap-3">- <Button onClick={handleTestConnection} loading={testConnection.isPending}>+ </form>+ </FormProvider>++ <div className="border-t border-border pt-6 flex justify-end gap-3">+ <Button variant="outline" onClick={handleTestConnection} disabled={testConnection.isPending}>+ {testConnection.isPending && <UiLoadingSpinner className="size-4" />}{testConnection.isPending ? "Testing..." : "Test Connection"}</Button>- <Button type="primary" onClick={handleSaveChanges} loading={updateSettings.isPending}>+ <Button onClick={handleSaveChanges} disabled={updateSettings.isPending}>+ {updateSettings.isPending && <UiLoadingSpinner className="size-4" />}{updateSettings.isPending ? "Saving..." : "Save Changes"}</Button></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.integration.test.tsxnew file mode 100644index 00000000000..b32eeff975e--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.integration.test.tsx@@ -0,0 +1,155 @@+import React from "react";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { renderWithProviders } from "../../../../../tests/test-utils";+import CostTrackingSettings from "./cost_tracking_settings";++const mockDiscountConfig = vi.fn(() => ({}));+const mockMarginConfig = vi.fn(() => ({}));+const mockRemoveDiscount = vi.fn();+const mockRemoveMargin = vi.fn();++const stableDiscountCallbacks = {+ fetchDiscountConfig: vi.fn().mockResolvedValue(undefined),+ handleAddProvider: vi.fn().mockResolvedValue(true),+ handleRemoveProvider: mockRemoveDiscount,+ handleDiscountChange: vi.fn().mockResolvedValue(undefined),+};++const stableMarginCallbacks = {+ fetchMarginConfig: vi.fn().mockResolvedValue(undefined),+ handleAddMargin: vi.fn().mockResolvedValue(true),+ handleRemoveMargin: mockRemoveMargin,+ handleMarginChange: vi.fn().mockResolvedValue(undefined),+};++vi.mock("./use_discount_config", () => ({+ useDiscountConfig: () => ({ discountConfig: mockDiscountConfig(), ...stableDiscountCallbacks }),+}));++vi.mock("./use_margin_config", () => ({+ useMarginConfig: () => ({ marginConfig: mockMarginConfig(), ...stableMarginCallbacks }),+}));++vi.mock("./pricing_calculator/index", () => ({+ default: () => <div data-testid="pricing-calculator">Pricing Calculator</div>,+}));++vi.mock("@/components/llm_calls/fetch_models", () => ({+ fetchAvailableModels: vi.fn().mockResolvedValue([]),+}));++vi.mock("@/components/HelpLink", () => ({+ DocsMenu: () => null,+}));++vi.mock("./how_it_works", () => ({+ default: () => <div data-testid="how-it-works">How It Works</div>,+}));++vi.mock("@/components/provider_info_helpers", () => ({+ Providers: { OpenAI: "OpenAI" },+ provider_map: { OpenAI: "openai" },+ providerLogoMap: {},+ getProviderLogoAndName: (providerValue: string) => ({ logo: "", displayName: providerValue }),+}));++const ADMIN_PROPS = {+ userID: "user-1",+ userRole: "proxy_admin",+ accessToken: "test-token",+};+describe("CostTrackingSettings submit paths", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockDiscountConfig.mockReturnValue({});+ mockMarginConfig.mockReturnValue({});+ });++ const openDiscountModal = async (user: ReturnType<typeof userEvent.setup>) => {+ renderWithProviders(<CostTrackingSettings {...ADMIN_PROPS} />);+ const header = screen.getByText("Provider Discounts").closest("button");+ if (header) await user.click(header);+ await user.click(await screen.findByRole("button", { name: /add provider discount/i }));+ await screen.findByText("Add Provider Discount", { selector: "h2" });+ };++ const submitDiscount = () =>+ screen+ .getAllByRole("button")+ .filter((button) => (button.textContent || "").trim() === "Add Provider Discount")+ .pop()!;++ it("requests the discount exactly once per click", async () => {+ const user = userEvent.setup();+ await openDiscountModal(user);++ await user.click(screen.getAllByRole("combobox")[0]);+ await user.click((await screen.findAllByRole("option"))[0]);+ await user.type(screen.getByLabelText(/Discount Percentage/i), "5");+ await user.click(submitDiscount());++ await waitFor(() => expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalled());+ expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalledTimes(1);+ expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalledWith("OpenAI", "5");+ });++ it("requests the margin exactly once per click", async () => {+ const user = userEvent.setup();+ renderWithProviders(<CostTrackingSettings {...ADMIN_PROPS} />);+ const header = screen.getByText("Fee/Price Margin").closest("button");+ if (header) await user.click(header);+ await user.click(await screen.findByRole("button", { name: /add provider margin/i }));+ await screen.findByText("Add Provider Margin", { selector: "h2" });++ await user.click(screen.getAllByRole("combobox")[0]);+ await user.click((await screen.findAllByRole("option"))[0]);+ await user.type(screen.getByLabelText(/Margin Percentage/i), "10");++ const submit = screen+ .getAllByRole("button")+ .filter((button) => (button.textContent || "").trim() === "Add Provider Margin")+ .pop()!;+ await user.click(submit);++ await waitFor(() => expect(stableMarginCallbacks.handleAddMargin).toHaveBeenCalled());+ expect(stableMarginCallbacks.handleAddMargin).toHaveBeenCalledTimes(1);+ });++ it("requests the discount exactly once when Enter is pressed in the discount field", async () => {+ const user = userEvent.setup();+ await openDiscountModal(user);++ await user.click(screen.getAllByRole("combobox")[0]);+ await user.click((await screen.findAllByRole("option"))[0]);+ await user.type(screen.getByLabelText(/Discount Percentage/i), "5{Enter}");++ await waitFor(() => expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalled());+ expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalledTimes(1);+ expect(stableDiscountCallbacks.handleAddProvider).toHaveBeenCalledWith("OpenAI", "5");+ });++ it("leaves Enter inert in the margin field while the button still submits", async () => {+ const user = userEvent.setup();+ renderWithProviders(<CostTrackingSettings {...ADMIN_PROPS} />);+ const header = screen.getByText("Fee/Price Margin").closest("button");+ if (header) await user.click(header);+ await user.click(await screen.findByRole("button", { name: /add provider margin/i }));+ await screen.findByText("Add Provider Margin", { selector: "h2" });++ await user.click(screen.getAllByRole("combobox")[0]);+ await user.click((await screen.findAllByRole("option"))[0]);+ await user.type(screen.getByLabelText(/Margin Percentage/i), "10{Enter}");++ expect(stableMarginCallbacks.handleAddMargin).not.toHaveBeenCalled();++ const submit = screen+ .getAllByRole("button")+ .filter((button) => (button.textContent || "").trim() === "Add Provider Margin")+ .pop()!;+ await user.click(submit);++ await waitFor(() => expect(stableMarginCallbacks.handleAddMargin).toHaveBeenCalledTimes(1));+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsxindex 7f86bad3028..32121e90a77 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-tracking/_components/cost_tracking_settings.tsx@@ -1,6 +1,6 @@import React, { useState, useEffect } from "react";import { ChevronDown } from "lucide-react";-import { Modal, Form } from "antd";+import { Modal } from "antd";import {AlertDialog,AlertDialogCancel,@@ -66,8 +66,6 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useconst [models, setModels] = useState<string[]>([]);const [pendingRemoval, setPendingRemoval] = useState<PendingRemoval | null>(null);const [isRemoving, setIsRemoving] = useState(false);- const [form] = Form.useForm();- const [marginForm] = Form.useForm();const isProxyAdmin = userRole === "proxy_admin" || userRole === "Admin";@@ -118,15 +116,10 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useconst handleModalCancel = () => {setIsModalVisible(false);- form.resetFields();setSelectedProvider(undefined);setNewDiscount("");};- const handleFormSubmit = () => {- handleAddProvider();- };-const handleRemoveProvider = (provider: string, providerDisplayName: string) => {setPendingRemoval({ kind: "discount", provider, displayName: providerDisplayName });};@@ -164,7 +157,6 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useconst handleMarginModalCancel = () => {setIsMarginModalVisible(false);- marginForm.resetFields();setSelectedMarginProvider(undefined);setPercentageValue("");setFixedAmountValue("");@@ -356,7 +348,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useSelect a provider and set its discount percentage. Enter a value between 0% and 100% (e.g., 5 for a 5%discount).</p>- <Form form={form} onFinish={handleFormSubmit} layout="vertical" className="space-y-6">+ <form onSubmit={(event) => event.preventDefault()} className="space-y-6"><AddProviderFormdiscountConfig={discountConfig}selectedProvider={selectedProvider}@@ -365,7 +357,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useonDiscountChange={setNewDiscount}onAddProvider={handleAddProvider}/>- </Form>+ </form></div></Modal>@@ -390,7 +382,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useSelect a provider (or "Global" for all providers) and configure the margin. You can usepercentage-based or fixed amount.</p>- <Form form={marginForm} layout="vertical" className="space-y-6">+ <div className="space-y-6"><AddMarginFormmarginConfig={marginConfig}selectedProvider={selectedMarginProvider}@@ -403,7 +395,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({ userID, useonFixedAmountChange={setFixedAmountValue}onAddProvider={handleAddMargin}/>- </Form>+ </div></div></Modal></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.integration.test.tsxnew file mode 100644index 00000000000..edb0ef2802e--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.integration.test.tsx@@ -0,0 +1,222 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import UserInfoView from "./user_info_view";++const mockTeamMemberAddCall = vi.fn();+const mockTeamMemberDeleteCall = vi.fn();+const mockTeamListCall = vi.fn();+const mockUserGetInfoV2 = vi.fn();+const mockTeamInfoCall = vi.fn();+const mockUserUpdateUserCall = vi.fn();+const mockFetchMCPServers = vi.fn();+const mockListMCPTools = vi.fn();++const MCP_SERVER = { server_id: "srv-1", server_name: "GitHub MCP", alias: "GitHub MCP" };++const MOCK_USER_DATA = {+ user_id: "user-123",+ user_email: "[email protected]",+ user_alias: "Test Alias",+ user_role: "admin",+ spend: 0,+ max_budget: 100,+ models: [],+ budget_duration: "30d",+ budget_reset_at: null,+ metadata: {},+ created_at: "2025-01-01T00:00:00.000Z",+ updated_at: "2025-01-02T00:00:00.000Z",+ sso_user_id: null,+ teams: ["team-1", "team-2"],+ object_permission: {+ mcp_servers: ["srv-1"],+ mcp_access_groups: ["dev-group"],+ mcp_tool_permissions: { "srv-1": ["list_issues"] },+ },+};++const MOCK_USER_DATA_NO_TEAMS = {+ ...MOCK_USER_DATA,+ teams: [],+};++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn() }),+ usePathname: () => "/users",+ useSearchParams: () => new URLSearchParams(window.location.search),+}));++vi.mock("@/components/networking", () => {+ return {+ serverRootPath: "/",+ userGetInfoV2: (...args: unknown[]) => mockUserGetInfoV2(...args),+ userDeleteCall: vi.fn(),+ userUpdateUserCall: (...args: unknown[]) => mockUserUpdateUserCall(...args),+ modelAvailableCall: vi.fn().mockResolvedValue({ data: [] }),+ invitationCreateCall: vi.fn(),+ teamInfoCall: (...args: unknown[]) => mockTeamInfoCall(...args),+ teamListCall: (...args: unknown[]) => mockTeamListCall(...args),+ teamMemberAddCall: (...args: unknown[]) => mockTeamMemberAddCall(...args),+ teamMemberDeleteCall: (...args: unknown[]) => mockTeamMemberDeleteCall(...args),+ getProxyBaseUrl: () => "https://litellm.test",+ fetchMCPServers: (...args: unknown[]) => mockFetchMCPServers(...args),+ fetchMCPToolsets: vi.fn().mockResolvedValue([]),+ listMCPTools: (...args: unknown[]) => mockListMCPTools(...args),+ };+});++vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({+ useMCPServers: () => ({ data: [MCP_SERVER], isLoading: false }),+}));+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPAccessGroups", () => ({+ useMCPAccessGroups: () => ({ data: ["dev-group"], isLoading: false }),+}));+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPToolsets", () => ({+ useMCPToolsets: () => ({ data: [], isLoading: false }),+}));+describe("UserInfoView add-to-team form", () => {+ const defaultProps = {+ userId: "user-123",+ onClose: vi.fn(),+ accessToken: "test-token",+ userRole: "proxy_admin" as string | null,+ possibleUIRoles: null,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mockUserGetInfoV2.mockResolvedValue(MOCK_USER_DATA);+ mockTeamInfoCall.mockImplementation((_token: string, teamId: string) => {+ const teamMap: Record<string, any> = {+ "team-1": { team_id: "team-1", team_info: { team_alias: "Alpha Team" } },+ "team-2": { team_id: "team-2", team_info: { team_alias: "Beta Team" } },+ "team-3": { team_id: "team-3", team_info: { team_alias: "Gamma Team" } },+ };+ return Promise.resolve(teamMap[teamId] || { team_id: teamId, team_info: { team_alias: null } });+ });+ mockTeamListCall.mockResolvedValue([+ { team_id: "team-1", team_alias: "Alpha Team" },+ { team_id: "team-2", team_alias: "Beta Team" },+ { team_id: "team-3", team_alias: "Gamma Team" },+ ]);+ mockTeamMemberAddCall.mockResolvedValue({});+ mockFetchMCPServers.mockResolvedValue([MCP_SERVER]);+ mockListMCPTools.mockResolvedValue({ tools: [] });+ });++ const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });++ const openAddTeam = async (user: ReturnType<typeof userEvent.setup>, anchorTeam = "Alpha Team") => {+ render(<UserInfoView {...defaultProps} />);+ await screen.findByText(anchorTeam);+ await user.click(screen.getByText("Add Team"));+ await screen.findByText("Add User to Team");+ };++ const teamField = () => screen.getAllByRole("combobox")[0];+ const roleField = () => screen.getAllByRole("combobox")[1];+ const submitButton = () => screen.getByRole("button", { name: /Add to Team|Adding\.\.\./i });++ const chooseTeam = async (user: ReturnType<typeof userEvent.setup>, alias: string) => {+ await user.click(teamField());+ await user.click(await screen.findByTitle(alias));+ };++ it("offers only the teams the user is not already a member of", async () => {+ const user = setup();+ await openAddTeam(user);++ await user.click(teamField());++ expect(await screen.findByTitle("Gamma Team")).toBeInTheDocument();+ expect(screen.queryByTitle("Alpha Team")).not.toBeInTheDocument();+ expect(screen.queryByTitle("Beta Team")).not.toBeInTheDocument();+ });++ it("shows the default role name on the trigger rather than a blank or raw value", async () => {+ const user = userEvent.setup();+ await openAddTeam(user);++ expect(screen.getAllByRole("combobox")[1]).toHaveTextContent("user");+ });++ it("adds the user to the chosen team with the default role", async () => {+ const user = setup();+ await openAddTeam(user);++ await chooseTeam(user, "Gamma Team");+ await user.click(submitButton());++ await waitFor(() => expect(mockTeamMemberAddCall).toHaveBeenCalledTimes(1));+ expect(mockTeamMemberAddCall).toHaveBeenCalledWith("test-token", "team-3", {+ role: "user",+ user_id: "user-123",+ });+ });++ it("sends the admin role when it is chosen", async () => {+ const user = setup();+ await openAddTeam(user);++ await chooseTeam(user, "Gamma Team");+ await user.click(roleField());+ await user.click(await screen.findByText("admin", { selector: "span.font-medium" }));+ await user.click(submitButton());++ await waitFor(() => expect(mockTeamMemberAddCall).toHaveBeenCalledTimes(1));+ expect(mockTeamMemberAddCall).toHaveBeenCalledWith("test-token", "team-3", {+ role: "admin",+ user_id: "user-123",+ });+ });++ it("keeps the submit disabled until a team is chosen", async () => {+ const user = setup();+ await openAddTeam(user);++ expect(submitButton()).toBeDisabled();++ await chooseTeam(user, "Gamma Team");++ expect(submitButton()).toBeEnabled();+ });++ it("sends nothing while no team is chosen", async () => {+ const user = setup();+ await openAddTeam(user);++ await user.click(submitButton());++ expect(mockTeamMemberAddCall).not.toHaveBeenCalled();+ });++ it("narrows the team list to the aliases matching what was typed", async () => {+ mockUserGetInfoV2.mockResolvedValue(MOCK_USER_DATA_NO_TEAMS);+ const user = setup();+ render(<UserInfoView {...defaultProps} />);+ await screen.findByText("Add Team");+ await user.click(screen.getByText("Add Team"));+ await screen.findByText("Add User to Team");++ await user.click(teamField());+ await screen.findByTitle("Alpha Team");++ await user.keyboard("Gam");++ expect(await screen.findByTitle("Gamma Team")).toBeInTheDocument();+ await waitFor(() => expect(screen.queryByTitle("Alpha Team")).not.toBeInTheDocument());+ });++ it("keeps the dialog open when the member could not be added", async () => {+ mockTeamMemberAddCall.mockRejectedValue(new Error("nope"));+ const user = setup();+ await openAddTeam(user);++ await chooseTeam(user, "Gamma Team");+ await user.click(submitButton());++ await waitFor(() => expect(mockTeamMemberAddCall).toHaveBeenCalledTimes(1));+ expect(screen.getByText("Add User to Team")).toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsxindex c4b09f7fffd..bd542380539 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx@@ -32,7 +32,17 @@ import {teamMemberDeleteCall,Member,} from "@/components/networking";-import { Button as AntdButton, Modal, Select as AntdSelect, Form, Tooltip } from "antd";+import { Button as AntdButton, Modal, Tooltip } from "antd";+import { Field, FieldGroup, FieldLabel } from "@/components/shared/form/field";+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+} from "@/components/ui/combobox";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { rolesWithWriteAccess } from "@/utils/roles";import { teamDetailHref } from "@/utils/entityLinks";import { BadgeLink } from "@/components/shared/BadgeLink";@@ -65,6 +75,19 @@ interface TeamDisplayInfo {team_alias: string | null;}+const ADD_TEAM_FIELD_ID = "add-team-team";+const ADD_TEAM_ROLE_FIELD_ID = "add-team-role";++interface TeamOption {+ team_id: string;+ team_alias: string;+}++const MEMBER_ROLE_OPTIONS = [+ { value: "user", hint: "Can view team info, but not manage it" },+ { value: "admin", hint: "Can create team keys, add members, and manage settings" },+] as const;+export default function UserInfoView({userId,onClose,@@ -258,6 +281,8 @@ export default function UserInfoView({const availableTeamsForAdd = allTeams.filter((t) => !teamDetails.some((td) => td.team_id === t.team_id));+ const selectedTeamOption = availableTeamsForAdd.find((team) => team.team_id === selectedTeamId) ?? null;+const handleResetPassword = async () => {if (!accessToken) {toast.fromError("Access token not found");@@ -690,53 +715,62 @@ export default function UserInfoView({width={500}maskClosable={!isAddingTeam}>- <Form layout="vertical" onFinish={handleAddTeamSubmit}>- <Form.Item label="Team" required>- <AntdSelect- showSearch- value={selectedTeamId || undefined}- onChange={setSelectedTeamId}- placeholder="Select a team"- filterOption={(input, option) => {- const team = availableTeamsForAdd.find((t) => t.team_id === option?.value);- if (!team) return false;- return team.team_alias.toLowerCase().includes(input.toLowerCase());- }}- loading={isLoadingTeams}- >- {availableTeamsForAdd.map((team) => (- <AntdSelect.Option key={team.team_id} value={team.team_id}>- {team.team_alias}- </AntdSelect.Option>- ))}- </AntdSelect>- </Form.Item>-- <Form.Item label="Member Role">- <AntdSelect value={selectedRole} onChange={setSelectedRole}>- <AntdSelect.Option value="user">- <Tooltip title="Can view team info, but not manage it">- <span className="font-medium">user</span>- <span className="ml-2 text-gray-500 text-sm">- Can view team info, but not manage it</span>- </Tooltip>- </AntdSelect.Option>- <AntdSelect.Option value="admin">- <Tooltip title="Can create team keys, add members, and manage settings">- <span className="font-medium">admin</span>- <span className="ml-2 text-gray-500 text-sm">- - Can create team keys, add members, and manage settings- </span>- </Tooltip>- </AntdSelect.Option>- </AntdSelect>- </Form.Item>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ handleAddTeamSubmit();+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={ADD_TEAM_FIELD_ID}>Team</FieldLabel>+ <Combobox+ items={availableTeamsForAdd}+ value={selectedTeamOption}+ onValueChange={(team: TeamOption | null) => setSelectedTeamId(team?.team_id ?? "")}+ itemToStringLabel={(team: TeamOption) => team.team_alias}+ isItemEqualToValue={(team: TeamOption, value: TeamOption) => team.team_id === value.team_id}+ >+ <ComboboxInput id={ADD_TEAM_FIELD_ID} placeholder="Select a team" className="w-full" />+ <ComboboxContent>+ <ComboboxEmpty>No teams found</ComboboxEmpty>+ <ComboboxList>+ {(team: TeamOption) => (+ <ComboboxItem key={team.team_id} value={team} title={team.team_alias}>+ {team.team_alias}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </Field>++ <Field>+ <FieldLabel htmlFor={ADD_TEAM_ROLE_FIELD_ID}>Member Role</FieldLabel>+ <Select value={selectedRole} onValueChange={(value) => value !== null && setSelectedRole(value)}>+ <SelectTrigger id={ADD_TEAM_ROLE_FIELD_ID} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {MEMBER_ROLE_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value} title={option.value}>+ <Tooltip title={option.hint}>+ <span className="font-medium">{option.value}</span>+ <span className="ml-2 text-muted-foreground text-sm">- {option.hint}</span>+ </Tooltip>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </FieldGroup><div className="text-right mt-4"><AntdButton type="primary" htmlType="submit" loading={isAddingTeam} disabled={!selectedTeamId}>{isAddingTeam ? "Adding..." : "Add to Team"}</AntdButton></div>- </Form>+ </form></Modal></div>);diff --git a/ui/litellm-dashboard/src/components/alerting/dynamic_form.integration.test.tsx b/ui/litellm-dashboard/src/components/alerting/dynamic_form.integration.test.tsxnew file mode 100644index 00000000000..89eee83374a--- /dev/null+++ b/ui/litellm-dashboard/src/components/alerting/dynamic_form.integration.test.tsx@@ -0,0 +1,225 @@+import React from "react";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, it, expect, vi } from "vitest";+import DynamicForm from "./dynamic_form";++interface Setting {+ field_name: string;+ field_description: string;+ field_type: string;+ field_value: unknown;+ stored_in_db: boolean | null;+ premium_field: boolean;+}++const SETTINGS: Setting[] = [+ {+ field_name: "daily_report_frequency",+ field_description: "How often the report runs",+ field_type: "Integer",+ field_value: 12,+ stored_in_db: true,+ premium_field: false,+ },+ {+ field_name: "region_name",+ field_description: "Region to watch",+ field_type: "String",+ field_value: "us-east",+ stored_in_db: false,+ premium_field: false,+ },+ {+ field_name: "slack_alerting",+ field_description: "Send to slack",+ field_type: "Boolean",+ field_value: false,+ stored_in_db: null,+ premium_field: false,+ },+];++const renderForm = (+ overrides: {+ settings?: Setting[];+ premiumUser?: boolean;+ handleSubmit?: (values: Record<string, unknown>) => void;+ handleInputChange?: (fieldName: string, newValue: unknown) => void;+ handleResetField?: (fieldName: string, index: number) => void;+ } = {},+) => {+ const handleSubmit = overrides.handleSubmit ?? vi.fn();+ const handleInputChange = overrides.handleInputChange ?? vi.fn();+ const handleResetField = overrides.handleResetField ?? vi.fn();+ render(+ <table>+ <tbody>+ <DynamicForm+ alertingSettings={overrides.settings ?? SETTINGS}+ handleInputChange={handleInputChange}+ handleResetField={handleResetField}+ handleSubmit={handleSubmit}+ premiumUser={overrides.premiumUser ?? false}+ />+ </tbody>+ </table>,+ );+ return { handleSubmit, handleInputChange, handleResetField };+};++const submit = async (user: ReturnType<typeof userEvent.setup>) =>+ user.click(screen.getByRole("button", { name: "Update Settings" }));++describe("DynamicForm submit payload", () => {+ it("submits nothing when no field has been changed", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await submit(user);++ expect(handleSubmit).not.toHaveBeenCalled();+ });++ it("submits only the fields the user actually changed", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await user.type(screen.getByDisplayValue("us-east"), "Z");+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledTimes(1);+ expect(handleSubmit).toHaveBeenCalledWith({ region_name: "us-eastZ" });+ });++ it("submits an Integer field as a string, not a number", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await user.type(screen.getByDisplayValue("12"), "7");+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledWith({ daily_report_frequency: "127" });+ });++ it("submits a Boolean field as a boolean", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await user.click(screen.getByRole("switch"));+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledWith({ slack_alerting: true });+ });++ it("submits every changed field together", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await user.type(screen.getByDisplayValue("us-east"), "Z");+ await user.click(screen.getByRole("switch"));+ await user.type(screen.getByDisplayValue("12"), "9");+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledWith({+ daily_report_frequency: "129",+ region_name: "us-eastZ",+ slack_alerting: true,+ });+ });++ it("submits nothing when the only change cleared a field to an empty string", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm();++ await user.clear(screen.getByDisplayValue("us-east"));+ await submit(user);++ expect(handleSubmit).not.toHaveBeenCalled();+ });++ it("still submits a false Boolean, which is never treated as empty", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm({+ settings: [{ ...SETTINGS[2], field_value: true }],+ });++ await user.click(screen.getByRole("switch"));+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledWith({ slack_alerting: false });+ });+});++describe("DynamicForm change notifications", () => {+ it("reports a Boolean change to the parent as a boolean", async () => {+ const user = userEvent.setup();+ const { handleInputChange } = renderForm();++ await user.click(screen.getByRole("switch"));++ expect(handleInputChange).toHaveBeenCalledWith("slack_alerting", true);+ });++ it("reports an Integer change to the parent as a number", async () => {+ const user = userEvent.setup();+ const { handleInputChange } = renderForm();++ await user.type(screen.getByDisplayValue("12"), "8");++ expect(handleInputChange).toHaveBeenCalledWith("daily_report_frequency", 128);+ });++ it("reports a reset with the field name and its row index", async () => {+ const user = userEvent.setup();+ const { handleResetField } = renderForm();++ const row = screen.getByText("region_name").closest("tr");+ const reset = row?.querySelector(".tremor-Icon-root");+ await user.click(reset as Element);++ expect(handleResetField).toHaveBeenCalledWith("region_name", 1);+ });+});++describe("DynamicForm premium gating", () => {+ it("hides the control behind an upsell and registers no value when the user is not premium", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm({+ settings: [{ ...SETTINGS[1], premium_field: true }],+ premiumUser: false,+ });++ expect(screen.getByText(/Enterprise Feature/)).toBeInTheDocument();+ expect(screen.queryByDisplayValue("us-east")).not.toBeInTheDocument();++ await submit(user);++ expect(handleSubmit).not.toHaveBeenCalled();+ });++ it("renders the real control for a premium user on a premium field", async () => {+ const user = userEvent.setup();+ const { handleSubmit } = renderForm({+ settings: [{ ...SETTINGS[1], premium_field: true }],+ premiumUser: true,+ });++ await user.type(screen.getByDisplayValue("us-east"), "Q");+ await submit(user);++ expect(handleSubmit).toHaveBeenCalledWith({ region_name: "us-eastQ" });+ });+});++describe("DynamicForm presentation", () => {+ it("shows each field name, description and storage origin", () => {+ renderForm();++ expect(screen.getByText("daily_report_frequency")).toBeInTheDocument();+ expect(screen.getByText("How often the report runs")).toBeInTheDocument();+ expect(screen.getByText("In DB")).toBeInTheDocument();+ expect(screen.getByText("In Config")).toBeInTheDocument();+ expect(screen.getByText("Not Set")).toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/alerting/dynamic_form.tsx b/ui/litellm-dashboard/src/components/alerting/dynamic_form.tsxindex 9457724f9c5..1ee3833c1b9 100644--- a/ui/litellm-dashboard/src/components/alerting/dynamic_form.tsx+++ b/ui/litellm-dashboard/src/components/alerting/dynamic_form.tsx@@ -1,7 +1,9 @@import React from "react";-import { Form, Input, InputNumber, Button as Button2 } from "antd";+import { useForm } from "react-hook-form";import { TrashIcon, CheckCircleIcon } from "@heroicons/react/outline";import { Button, Badge, Icon, Text, TableRow, TableCell, Switch } from "@tremor/react";+import { Input } from "@/components/ui/input";+interface AlertingSetting {field_name: string;field_description: string;@@ -19,6 +21,8 @@ interface DynamicFormProps {premiumUser: boolean;}+type AlertingFormValues = Record<string, string | boolean>;+const DynamicForm: React.FC<DynamicFormProps> = ({alertingSettings,handleInputChange,@@ -26,95 +30,70 @@ const DynamicForm: React.FC<DynamicFormProps> = ({handleSubmit,premiumUser,}) => {- const [form] = Form.useForm();+ const form = useForm<AlertingFormValues>({ defaultValues: {} });- const onFinish = () => {- const formData = form.getFieldsValue();- const isEmpty = Object.entries(formData).every(([key, value]) => {+ const onFinish = (formData: AlertingFormValues) => {+ const isEmpty = Object.entries(formData).every(([, value]) => {if (typeof value === "boolean") {- return false; // Boolean values are never considered empty+ return false;}return value === "" || value === null || value === undefined;});if (!isEmpty) {handleSubmit(formData);- } else {}};+ const handleNumericChange = (setting: AlertingSetting, raw: string) => {+ form.setValue(setting.field_name, raw);+ handleInputChange(setting.field_name, raw === "" ? null : Number(raw));+ };++ const handleTextChange = (setting: AlertingSetting, event: React.ChangeEvent<HTMLInputElement>) => {+ form.setValue(setting.field_name, event.target.value);+ handleInputChange(setting.field_name, event);+ };++ const handleToggle = (setting: AlertingSetting, checked: boolean) => {+ form.setValue(setting.field_name, checked);+ handleInputChange(setting.field_name, checked);+ };++ const renderControl = (setting: AlertingSetting) => {+ if (setting.field_type === "Integer") {+ return (+ <Input+ type="number"+ step={1}+ value={setting.field_value ?? ""}+ onChange={(event) => handleNumericChange(setting, event.target.value)}+ />+ );+ }+ if (setting.field_type === "Boolean") {+ return <Switch checked={setting.field_value} onChange={(checked) => handleToggle(setting, checked)} />;+ }+ return <Input value={setting.field_value ?? ""} onChange={(event) => handleTextChange(setting, event)} />;+ };+return (- <Form form={form} onFinish={onFinish} labelAlign="left">+ <form onSubmit={form.handleSubmit(onFinish)} noValidate>{alertingSettings.map((value, index) => (<TableRow key={index}><TableCell align="center"><Text>{value.field_name}</Text>- <p- style={{- fontSize: "0.65rem",- color: "#808080",- fontStyle: "italic",- }}- className="mt-1"- >- {value.field_description}- </p>+ <p className="mt-1 text-[0.65rem] italic text-muted-foreground">{value.field_description}</p></TableCell>- {value.premium_field ? (- premiumUser ? (- <Form.Item name={value.field_name}>- <TableCell>- {value.field_type === "Integer" ? (- <InputNumber- step={1}- value={value.field_value}- onChange={(e) => handleInputChange(value.field_name, e)}- />- ) : value.field_type === "Boolean" ? (- <Switch- checked={value.field_value}- onChange={(checked) => handleInputChange(value.field_name, checked)}- />- ) : (- <Input value={value.field_value} onChange={(e) => handleInputChange(value.field_name, e)} />- )}- </TableCell>- </Form.Item>- ) : (- <TableCell>- <Button className="flex items-center justify-center">- <a href="https://forms.gle/W3U4PZpJGFHWtHyA9" target="_blank">- ✨ Enterprise Feature- </a>- </Button>- </TableCell>- )+ {value.premium_field && !premiumUser ? (+ <TableCell>+ <Button className="flex items-center justify-center">+ <a href="https://forms.gle/W3U4PZpJGFHWtHyA9" target="_blank">+ ✨ Enterprise Feature+ </a>+ </Button>+ </TableCell>) : (- <Form.Item- name={value.field_name}- className="mb-0"- valuePropName={value.field_type === "Boolean" ? "checked" : "value"}- >- <TableCell>- {value.field_type === "Integer" ? (- <InputNumber- step={1}- value={value.field_value}- onChange={(e) => handleInputChange(value.field_name, e)}- className="p-0"- />- ) : value.field_type === "Boolean" ? (- <Switch- checked={value.field_value}- onChange={(checked) => {- handleInputChange(value.field_name, checked);- form.setFieldsValue({ [value.field_name]: checked });- }}- />- ) : (- <Input value={value.field_value} onChange={(e) => handleInputChange(value.field_name, e)} />- )}- </TableCell>- </Form.Item>+ <TableCell>{renderControl(value)}</TableCell>)}<TableCell>{value.stored_in_db == true ? (@@ -122,9 +101,9 @@ const DynamicForm: React.FC<DynamicFormProps> = ({In DB</Badge>) : value.stored_in_db == false ? (- <Badge className="text-gray bg-white outline-solid">In Config</Badge>+ <Badge className="text-gray bg-background outline-solid">In Config</Badge>) : (- <Badge className="text-gray bg-white outline-solid">Not Set</Badge>+ <Badge className="text-gray bg-background outline-solid">Not Set</Badge>)}</TableCell><TableCell>@@ -135,9 +114,9 @@ const DynamicForm: React.FC<DynamicFormProps> = ({</TableRow>))}<div>- <Button2 htmlType="submit">Update Settings</Button2>+ <Button type="submit">Update Settings</Button></div>- </Form>+ </form>);};diff --git a/ui/litellm-dashboard/src/components/cloudzero_export_modal.integration.test.tsx b/ui/litellm-dashboard/src/components/cloudzero_export_modal.integration.test.tsxnew file mode 100644index 00000000000..07eff973ea3--- /dev/null+++ b/ui/litellm-dashboard/src/components/cloudzero_export_modal.integration.test.tsx@@ -0,0 +1,155 @@+import React from "react";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import CloudZeroExportModal from "./cloudzero_export_modal";++vi.mock("@/lib/toast", () => ({+ toast: { success: vi.fn(), fromError: vi.fn(), info: vi.fn() },+}));++vi.mock("@/components/networking", () => ({+ getGlobalLitellmHeaderName: () => "Authorization",+}));++const jsonResponse = (status: number, body: unknown) =>+ ({ ok: status >= 200 && status < 300, status, json: async () => body }) as Response;++const bodyOf = (call: unknown[]) => JSON.parse((call[1] as RequestInit).body as string);++const callsTo = (fetchMock: ReturnType<typeof vi.fn>, path: string) =>+ fetchMock.mock.calls.filter((call) => call[0] === path);++describe("CloudZeroExportModal", () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn(async (url: string) => {+ if (url === "/cloudzero/settings") return jsonResponse(404, { error: "not configured" });+ if (url === "/cloudzero/init") return jsonResponse(200, { message: "saved" });+ if (url === "/cloudzero/export") return jsonResponse(200, { message: "exported" });+ return jsonResponse(500, { error: "unexpected" });+ });+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ const open = () => render(<CloudZeroExportModal isOpen onClose={vi.fn()} accessToken="sk-test" />);++ it("saves the settings with a hardcoded UTC timezone before exporting", async () => {+ const user = userEvent.setup();+ open();++ await user.type(await screen.findByLabelText("CloudZero API Key"), "cz-key-123");+ await user.type(screen.getByLabelText("Connection ID"), "conn-abc");+ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ await waitFor(() => expect(callsTo(fetchMock, "/cloudzero/init")).toHaveLength(1));++ const [initCall] = callsTo(fetchMock, "/cloudzero/init");+ expect((initCall[1] as RequestInit).method).toBe("POST");+ expect(bodyOf(initCall)).toEqual({+ api_key: "cz-key-123",+ connection_id: "conn-abc",+ timezone: "UTC",+ });+ });++ it("exports with a fixed limit and operation once the settings are saved", async () => {+ const user = userEvent.setup();+ open();++ await user.type(await screen.findByLabelText("CloudZero API Key"), "cz-key-123");+ await user.type(screen.getByLabelText("Connection ID"), "conn-abc");+ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ await waitFor(() => expect(callsTo(fetchMock, "/cloudzero/export")).toHaveLength(1));++ const [exportCall] = callsTo(fetchMock, "/cloudzero/export");+ expect((exportCall[1] as RequestInit).method).toBe("POST");+ expect(bodyOf(exportCall)).toEqual({ limit: 100000, operation: "replace_hourly" });+ });++ it("sends nothing while a required field is still empty", async () => {+ const user = userEvent.setup();+ open();++ await user.type(await screen.findByLabelText("CloudZero API Key"), "cz-key-123");+ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ await screen.findByText("Please enter the CloudZero connection ID");+ expect(callsTo(fetchMock, "/cloudzero/init")).toHaveLength(0);+ expect(callsTo(fetchMock, "/cloudzero/export")).toHaveLength(0);+ });++ it("reports both required messages when the form is untouched", async () => {+ const user = userEvent.setup();+ open();++ await screen.findByLabelText("CloudZero API Key");+ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ expect(await screen.findByText("Please enter your CloudZero API key")).toBeInTheDocument();+ expect(screen.getByText("Please enter the CloudZero connection ID")).toBeInTheDocument();+ expect(callsTo(fetchMock, "/cloudzero/init")).toHaveLength(0);+ });++ it("skips the save entirely when CloudZero is already configured", async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url === "/cloudzero/settings")+ return jsonResponse(200, {+ api_key_masked: "cz-1****4567",+ connection_id: "conn-existing",+ status: "configured",+ });+ if (url === "/cloudzero/export") return jsonResponse(200, { message: "exported" });+ return jsonResponse(500, { error: "unexpected" });+ });+ const user = userEvent.setup();+ open();++ await screen.findByText(/conn-existing/);+ expect(screen.queryByLabelText("CloudZero API Key")).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ await waitFor(() => expect(callsTo(fetchMock, "/cloudzero/export")).toHaveLength(1));+ expect(callsTo(fetchMock, "/cloudzero/init")).toHaveLength(0);+ });++ it("masks the API key it echoes back after a successful save", async () => {+ const user = userEvent.setup();+ open();++ await user.type(await screen.findByLabelText("CloudZero API Key"), "cz-key-123456789");+ await user.type(screen.getByLabelText("Connection ID"), "conn-abc");+ await user.click(screen.getByRole("button", { name: "Export to CloudZero" }));++ await waitFor(() => expect(callsTo(fetchMock, "/cloudzero/export")).toHaveLength(1));+ expect(bodyOf(callsTo(fetchMock, "/cloudzero/init")[0]).api_key).toBe("cz-key-123456789");+ });++ it("switches to the CSV destination without touching the CloudZero endpoints", async () => {+ const user = userEvent.setup();+ open();++ await screen.findByLabelText("CloudZero API Key");+ await user.click(screen.getByRole("combobox"));+ await user.click(await screen.findByText("Export to CSV"));++ expect(screen.queryByLabelText("CloudZero API Key")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Export CSV" }));++ expect(callsTo(fetchMock, "/cloudzero/init")).toHaveLength(0);+ expect(callsTo(fetchMock, "/cloudzero/export")).toHaveLength(0);+ });++ it("keeps the API key entry obscured", async () => {+ open();+ expect(await screen.findByLabelText("CloudZero API Key")).toHaveAttribute("type", "password");+ });+});diff --git a/ui/litellm-dashboard/src/components/cloudzero_export_modal.tsx b/ui/litellm-dashboard/src/components/cloudzero_export_modal.tsxindex 2aaad786e91..7a937d32b3e 100644--- a/ui/litellm-dashboard/src/components/cloudzero_export_modal.tsx+++ b/ui/litellm-dashboard/src/components/cloudzero_export_modal.tsx@@ -1,8 +1,19 @@import React, { useState, useEffect } from "react";-import { Text, Button, Callout, TextInput } from "@tremor/react";-import { Modal, Form, Spin, Select } from "antd";+import { Text, Button, Callout } from "@tremor/react";+import { Modal, Spin, Select } from "antd";+import { z } from "zod/v4";import { getGlobalLitellmHeaderName } from "@/components/networking";import { toast } from "@/lib/toast";+import { PasswordInput } from "@/components/shared/PasswordInput";+import { FieldGroup } from "@/components/shared/form/field";+import { FormField } from "@/components/shared/form/FormField";+import { Input } from "@/components/ui/input";+import { useZodForm } from "@/lib/forms/useZodForm";++const cloudZeroSettingsSchema = z.object({+ api_key: z.string().min(1, "Please enter your CloudZero API key"),+ connection_id: z.string().min(1, "Please enter the CloudZero connection ID"),+});interface CloudZeroExportModalProps {isOpen: boolean;@@ -10,10 +21,7 @@ interface CloudZeroExportModalProps {accessToken: string | null;}-interface CloudZeroSettings {- api_key: string;- connection_id: string;-}+type CloudZeroSettings = z.output<typeof cloudZeroSettingsSchema>;interface CloudZeroSettingsView {api_key_masked: string;@@ -24,7 +32,9 @@ interface CloudZeroSettingsView {type ExportType = "cloudzero" | "csv";const CloudZeroExportModal: React.FC<CloudZeroExportModalProps> = ({ isOpen, onClose, accessToken }) => {- const [form] = Form.useForm();+ const form = useZodForm(cloudZeroSettingsSchema, {+ defaultValues: { api_key: "", connection_id: "" },+ });const [loading, setLoading] = useState(false);const [existingSettings, setExistingSettings] = useState<CloudZeroSettingsView | null>(null);const [settingsLoading, setSettingsLoading] = useState(false);@@ -53,9 +63,7 @@ const CloudZeroExportModal: React.FC<CloudZeroExportModalProps> = ({ isOpen, onCconst settings = await response.json();setExistingSettings(settings);// Pre-populate form with existing settings (except masked API key)- form.setFieldsValue({- connection_id: settings.connection_id,- });+ form.setValue("connection_id", settings.connection_id);} else if (response.status !== 404) {// 404 means no settings configured yet, which is fineconst errorData = await response.json();@@ -172,7 +180,11 @@ const CloudZeroExportModal: React.FC<CloudZeroExportModalProps> = ({ isOpen, onCif (exportType === "cloudzero") {// Check if settings exist, if not save them firstif (!existingSettings) {- const values = await form.validateFields();+ let values: CloudZeroSettings | undefined;+ await form.handleSubmit((formValues) => {+ values = formValues;+ })();+ if (!values) return;const success = await handleSaveCloudZeroSettings(values);if (!success) return;}@@ -183,7 +195,7 @@ const CloudZeroExportModal: React.FC<CloudZeroExportModalProps> = ({ isOpen, onC};const handleModalClose = () => {- form.resetFields();+ form.reset();setExportType("cloudzero");setExistingSettings(null);onClose();@@ -268,23 +280,21 @@ const CloudZeroExportModal: React.FC<CloudZeroExportModalProps> = ({ isOpen, onC)}{!existingSettings && (- <Form form={form} layout="vertical">- <Form.Item- label="CloudZero API Key"- name="api_key"- rules={[{ required: true, message: "Please enter your CloudZero API key" }]}- >- <TextInput type="password" placeholder="Enter your CloudZero API key" />- </Form.Item>+ <form onSubmit={(event) => event.preventDefault()}>+ <FieldGroup>+ <FormField control={form.control} name="api_key" label="CloudZero API Key">+ {({ ref, ...field }) => (+ <PasswordInput {...field} ref={ref} placeholder="Enter your CloudZero API key" />+ )}+ </FormField>- <Form.Item- label="Connection ID"- name="connection_id"- rules={[{ required: true, message: "Please enter the CloudZero connection ID" }]}- >- <TextInput placeholder="Enter CloudZero connection ID" />- </Form.Item>- </Form>+ <FormField control={form.control} name="connection_id" label="Connection ID">+ {({ ref, ...field }) => (+ <Input {...field} ref={ref} placeholder="Enter CloudZero connection ID" />+ )}+ </FormField>+ </FieldGroup>+ </form>)}</>)}