Skip to content

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]

feat(ui): add react-hook-form + zod form infrastructure (#34170)

yuneng-jiang72d458e416d1
diff --git a/ui/litellm-dashboard/package-lock.json b/ui/litellm-dashboard/package-lock.json
index 7a65b63b33c..49d289879d3 100644
--- a/ui/litellm-dashboard/package-lock.json
+++ b/ui/litellm-dashboard/package-lock.json
@@ -14,6 +14,7 @@
"@base-ui/react": "^1.6.0",
"@headlessui/tailwindcss": "0.2.2",
"@heroicons/react": "1.0.6",
+ "@hookform/resolvers": "5.4.0",
"@tanstack/react-pacer": "0.22.1",
"@tanstack/react-query": "5.100.7",
"@tanstack/react-table": "8.21.3",
@@ -34,13 +35,15 @@
"react": "18.3.1",
"react-copy-to-clipboard": "5.1.1",
"react-dom": "18.3.1",
+ "react-hook-form": "7.82.0",
"react-json-view-lite": "2.5.0",
"react-markdown": "9.1.0",
"react-syntax-highlighter": "15.6.6",
"recharts": "3.9.2",
"remark-gfm": "4.0.1",
"tailwind-merge": "3.4.0",
- "uuid": "14.0.0"
+ "uuid": "14.0.0",
+ "zod": "3.25.76"
},
"devDependencies": {
"@eslint/js": "9.39.2",
@@ -1556,6 +1559,18 @@
"react": ">= 16"
}
},
+ "node_modules/@hookform/resolvers": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.4.0.tgz",
+ "integrity": "sha512-EIsqr/t/qbinPIhGjMdtvutIN1Kk4uwbROE9/UQ93CAVGR7GkA7Y92+fX80OzXi/OB67jVFYwKGO1WzkxmkFZw==",
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/utils": "^0.3.0"
+ },
+ "peerDependencies": {
+ "react-hook-form": "^7.55.0"
+ }
+ },
"node_modules/@humanfs/core": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
@@ -11780,6 +11795,22 @@
"react": "^18.3.1"
}
},
+ "node_modules/react-hook-form": {
+ "version": "7.82.0",
+ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.82.0.tgz",
+ "integrity": "sha512-Zw/uFZ2dO+02GHlBn7JFGn8kZJ7LdM33B/0BXOovzFay+CMhf94JMw5BVu+F1tVkUKjNvBuaE3fz5BJhga10Tg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/react-hook-form"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17 || ^18 || ^19"
+ }
+ },
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
@@ -14156,7 +14187,6 @@
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
- "devOptional": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
diff --git a/ui/litellm-dashboard/package.json b/ui/litellm-dashboard/package.json
index b5e93d175bf..c29b53cd818 100644
--- a/ui/litellm-dashboard/package.json
+++ b/ui/litellm-dashboard/package.json
@@ -30,6 +30,7 @@
"@base-ui/react": "^1.6.0",
"@headlessui/tailwindcss": "0.2.2",
"@heroicons/react": "1.0.6",
+ "@hookform/resolvers": "5.4.0",
"@tanstack/react-pacer": "0.22.1",
"@tanstack/react-query": "5.100.7",
"@tanstack/react-table": "8.21.3",
@@ -50,13 +51,15 @@
"react": "18.3.1",
"react-copy-to-clipboard": "5.1.1",
"react-dom": "18.3.1",
+ "react-hook-form": "7.82.0",
"react-json-view-lite": "2.5.0",
"react-markdown": "9.1.0",
"react-syntax-highlighter": "15.6.6",
"recharts": "3.9.2",
"remark-gfm": "4.0.1",
"tailwind-merge": "3.4.0",
- "uuid": "14.0.0"
+ "uuid": "14.0.0",
+ "zod": "3.25.76"
},
"devDependencies": {
"@eslint/js": "9.39.2",
diff --git a/ui/litellm-dashboard/src/components/shared/form/FormField.test.tsx b/ui/litellm-dashboard/src/components/shared/form/FormField.test.tsx
new file mode 100644
index 00000000000..af9122e2bd5
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/form/FormField.test.tsx
@@ -0,0 +1,180 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import * as React from "react";
+import { useForm } from "react-hook-form";
+import { describe, expect, it, vi } from "vitest";
+import { z } from "zod/v4";
+
+import { Input } from "@/components/ui/input";
+
+import { FormField } from "./FormField";
+
+const schema = z.object({
+ team_alias: z.string().min(1, "Please input a team name"),
+ owner: z.string(),
+});
+
+type FormInput = z.input<typeof schema>;
+
+const TestForm = ({
+ onSubmit,
+ defaultValues = { team_alias: "team-a", owner: "" },
+ description,
+}: {
+ onSubmit: (values: z.output<typeof schema>) => void;
+ defaultValues?: FormInput;
+ description?: React.ReactNode;
+}) => {
+ const form = useForm<FormInput, unknown, z.output<typeof schema>>({
+ resolver: zodResolver(schema),
+ defaultValues,
+ });
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <FormField control={form.control} name="team_alias" label="Team Name" description={description}>
+ {(field) => <Input {...field} />}
+ </FormField>
+ <button type="submit">Save</button>
+ </form>
+ );
+};
+
+describe("FormField", () => {
+ it("associates the label with the control so it is reachable by its accessible name", () => {
+ render(<TestForm onSubmit={vi.fn()} />);
+
+ expect(screen.getByLabelText("Team Name")).toHaveValue("team-a");
+ });
+
+ it("gives each field instance a unique control id", () => {
+ const Harness = () => {
+ const form = useForm<FormInput>({ defaultValues: { team_alias: "", owner: "" } });
+ return (
+ <>
+ <FormField control={form.control} name="team_alias" label="One">
+ {(field) => <Input {...field} />}
+ </FormField>
+ <FormField control={form.control} name="owner" label="Two">
+ {(field) => <Input {...field} />}
+ </FormField>
+ </>
+ );
+ };
+ render(<Harness />);
+
+ expect(screen.getByLabelText("One").id).not.toBe(screen.getByLabelText("Two").id);
+ });
+
+ it("feeds edits back into form state and submits the parsed output", async () => {
+ const user = userEvent.setup();
+ const onSubmit = vi.fn();
+ render(<TestForm onSubmit={onSubmit} />);
+
+ await user.clear(screen.getByLabelText("Team Name"));
+ await user.type(screen.getByLabelText("Team Name"), "team-b");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ expect(onSubmit.mock.calls[0][0]).toEqual({ team_alias: "team-b", owner: "" });
+ });
+
+ it("renders the zod message and blocks submit when validation fails", async () => {
+ const user = userEvent.setup();
+ const onSubmit = vi.fn();
+ render(<TestForm onSubmit={onSubmit} />);
+
+ await user.clear(screen.getByLabelText("Team Name"));
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent("Please input a team name");
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("marks the control invalid and points aria-describedby at the message", async () => {
+ const user = userEvent.setup();
+ render(<TestForm onSubmit={vi.fn()} />);
+
+ await user.clear(screen.getByLabelText("Team Name"));
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ const control = await screen.findByLabelText("Team Name");
+ await waitFor(() => expect(control).toHaveAttribute("aria-invalid", "true"));
+ expect(control.getAttribute("aria-describedby")).toBe(screen.getByRole("alert").id);
+ });
+
+ it("leaves a valid control free of aria-invalid", () => {
+ render(<TestForm onSubmit={vi.fn()} />);
+
+ expect(screen.getByLabelText("Team Name")).not.toHaveAttribute("aria-invalid");
+ });
+
+ it("clears the message once the value becomes valid again", async () => {
+ const user = userEvent.setup();
+ render(<TestForm onSubmit={vi.fn()} />);
+
+ await user.clear(screen.getByLabelText("Team Name"));
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ expect(await screen.findByRole("alert")).toBeInTheDocument();
+
+ await user.type(screen.getByLabelText("Team Name"), "team-c");
+
+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
+ });
+
+ it("describes the control by its description when there is no error", () => {
+ render(<TestForm onSubmit={vi.fn()} description="Shown to team members" />);
+
+ const control = screen.getByLabelText("Team Name");
+ const describedBy = control.getAttribute("aria-describedby");
+
+ expect(describedBy).not.toBeNull();
+ expect(document.getElementById(describedBy!)).toHaveTextContent("Shown to team members");
+ });
+
+ it("describes the control by both description and error while invalid", async () => {
+ const user = userEvent.setup();
+ render(<TestForm onSubmit={vi.fn()} description="Shown to team members" />);
+
+ await user.clear(screen.getByLabelText("Team Name"));
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await screen.findByRole("alert");
+
+ const ids = screen.getByLabelText("Team Name").getAttribute("aria-describedby")?.split(" ") ?? [];
+
+ expect(ids).toHaveLength(2);
+ expect(ids).toContain(screen.getByRole("alert").id);
+ });
+
+ it("omits aria-describedby entirely when there is no description and no error", () => {
+ render(<TestForm onSubmit={vi.fn()} />);
+
+ expect(screen.getByLabelText("Team Name")).not.toHaveAttribute("aria-describedby");
+ });
+
+ it("hands the control a value and onChange so non-native widgets can be wired", async () => {
+ const user = userEvent.setup();
+ const seen: unknown[] = [];
+ const Harness = () => {
+ const form = useForm<FormInput>({ defaultValues: { team_alias: "team-a", owner: "" } });
+ return (
+ <FormField control={form.control} name="team_alias" label="Team Name">
+ {(field) => {
+ seen.push(field.value);
+ return (
+ <button type="button" onClick={() => field.onChange("from-widget")}>
+ widget
+ </button>
+ );
+ }}
+ </FormField>
+ );
+ };
+ render(<Harness />);
+
+ await user.click(screen.getByRole("button", { name: "widget" }));
+
+ await waitFor(() => expect(seen.at(-1)).toBe("from-widget"));
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/shared/form/FormField.tsx b/ui/litellm-dashboard/src/components/shared/form/FormField.tsx
new file mode 100644
index 00000000000..3b9783333cc
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/form/FormField.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import * as React from "react";
+import {
+ Controller,
+ type Control,
+ type ControllerRenderProps,
+ type FieldPath,
+ type FieldValues,
+} from "react-hook-form";
+
+import { Field, FieldDescription, FieldError, FieldLabel } from "./field";
+
+export type FormFieldControlProps<
+ TFieldValues extends FieldValues,
+ TName extends FieldPath<TFieldValues>,
+> = ControllerRenderProps<TFieldValues, TName> & {
+ id: string;
+ "aria-invalid": true | undefined;
+ "aria-describedby": string | undefined;
+};
+
+export interface FormFieldProps<TFieldValues extends FieldValues, TName extends FieldPath<TFieldValues>> {
+ control: Control<TFieldValues>;
+ name: TName;
+ label?: React.ReactNode;
+ description?: React.ReactNode;
+ orientation?: "vertical" | "horizontal" | "responsive";
+ className?: string;
+ children: (control: FormFieldControlProps<TFieldValues, TName>) => React.ReactNode;
+}
+
+export const FormField = <TFieldValues extends FieldValues, TName extends FieldPath<TFieldValues>>({
+ control,
+ name,
+ label,
+ description,
+ orientation,
+ className,
+ children,
+}: FormFieldProps<TFieldValues, TName>) => {
+ const reactId = React.useId();
+ const controlId = `${reactId}-control`;
+ const descriptionId = `${reactId}-description`;
+ const errorId = `${reactId}-error`;
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field, fieldState }) => {
+ const invalid = fieldState.error !== undefined;
+ const describedBy =
+ [description !== undefined ? descriptionId : undefined, invalid ? errorId : undefined]
+ .filter((id): id is string => id !== undefined)
+ .join(" ") || undefined;
+ const controlProps: FormFieldControlProps<TFieldValues, TName> = {
+ ...field,
+ id: controlId,
+ "aria-invalid": invalid || undefined,
+ "aria-describedby": describedBy,
+ };
+
+ return (
+ <Field orientation={orientation} data-invalid={invalid || undefined} className={className}>
+ {label !== undefined && <FieldLabel htmlFor={controlId}>{label}</FieldLabel>}
+ {children(controlProps)}
+ {description !== undefined && <FieldDescription id={descriptionId}>{description}</FieldDescription>}
+ <FieldError id={errorId} errors={[fieldState.error]} />
+ </Field>
+ );
+ }}
+ />
+ );
+};
diff --git a/ui/litellm-dashboard/src/components/shared/form/field.test.tsx b/ui/litellm-dashboard/src/components/shared/form/field.test.tsx
new file mode 100644
index 00000000000..54b589ce2f4
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/form/field.test.tsx
@@ -0,0 +1,125 @@
+import { render, screen } from "@testing-library/react";
+import * as React from "react";
+import { describe, expect, it } from "vitest";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldTitle,
+} from "./field";
+
+describe("FieldError", () => {
+ it("renders nothing when there are no errors and no children", () => {
+ const { container } = render(<FieldError errors={[]} />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when every error entry is undefined", () => {
+ const { container } = render(<FieldError errors={[undefined, undefined]} />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders a single message as plain text, not a list", () => {
+ render(<FieldError errors={[{ message: "Required" }]} />);
+
+ expect(screen.getByRole("alert")).toHaveTextContent("Required");
+ expect(screen.queryByRole("listitem")).not.toBeInTheDocument();
+ });
+
+ it("collapses duplicate messages to a single entry", () => {
+ render(<FieldError errors={[{ message: "Required" }, { message: "Required" }]} />);
+
+ expect(screen.getByRole("alert")).toHaveTextContent("Required");
+ expect(screen.queryByRole("listitem")).not.toBeInTheDocument();
+ });
+
+ it("renders distinct messages as a list", () => {
+ render(<FieldError errors={[{ message: "Too short" }, { message: "Must be lowercase" }]} />);
+
+ const items = screen.getAllByRole("listitem");
+ expect(items.map((item) => item.textContent)).toEqual(["Too short", "Must be lowercase"]);
+ });
+
+ it("prefers explicit children over the errors prop", () => {
+ render(<FieldError errors={[{ message: "from errors" }]}>from children</FieldError>);
+
+ expect(screen.getByRole("alert")).toHaveTextContent("from children");
+ expect(screen.getByRole("alert")).not.toHaveTextContent("from errors");
+ });
+
+ it("exposes the message to assistive tech via role=alert", () => {
+ render(<FieldError errors={[{ message: "Required" }]} />);
+
+ expect(screen.getByRole("alert")).toBeInTheDocument();
+ });
+});
+
+describe("Field", () => {
+ it("marks itself invalid so descendants can style off it", () => {
+ render(
+ <Field data-invalid={true}>
+ <span>child</span>
+ </Field>,
+ );
+
+ expect(screen.getByRole("group")).toHaveAttribute("data-invalid", "true");
+ });
+
+ it("defaults to vertical orientation", () => {
+ render(<Field />);
+
+ expect(screen.getByRole("group")).toHaveAttribute("data-orientation", "vertical");
+ });
+
+ it("honours an explicit orientation", () => {
+ render(<Field orientation="horizontal" />);
+
+ expect(screen.getByRole("group")).toHaveAttribute("data-orientation", "horizontal");
+ });
+});
+
+describe("field primitives forward refs to their DOM node", () => {
+ it.each([
+ ["Field", Field, HTMLDivElement],
+ ["FieldContent", FieldContent, HTMLDivElement],
+ ["FieldDescription", FieldDescription, HTMLParagraphElement],
+ ["FieldGroup", FieldGroup, HTMLDivElement],
+ ["FieldLabel", FieldLabel, HTMLLabelElement],
+ ["FieldSeparator", FieldSeparator, HTMLDivElement],
+ ["FieldTitle", FieldTitle, HTMLDivElement],
+ ])("%s", (_name, Component, expected) => {
+ const ref = React.createRef<HTMLElement>();
+ render(React.createElement(Component as React.ElementType, { ref }));
+
+ expect(ref.current).toBeInstanceOf(expected);
+ });
+
+ it("FieldSet and FieldLegend", () => {
+ const fieldSet = React.createRef<HTMLFieldSetElement>();
+ const legend = React.createRef<HTMLLegendElement>();
+ render(
+ <FieldSet ref={fieldSet}>
+ <FieldLegend ref={legend}>Legend</FieldLegend>
+ </FieldSet>,
+ );
+
+ expect(fieldSet.current).toBeInstanceOf(HTMLFieldSetElement);
+ expect(legend.current).toBeInstanceOf(HTMLLegendElement);
+ });
+
+ it("FieldError", () => {
+ const ref = React.createRef<HTMLDivElement>();
+ render(<FieldError ref={ref} errors={[{ message: "Required" }]} />);
+
+ expect(ref.current).toBeInstanceOf(HTMLDivElement);
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/shared/form/field.tsx b/ui/litellm-dashboard/src/components/shared/form/field.tsx
new file mode 100644
index 00000000000..36ce691827c
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/form/field.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import * as React from "react";
+import { type VariantProps } from "cva";
+
+import { Label } from "@/components/ui/label";
+import { Separator } from "@/components/ui/separator";
+import { cn, cva } from "@/lib/cva.config";
+
+const FieldSet = React.forwardRef<HTMLFieldSetElement, React.ComponentPropsWithoutRef<"fieldset">>(
+ ({ className, ...props }, ref) => (
+ <fieldset
+ ref={ref}
+ data-slot="field-set"
+ className={cn(
+ "flex flex-col gap-6 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+FieldSet.displayName = "FieldSet";
+
+const FieldLegend = React.forwardRef<
+ HTMLLegendElement,
+ React.ComponentPropsWithoutRef<"legend"> & { variant?: "legend" | "label" }
+>(({ className, variant = "legend", ...props }, ref) => (
+ <legend
+ ref={ref}
+ data-slot="field-legend"
+ data-variant={variant}
+ className={cn("mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base", className)}
+ {...props}
+ />
+));
+FieldLegend.displayName = "FieldLegend";
+
+const FieldGroup = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-slot="field-group"
+ className={cn(
+ "group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+FieldGroup.displayName = "FieldGroup";
+
+const fieldVariants = cva({
+ base: "group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
+ variants: {
+ orientation: {
+ vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
+ horizontal:
+ "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ responsive:
+ "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ },
+ },
+ defaultVariants: {
+ orientation: "vertical",
+ },
+});
+
+const Field = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentPropsWithoutRef<"div"> & VariantProps<typeof fieldVariants>
+>(({ className, orientation = "vertical", ...props }, ref) => (
+ <div
+ ref={ref}
+ role="group"
+ data-slot="field"
+ data-orientation={orientation}
+ className={cn(fieldVariants({ orientation }), className)}
+ {...props}
+ />
+));
+Field.displayName = "Field";
+
+const FieldContent = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-slot="field-content"
+ className={cn("group/field-content flex flex-1 flex-col gap-1 leading-snug", className)}
+ {...props}
+ />
+ ),
+);
+FieldContent.displayName = "FieldContent";
+
+const FieldLabel = React.forwardRef<HTMLLabelElement, React.ComponentPropsWithoutRef<typeof Label>>(
+ ({ className, ...props }, ref) => (
+ <Label
+ ref={ref}
+ data-slot="field-label"
+ className={cn(
+ "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-3 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
+ "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+FieldLabel.displayName = "FieldLabel";
+
+const FieldTitle = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-slot="field-label"
+ className={cn(
+ "flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+FieldTitle.displayName = "FieldTitle";
+
+const FieldDescription = React.forwardRef<HTMLParagraphElement, React.ComponentPropsWithoutRef<"p">>(
+ ({ className, ...props }, ref) => (
+ <p
+ ref={ref}
+ data-slot="field-description"
+ className={cn(
+ "text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
+ "last:mt-0 nth-last-2:-mt-1",
+ "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+FieldDescription.displayName = "FieldDescription";
+
+const FieldSeparator = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<"div">>(
+ ({ children, className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-slot="field-separator"
+ data-content={!!children}
+ className={cn("relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2", className)}
+ {...props}
+ >
+ <Separator className="absolute inset-0 top-1/2" />
+ {children && (
+ <span
+ className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
+ data-slot="field-separator-content"
+ >
+ {children}
+ </span>
+ )}
+ </div>
+ ),
+);
+FieldSeparator.displayName = "FieldSeparator";
+
+const FieldError = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentPropsWithoutRef<"div"> & { errors?: Array<{ message?: string } | undefined> }
+>(({ className, children, errors, ...props }, ref) => {
+ const content = React.useMemo(() => {
+ if (children) {
+ return children;
+ }
+
+ if (!errors?.length) {
+ return null;
+ }
+
+ const uniqueErrors = [...new Map(errors.map((error) => [error?.message, error])).values()];
+
+ if (uniqueErrors.length === 1) {
+ return uniqueErrors[0]?.message;
+ }
+
+ return (
+ <ul className="ml-4 flex list-disc flex-col gap-1">
+ {uniqueErrors.map((error, index) => error?.message && <li key={index}>{error.message}</li>)}
+ </ul>
+ );
+ }, [children, errors]);
+
+ if (!content) {
+ return null;
+ }
+
+ return (
+ <div
+ ref={ref}
+ role="alert"
+ data-slot="field-error"
+ className={cn("text-sm font-normal text-destructive", className)}
+ {...props}
+ >
+ {content}
+ </div>
+ );
+});
+FieldError.displayName = "FieldError";
+
+export {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldTitle,
+};
diff --git a/ui/litellm-dashboard/src/lib/forms/pickDirty.test.ts b/ui/litellm-dashboard/src/lib/forms/pickDirty.test.ts
new file mode 100644
index 00000000000..43b2c69b1c1
--- /dev/null
+++ b/ui/litellm-dashboard/src/lib/forms/pickDirty.test.ts
@@ -0,0 +1,263 @@
+import { act, renderHook } from "@testing-library/react";
+import type { FieldValues, FormState } from "react-hook-form";
+import { useFieldArray, useForm } from "react-hook-form";
+import { describe, expect, it } from "vitest";
+
+import { pickDirty } from "./pickDirty";
+
+const dirty = <T extends FieldValues>(map: Record<string, unknown>) => map as FormState<T>["dirtyFields"];
+
+describe("pickDirty", () => {
+ it("omits untouched keys entirely rather than sending them as undefined", () => {
+ const result = pickDirty({ team_alias: "a", tpm_limit: 5 }, dirty({ team_alias: true }));
+
+ expect(result).toEqual({ team_alias: "a" });
+ expect("tpm_limit" in result).toBe(false);
+ });
+
+ it("returns an empty patch when nothing is dirty", () => {
+ expect(pickDirty({ team_alias: "a", models: ["gpt-4"] }, dirty({}))).toEqual({});
+ });
+
+ describe("clear tokens survive", () => {
+ it.each([
+ ["null scalar", null],
+ ["empty string", ""],
+ ["zero", 0],
+ ["false", false],
+ ])("keeps a dirty key whose value is %s", (_label, value) => {
+ const result = pickDirty({ max_budget: value }, dirty({ max_budget: true }));
+
+ expect("max_budget" in result).toBe(true);
+ expect(result.max_budget).toBe(value);
+ });
+
+ it("keeps a dirty empty array, which is how lists are cleared", () => {
+ expect(pickDirty({ models: [] }, dirty({ models: true }))).toEqual({ models: [] });
+ });
+
+ it("keeps a dirty empty object, which is how model_aliases is cleared", () => {
+ expect(pickDirty({ model_aliases: {} }, dirty({ model_aliases: true }))).toEqual({ model_aliases: {} });
+ });
+ });
+
+ describe("dirtiness is read at the top level", () => {
+ it("sends the whole array when any element is dirty", () => {
+ const values = { models: ["gpt-4", "gpt-5", "opus"] };
+
+ expect(pickDirty(values, dirty({ models: [false, true, false] }))).toEqual(values);
+ });
+
+ it("omits the array when no element is dirty", () => {
+ const result = pickDirty({ models: ["gpt-4"] }, dirty({ models: [false, false] }));
+
+ expect("models" in result).toBe(false);
+ });
+
+ it("sends the whole object when one nested leaf is dirty", () => {
+ const values = { object_permission: { vector_stores: ["vs-1"], agents: ["a-1"] } };
+
+ expect(pickDirty(values, dirty({ object_permission: { vector_stores: true, agents: false } }))).toEqual(values);
+ });
+
+ it("tolerates the null holes RHF leaves in sparse per-leaf dirty arrays", () => {
+ const values = {
+ modelLimits: [
+ { model: "gpt-4", tpm: 1 },
+ { model: "opus", tpm: 2 },
+ ],
+ };
+
+ expect(pickDirty(values, dirty({ modelLimits: [null, { tpm: true }] }))).toEqual(values);
+ });
+
+ it("omits an object whose every nested leaf is clean", () => {
+ const result = pickDirty(
+ { object_permission: { vector_stores: ["vs-1"] } },
+ dirty({ object_permission: { vector_stores: false } }),
+ );
+
+ expect("object_permission" in result).toBe(false);
+ });
+ });
+
+ it("ignores dirty keys that are absent from the submitted values", () => {
+ const result = pickDirty({ team_alias: "a" }, dirty({ team_alias: true, ghost_field: true }));
+
+ expect(result).toEqual({ team_alias: "a" });
+ expect("ghost_field" in result).toBe(false);
+ });
+
+ it("does not mutate its inputs", () => {
+ const values = { models: ["gpt-4"], tpm_limit: 5 };
+ const dirtyFields = dirty<typeof values>({ models: [true] });
+
+ pickDirty(values, dirtyFields);
+
+ expect(values).toEqual({ models: ["gpt-4"], tpm_limit: 5 });
+ expect(dirtyFields).toEqual({ models: [true] });
+ });
+
+ it("keeps value identity so nested references are not cloned", () => {
+ const models = ["gpt-4"];
+
+ expect(pickDirty({ models }, dirty({ models: true })).models).toBe(models);
+ });
+});
+
+describe("pickDirty against a real react-hook-form instance", () => {
+ const defaultValues = {
+ team_alias: "team-a",
+ max_budget: 10 as number | null,
+ models: ["gpt-4", "opus"] as string[],
+ object_permission: { vector_stores: ["vs-1"] as string[] },
+ modelLimits: [{ model: "gpt-4", tpm: 1 }],
+ };
+
+ const renderForm = () =>
+ renderHook(() => {
+ const form = useForm({ defaultValues });
+ const fieldArray = useFieldArray({ control: form.control, name: "modelLimits" });
+ void form.formState.dirtyFields;
+ return { form, fieldArray };
+ });
+
+ const patchOf = (result: { current: { form: ReturnType<typeof useForm<typeof defaultValues>> } }) =>
+ pickDirty(result.current.form.getValues(), result.current.form.formState.dirtyFields);
+
+ it("sends nothing when the user opens the form and saves without editing", () => {
+ const { result } = renderForm();
+
+ expect(patchOf(result)).toEqual({});
+ });
+
+ it("sends only the edited scalar", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.form.setValue("team_alias", "team-b", { shouldDirty: true });
+ });
+
+ expect(patchOf(result)).toEqual({ team_alias: "team-b" });
+ });
+
+ it("sends null to clear a scalar, and nothing else", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.form.setValue("max_budget", null, { shouldDirty: true });
+ });
+
+ expect(patchOf(result)).toEqual({ max_budget: null });
+ });
+
+ it("sends an empty array to clear a list emptied through useFieldArray", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.fieldArray.remove(0);
+ });
+
+ expect(patchOf(result)).toEqual({ modelLimits: [] });
+ });
+
+ it("sends the whole nested object when one leaf under it changes", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.form.setValue("object_permission.vector_stores", [], { shouldDirty: true });
+ });
+
+ expect(patchOf(result)).toEqual({ object_permission: { vector_stores: [] } });
+ });
+
+ it("drops a field the user edited and then reverted to its original value", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.form.setValue("team_alias", "team-b", { shouldDirty: true });
+ });
+ act(() => {
+ result.current.form.setValue("team_alias", "team-a", { shouldDirty: true });
+ });
+
+ expect(patchOf(result)).toEqual({});
+ });
+
+ it("resets to a clean baseline after a successful save", () => {
+ const { result } = renderForm();
+
+ act(() => {
+ result.current.form.setValue("team_alias", "team-b", { shouldDirty: true });
+ });
+ act(() => {
+ result.current.form.reset({ ...defaultValues, team_alias: "team-b" });
+ });
+
+ expect(patchOf(result)).toEqual({});
+ });
+});
+
+describe("pickDirty picks up a pure reorder", () => {
+ // RHF compares each element to its default positionally by value, not by
+ // identity, so any reorder that changes the value at some index marks that
+ // index dirty and the whole array is sent. A reorder that leaves every index
+ // equal to its default is a value-level no-op whose payload is unchanged, so
+ // omitting it is correct.
+ const renderRows = (rows: Array<{ v: string }>) =>
+ renderHook(() => {
+ const form = useForm({ defaultValues: { rows } });
+ const fieldArray = useFieldArray({ control: form.control, name: "rows" });
+ void form.formState.dirtyFields;
+ return { form, fieldArray };
+ });
+
+ const patchOf = (result: { current: { form: ReturnType<typeof useForm<{ rows: Array<{ v: string }> }>> } }) =>
+ pickDirty(result.current.form.getValues(), result.current.form.formState.dirtyFields);
+
+ it("sends the whole array after useFieldArray.move()", () => {
+ const { result } = renderRows([{ v: "a" }, { v: "b" }, { v: "c" }]);
+
+ act(() => {
+ result.current.fieldArray.move(0, 2);
+ });
+
+ expect(patchOf(result)).toEqual({ rows: [{ v: "b" }, { v: "c" }, { v: "a" }] });
+ });
+
+ it("sends the whole array after useFieldArray.swap()", () => {
+ const { result } = renderRows([{ v: "a" }, { v: "b" }, { v: "c" }]);
+
+ act(() => {
+ result.current.fieldArray.swap(0, 2);
+ });
+
+ expect(patchOf(result)).toEqual({ rows: [{ v: "c" }, { v: "b" }, { v: "a" }] });
+ });
+
+ it("sends a reordered scalar array set through setValue", () => {
+ const { result } = renderHook(() => {
+ const form = useForm({ defaultValues: { models: ["a", "b", "c"] } });
+ void form.formState.dirtyFields;
+ return form;
+ });
+
+ act(() => {
+ result.current.setValue("models", ["c", "b", "a"], { shouldDirty: true });
+ });
+
+ expect(pickDirty(result.current.getValues(), result.current.formState.dirtyFields)).toEqual({
+ models: ["c", "b", "a"],
+ });
+ });
+
+ it("omits a swap of two equal elements, which is a value-level no-op", () => {
+ const { result } = renderRows([{ v: "a" }, { v: "b" }, { v: "a" }]);
+
+ act(() => {
+ result.current.fieldArray.swap(0, 2);
+ });
+
+ expect(patchOf(result)).toEqual({});
+ });
+});
diff --git a/ui/litellm-dashboard/src/lib/forms/pickDirty.ts b/ui/litellm-dashboard/src/lib/forms/pickDirty.ts
new file mode 100644
index 00000000000..1f8d705db12
--- /dev/null
+++ b/ui/litellm-dashboard/src/lib/forms/pickDirty.ts
@@ -0,0 +1,24 @@
+import type { FieldValues, FormState } from "react-hook-form";
+
+const isDirtyNode = (node: unknown): boolean => {
+ if (typeof node === "boolean") {
+ return node;
+ }
+ if (Array.isArray(node)) {
+ return node.some(isDirtyNode);
+ }
+ if (node !== null && typeof node === "object") {
+ return Object.values(node as Record<string, unknown>).some(isDirtyNode);
+ }
+ return false;
+};
+
+export const pickDirty = <TValues extends FieldValues>(
+ values: TValues,
+ dirtyFields: FormState<TValues>["dirtyFields"],
+): Partial<TValues> =>
+ Object.fromEntries(
+ Object.keys(values)
+ .filter((key) => isDirtyNode((dirtyFields as Record<string, unknown>)[key]))
+ .map((key) => [key, values[key]]),
+ ) as Partial<TValues>;