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]

refactor(ui): migrate pass-through, project and access group forms to react-hook-form and shadcn (#37354)

yuneng-jiang0cc2f29c78aa
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupBaseForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupBaseForm.tsx
index 72b89e34301..c9ba082f7a6 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupBaseForm.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupBaseForm.tsx
@@ -1,147 +1,179 @@
+"use client";
+
+import { BotIcon, InfoIcon, LayersIcon, ServerIcon } from "lucide-react";
+import type { UseFormReturn } from "react-hook-form";
+import { z } from "zod/v4";
+
import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents";
import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";
import { ModelSelect } from "@/components/ModelSelect/ModelSelect";
-import type { FormInstance } from "antd";
-import { Form, Input, Select, Space, Tabs } from "antd";
-import { BotIcon, InfoIcon, LayersIcon, ServerIcon } from "lucide-react";
+import { FieldGroup } from "@/components/shared/form/field";
+import { FormField } from "@/components/shared/form/FormField";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Textarea } from "@/components/ui/textarea";
+
+export const accessGroupFormSchema = z.object({
+ name: z.string().min(1, "Please enter the access group name"),
+ description: z.string(),
+ modelIds: z.array(z.string()),
+ mcpServerIds: z.array(z.string()),
+ agentIds: z.array(z.string()),
+});
+
+export type AccessGroupFormValues = z.output<typeof accessGroupFormSchema>;
-const { TextArea } = Input;
+export const GENERAL_TAB = "general";
+export const MODELS_TAB = "models";
+export const MCP_SERVERS_TAB = "mcp-servers";
+export const AGENTS_TAB = "agents";
-export interface AccessGroupFormValues {
- name: string;
- description: string;
- modelIds: string[];
- mcpServerIds: string[];
- agentIds: string[];
+interface MultiSelectOption {
+ value: string;
+ label: string;
}
+interface MultiSelectProps {
+ id: string;
+ value: string[];
+ onChange: (value: string[]) => void;
+ options: MultiSelectOption[];
+ placeholder: string;
+ "aria-invalid": true | undefined;
+ "aria-describedby": string | undefined;
+}
+
+const MultiSelect = ({
+ id,
+ value,
+ onChange,
+ options,
+ placeholder,
+ "aria-invalid": ariaInvalid,
+ "aria-describedby": ariaDescribedBy,
+}: MultiSelectProps) => (
+ <Select multiple items={options} value={value} onValueChange={onChange}>
+ <SelectTrigger id={id} aria-invalid={ariaInvalid} aria-describedby={ariaDescribedBy} className="w-full">
+ <SelectValue placeholder={placeholder}>
+ {(selected: string[]) =>
+ selected.length === 0
+ ? placeholder
+ : options
+ .filter((option) => selected.includes(option.value))
+ .map((option) => option.label)
+ .join(", ")
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value} title={option.label}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+);
+
interface AccessGroupBaseFormProps {
- form: FormInstance<AccessGroupFormValues>;
+ form: UseFormReturn<AccessGroupFormValues>;
isNameDisabled?: boolean;
+ activeTab: string;
+ onTabChange: (tab: string) => void;
}
-export function AccessGroupBaseForm({ form, isNameDisabled = false }: AccessGroupBaseFormProps) {
+export function AccessGroupBaseForm({
+ form,
+ isNameDisabled = false,
+ activeTab,
+ onTabChange,
+}: AccessGroupBaseFormProps) {
const { data: agentsData } = useAgents();
const { data: mcpServersData } = useMCPServers();
- const agents = agentsData?.agents ?? [];
- const mcpServers = mcpServersData ?? [];
- const items = [
- {
- key: "1",
- label: (
- <Space align="center" size={4}>
+ const mcpServerOptions = (mcpServersData ?? []).map((server) => ({
+ value: server.server_id,
+ label: server.server_name ?? server.server_id,
+ }));
+ const agentOptions = (agentsData?.agents ?? []).map((agent) => ({
+ value: agent.agent_id,
+ label: agent.agent_name,
+ }));
+
+ return (
+ <Tabs value={activeTab} onValueChange={onTabChange}>
+ <TabsList className="w-full">
+ <TabsTrigger value={GENERAL_TAB}>
<InfoIcon size={16} />
General Info
- </Space>
- ),
- children: (
- <div style={{ paddingTop: 16 }}>
- <Form.Item
- name="name"
- label="Group Name"
- rules={[
- {
- required: true,
- message: "Please enter the access group name",
- },
- ]}
- >
- <Input placeholder="e.g. Engineering Team" disabled={isNameDisabled} />
- </Form.Item>
- <Form.Item name="description" label="Description">
- <TextArea rows={4} placeholder="Describe the purpose of this access group..." />
- </Form.Item>
- </div>
- ),
- },
- {
- key: "2",
- label: (
- <Space align="center" size={4}>
+ </TabsTrigger>
+ <TabsTrigger value={MODELS_TAB}>
<LayersIcon size={16} />
Models
- </Space>
- ),
- children: (
- <div style={{ paddingTop: 16 }}>
- <Form.Item name="modelIds" label="Allowed Models">
- <ModelSelect
- context="global"
- value={form.getFieldValue("modelIds") ?? []}
- onChange={(values) => form.setFieldsValue({ modelIds: values })}
- style={{ width: "100%" }}
- />
- </Form.Item>
- </div>
- ),
- },
- {
- key: "3",
- label: (
- <Space align="center" size={4}>
+ </TabsTrigger>
+ <TabsTrigger value={MCP_SERVERS_TAB}>
<ServerIcon size={16} />
MCP Servers
- </Space>
- ),
- children: (
- <div style={{ paddingTop: 16 }}>
- <Form.Item name="mcpServerIds" label="Allowed MCP Servers">
- <Select
- mode="multiple"
- placeholder="Select MCP servers"
- style={{ width: "100%" }}
- optionFilterProp="label"
- allowClear
- options={mcpServers.map((server) => ({
- label: server.server_name ?? server.server_id,
- value: server.server_id,
- }))}
- />
- </Form.Item>
- </div>
- ),
- },
- {
- key: "4",
- label: (
- <Space align="center" size={4}>
+ </TabsTrigger>
+ <TabsTrigger value={AGENTS_TAB}>
<BotIcon size={16} />
Agents
- </Space>
- ),
- children: (
- <div style={{ paddingTop: 16 }}>
- <Form.Item name="agentIds" label="Allowed Agents">
- <Select
- mode="multiple"
- placeholder="Select agents"
- style={{ width: "100%" }}
- optionFilterProp="label"
- allowClear
- options={agents.map((agent) => ({
- label: agent.agent_name,
- value: agent.agent_id,
- }))}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value={GENERAL_TAB} className="pt-4">
+ <FieldGroup>
+ <FormField control={form.control} name="name" label="Group Name">
+ {({ ref, ...field }) => (
+ <Input {...field} ref={ref} placeholder="e.g. Engineering Team" disabled={isNameDisabled} />
+ )}
+ </FormField>
+ <FormField control={form.control} name="description" label="Description">
+ {({ ref, ...field }) => (
+ <Textarea {...field} ref={ref} rows={4} placeholder="Describe the purpose of this access group..." />
+ )}
+ </FormField>
+ </FieldGroup>
+ </TabsContent>
+
+ <TabsContent value={MODELS_TAB} className="pt-4">
+ <FormField control={form.control} name="modelIds" label="Allowed Models">
+ {(field) => <ModelSelect context="global" value={field.value} onChange={field.onChange} />}
+ </FormField>
+ </TabsContent>
+
+ <TabsContent value={MCP_SERVERS_TAB} className="pt-4">
+ <FormField control={form.control} name="mcpServerIds" label="Allowed MCP Servers">
+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (
+ <MultiSelect
+ id={id}
+ value={value}
+ onChange={onChange}
+ options={mcpServerOptions}
+ placeholder="Select MCP servers"
+ aria-invalid={ariaInvalid}
+ aria-describedby={ariaDescribedBy}
/>
- </Form.Item>
- </div>
- ),
- },
- ];
+ )}
+ </FormField>
+ </TabsContent>
- return (
- <Form
- form={form}
- layout="vertical"
- name="access_group_form"
- initialValues={{
- modelIds: [],
- mcpServerIds: [],
- agentIds: [],
- }}
- >
- <Tabs defaultActiveKey="1" items={items} />
- </Form>
+ <TabsContent value={AGENTS_TAB} className="pt-4">
+ <FormField control={form.control} name="agentIds" label="Allowed Agents">
+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (
+ <MultiSelect
+ id={id}
+ value={value}
+ onChange={onChange}
+ options={agentOptions}
+ placeholder="Select agents"
+ aria-invalid={ariaInvalid}
+ aria-describedby={ariaDescribedBy}
+ />
+ )}
+ </FormField>
+ </TabsContent>
+ </Tabs>
);
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.integration.test.tsx
new file mode 100644
index 00000000000..2eef71f9156
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.integration.test.tsx
@@ -0,0 +1,175 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
+import { renderWithProviders, screen, waitFor } from "../../../../../../tests/test-utils";
+import { AccessGroupEditModal } from "./AccessGroupEditModal";
+import { AccessGroupResponse } from "@/app/(dashboard)/hooks/accessGroups/useAccessGroups";
+
+const mutate = vi.fn();
+
+vi.mock("@/app/(dashboard)/hooks/accessGroups/useEditAccessGroup", () => ({
+ useEditAccessGroup: () => ({ mutate, isPending: false }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/agents/useAgents", () => ({
+ useAgents: () => ({ data: { agents: [{ agent_id: "agent-1", agent_name: "Support Bot" }] } }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({
+ useMCPServers: () => ({ data: [{ server_id: "srv-1", server_name: "Files" }] }),
+}));
+
+vi.mock("@/components/ModelSelect/ModelSelect", () => ({
+ ModelSelect: ({ value, onChange }: { value: string[]; onChange: (next: string[]) => void }) => (
+ <button type="button" aria-label="model-select" onClick={() => onChange([...(value ?? []), "gpt-4"])}>
+ {(value ?? []).join(",")}
+ </button>
+ ),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
+}));
+
+const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
+type User = ReturnType<typeof setup>;
+
+const accessGroup: AccessGroupResponse = {
+ access_group_id: "ag-1",
+ access_group_name: "Engineering",
+ description: "Engineers",
+ access_model_names: ["gpt-4"],
+ access_mcp_server_ids: ["srv-1"],
+ access_agent_ids: ["agent-1"],
+ assigned_team_ids: [],
+ assigned_key_ids: [],
+ created_at: "2024-01-01T00:00:00Z",
+ created_by: "user-1",
+ updated_at: "2024-01-02T00:00:00Z",
+ updated_by: "user-1",
+};
+
+const renderModal = (data: AccessGroupResponse = accessGroup) =>
+ renderWithProviders(<AccessGroupEditModal visible accessGroup={data} onCancel={vi.fn()} />);
+
+const save = async (user: User) => user.click(screen.getByRole("button", { name: "Save Changes" }));
+
+const variables = () => mutate.mock.calls.at(-1)?.[0] as { accessGroupId: string; params: Record<string, unknown> };
+
+describe("AccessGroupEditModal submit payload", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("sends exactly the antd payload for an untouched save", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("Engineering");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(variables().accessGroupId).toBe("ag-1");
+ expect(variables().params).toStrictEqual({
+ access_group_name: "Engineering",
+ description: "Engineers",
+ access_model_names: undefined,
+ access_mcp_server_ids: undefined,
+ access_agent_ids: undefined,
+ });
+ });
+
+ it("sends a tab's field only once that tab has been visited", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("Engineering");
+
+ await user.click(screen.getByRole("tab", { name: /MCP Servers/ }));
+ await user.click(screen.getByRole("tab", { name: /Agents/ }));
+ await user.click(screen.getByRole("tab", { name: /General Info/ }));
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params).toStrictEqual({
+ access_group_name: "Engineering",
+ description: "Engineers",
+ access_model_names: undefined,
+ access_mcp_server_ids: ["srv-1"],
+ access_agent_ids: ["agent-1"],
+ });
+ });
+
+ it("coerces a null description to an empty string", async () => {
+ const user = setup();
+ renderModal({ ...accessGroup, description: null });
+ await screen.findByDisplayValue("Engineering");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.description).toBe("");
+ });
+
+ it("does not trim surrounding whitespace from the group name", async () => {
+ const user = setup();
+ renderModal();
+ const nameInput = await screen.findByDisplayValue("Engineering");
+
+ await user.clear(nameInput);
+ await user.type(nameInput, " Padded ");
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.access_group_name).toBe(" Padded ");
+ });
+
+ it("never sends server-only fields from the loaded record", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("Engineering");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params).not.toHaveProperty("access_group_id");
+ expect(variables().params).not.toHaveProperty("created_at");
+ expect(variables().params).not.toHaveProperty("assigned_team_ids");
+ expect(variables().params).not.toHaveProperty("assigned_key_ids");
+ });
+
+ it("does not submit when the group name is cleared", async () => {
+ const user = setup();
+ renderModal();
+ const nameInput = await screen.findByDisplayValue("Engineering");
+
+ await user.clear(nameInput);
+ await save(user);
+
+ expect(await screen.findByText("Please enter the access group name")).toBeInTheDocument();
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it("does not save when Enter is pressed in the name field", async () => {
+ const user = setup();
+ renderModal();
+ const nameInput = await screen.findByDisplayValue("Engineering");
+
+ await user.type(nameInput, "{Enter}");
+
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it("sends models chosen on the Models tab", async () => {
+ const user = setup();
+ renderModal({ ...accessGroup, access_model_names: [] });
+ await screen.findByDisplayValue("Engineering");
+
+ await user.click(screen.getByRole("tab", { name: /Models/ }));
+ await user.click(await screen.findByLabelText("model-select"));
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.access_model_names).toStrictEqual(["gpt-4"]);
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.tsx
index c65f8bf951f..6514c7072bb 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.tsx
@@ -1,10 +1,24 @@
-import React, { useEffect } from "react";
-import { Modal, Form } from "antd";
+"use client";
+
+import React, { useState } from "react";
+import { Modal } from "antd";
+
import { toast } from "@/lib/toast";
-import { AccessGroupBaseForm, AccessGroupFormValues } from "./AccessGroupBaseForm";
+import { useZodForm } from "@/lib/forms/useZodForm";
+import { Button } from "@/components/ui/button";
import { useEditAccessGroup, AccessGroupUpdateParams } from "@/app/(dashboard)/hooks/accessGroups/useEditAccessGroup";
import { AccessGroupResponse } from "@/app/(dashboard)/hooks/accessGroups/useAccessGroups";
+import {
+ AccessGroupBaseForm,
+ accessGroupFormSchema,
+ AGENTS_TAB,
+ GENERAL_TAB,
+ MCP_SERVERS_TAB,
+ MODELS_TAB,
+ type AccessGroupFormValues,
+} from "./AccessGroupBaseForm";
+
interface AccessGroupEditModalProps {
visible: boolean;
accessGroup: AccessGroupResponse;
@@ -12,62 +26,74 @@ interface AccessGroupEditModalProps {
onSuccess?: () => void;
}
-export function AccessGroupEditModal({ visible, accessGroup, onCancel, onSuccess }: AccessGroupEditModalProps) {
- const [form] = Form.useForm<AccessGroupFormValues>();
+const toFormValues = (accessGroup: AccessGroupResponse): AccessGroupFormValues => ({
+ name: accessGroup.access_group_name,
+ description: accessGroup.description ?? "",
+ modelIds: accessGroup.access_model_names ?? [],
+ mcpServerIds: accessGroup.access_mcp_server_ids ?? [],
+ agentIds: accessGroup.access_agent_ids ?? [],
+});
+
+function AccessGroupEditForm({ accessGroup, onCancel, onSuccess }: Omit<AccessGroupEditModalProps, "visible">) {
+ const form = useZodForm(accessGroupFormSchema, { defaultValues: toFormValues(accessGroup) });
const editMutation = useEditAccessGroup();
+ const [activeTab, setActiveTab] = useState(GENERAL_TAB);
+ const [visitedTabs, setVisitedTabs] = useState<ReadonlySet<string>>(new Set([GENERAL_TAB]));
- // Populate the form with initial values whenever the modal opens or the data changes
- useEffect(() => {
- if (visible && accessGroup) {
- form.setFieldsValue({
- name: accessGroup.access_group_name,
- description: accessGroup.description ?? "",
- modelIds: accessGroup.access_model_names ?? [],
- mcpServerIds: accessGroup.access_mcp_server_ids ?? [],
- agentIds: accessGroup.access_agent_ids ?? [],
- });
- }
- }, [visible, accessGroup, form]);
+ const handleTabChange = (tab: string) => {
+ setActiveTab(tab);
+ setVisitedTabs((previous) => new Set([...previous, tab]));
+ };
- const handleOk = () => {
- form
- .validateFields()
- .then((values) => {
- const params: AccessGroupUpdateParams = {
- access_group_name: values.name,
- description: values.description,
- access_model_names: values.modelIds,
- access_mcp_server_ids: values.mcpServerIds,
- access_agent_ids: values.agentIds,
- };
+ const handleOk = form.handleSubmit(
+ (values) => {
+ const params: AccessGroupUpdateParams = {
+ access_group_name: values.name,
+ description: values.description,
+ access_model_names: visitedTabs.has(MODELS_TAB) ? values.modelIds : undefined,
+ access_mcp_server_ids: visitedTabs.has(MCP_SERVERS_TAB) ? values.mcpServerIds : undefined,
+ access_agent_ids: visitedTabs.has(AGENTS_TAB) ? values.agentIds : undefined,
+ };
- editMutation.mutate(
- { accessGroupId: accessGroup.access_group_id, params },
- {
- onSuccess: () => {
- toast.success("Access group updated successfully");
- onSuccess?.();
- onCancel();
- },
+ editMutation.mutate(
+ { accessGroupId: accessGroup.access_group_id, params },
+ {
+ onSuccess: () => {
+ toast.success("Access group updated successfully");
+ onSuccess?.();
+ onCancel();
},
- );
- })
- .catch((info) => {});
- };
+ },
+ );
+ },
+ () => setActiveTab(GENERAL_TAB),
+ );
+
+ return (
+ <form onSubmit={(event) => event.preventDefault()}>
+ <AccessGroupBaseForm form={form} activeTab={activeTab} onTabChange={handleTabChange} />
+ <div className="mt-6 flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={onCancel} disabled={editMutation.isPending}>
+ Cancel
+ </Button>
+ <Button type="button" onClick={() => void handleOk()} disabled={editMutation.isPending}>
+ Save Changes
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+export function AccessGroupEditModal({ visible, accessGroup, onCancel, onSuccess }: AccessGroupEditModalProps) {
return (
- <Modal
- title="Edit Access Group"
- open={visible}
- onOk={handleOk}
- onCancel={onCancel}
- width={700}
- okText="Save Changes"
- cancelText="Cancel"
- confirmLoading={editMutation.isPending}
- destroyOnHidden
- >
- <AccessGroupBaseForm form={form} />
+ <Modal title="Edit Access Group" open={visible} onCancel={onCancel} width={700} footer={null} destroyOnHidden>
+ <AccessGroupEditForm
+ key={accessGroup.access_group_id}
+ accessGroup={accessGroup}
+ onCancel={onCancel}
+ onSuccess={onSuccess}
+ />
</Modal>
);
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.integration.test.tsx
new file mode 100644
index 00000000000..2c57db89436
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.integration.test.tsx
@@ -0,0 +1,255 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
+import { renderWithProviders, screen, waitFor } from "../../../../../../tests/test-utils";
+import { CreateProjectModal } from "./CreateProjectModal";
+
+const mutate = vi.fn();
+
+vi.mock("@/app/(dashboard)/hooks/projects/useCreateProject", () => ({
+ useCreateProject: () => ({ mutate, isPending: false }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
+ default: () => ({ accessToken: "test-token", userId: "u-1", userRole: "Admin" }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({
+ useTeams: () => ({
+ data: [
+ { team_id: "team-1", team_alias: "Engineering", models: ["gpt-4"] },
+ { team_id: "team-2", team_alias: "Sales", models: [] },
+ ],
+ isLoading: false,
+ }),
+}));
+
+vi.mock("@/components/organisms/create_key_button", () => ({
+ fetchTeamModels: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/components/networking", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/components/networking")>()),
+ getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [{ guardrail_name: "pii-guard" }] }),
+}));
+
+vi.mock("@/components/key_team_helpers/fetch_available_models_team_key", () => ({
+ getModelDisplayName: (model: string) => model,
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
+}));
+
+const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
+type User = ReturnType<typeof setup>;
+
+const renderModal = () => renderWithProviders(<CreateProjectModal isOpen onClose={vi.fn()} />);
+
+const pickTeam = async (user: User) => {
+ await user.click(screen.getByLabelText("Team"));
+ await user.click(await screen.findByText("Engineering"));
+};
+
+const submit = async (user: User) => user.click(screen.getByRole("button", { name: /create project/i }));
+
+const expandAdvanced = async (user: User) => {
+ await user.click(screen.getByText("Advanced Settings"));
+ await screen.findByText("Model-Specific Limits");
+};
+
+const params = () => mutate.mock.calls.at(-1)?.[0] as Record<string, unknown>;
+
+describe("CreateProjectModal submit payload", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("sends exactly the antd payload for a minimal project", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(params()).toStrictEqual({
+ project_alias: "My Project",
+ description: undefined,
+ models: [],
+ max_budget: undefined,
+ blocked: false,
+ team_id: "team-1",
+ });
+ });
+
+ it("does not submit without a project name", async () => {
+ const user = setup();
+ renderModal();
+
+ await pickTeam(user);
+ await submit(user);
+
+ expect(await screen.findByText("Please enter a project name")).toBeInTheDocument();
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it("does not submit without a team", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await submit(user);
+
+ expect(await screen.findByText("Please select a team")).toBeInTheDocument();
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it("sends description and max_budget rounded to two decimals", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await user.type(screen.getByLabelText("Description"), "Handles support");
+ await user.type(screen.getByPlaceholderText("0.00"), "42.567");
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().description).toBe("Handles support");
+ expect(params().max_budget).toBe(42.57);
+ });
+
+ it("sends the selected models", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await user.click(screen.getByLabelText(/Allowed Models/));
+ await user.click(await screen.findByTitle("gpt-4"));
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().models).toStrictEqual(["gpt-4"]);
+ });
+
+ it("collapses models to all-team-models when that option is chosen", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await user.click(screen.getByLabelText(/Allowed Models/));
+ await user.click(await screen.findByTitle("gpt-4"));
+ await user.click(await screen.findByTitle("All Team Models"));
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().models).toStrictEqual(["all-team-models"]);
+ });
+
+ it("sends blocked true when the Block Project switch is on", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+ await user.click(screen.getByRole("switch"));
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().blocked).toBe(true);
+ });
+
+ it("omits guardrails, limits and metadata when the advanced section is untouched", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params()).not.toHaveProperty("guardrails");
+ expect(params()).not.toHaveProperty("model_rpm_limit");
+ expect(params()).not.toHaveProperty("model_tpm_limit");
+ expect(params()).not.toHaveProperty("metadata");
+ });
+
+ it("sends model limits as rpm and tpm maps keyed by model", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+
+ await user.click(screen.getByRole("button", { name: /add model limit/i }));
+ await user.type(screen.getByPlaceholderText("Model name (e.g. gpt-4)"), "gpt-4");
+ await user.type(screen.getByPlaceholderText("TPM Limit"), "100");
+ await user.type(screen.getByPlaceholderText("RPM Limit"), "20");
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().model_tpm_limit).toStrictEqual({ "gpt-4": 100 });
+ expect(params().model_rpm_limit).toStrictEqual({ "gpt-4": 20 });
+ });
+
+ it("sends metadata pairs as an object", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+
+ await user.click(screen.getByRole("button", { name: /add key-value pair/i }));
+ await user.type(screen.getByPlaceholderText("Key"), "owner");
+ await user.type(screen.getByPlaceholderText("Value"), "platform");
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().metadata).toStrictEqual({ owner: "platform" });
+ });
+
+ it("sends guardrails when chosen in the advanced section", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+
+ await user.click(screen.getByLabelText("Guardrails"));
+ await user.click(await screen.findByTitle("pii-guard"));
+ await user.keyboard("{Escape}");
+ await submit(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(params().guardrails).toStrictEqual(["pii-guard"]);
+ });
+
+ it("blocks submit when two model limits name the same model", async () => {
+ const user = setup();
+ renderModal();
+
+ await user.type(screen.getByLabelText("Project Name"), "My Project");
+ await pickTeam(user);
+ await expandAdvanced(user);
+
+ await user.click(screen.getByRole("button", { name: /add model limit/i }));
+ await user.click(screen.getByRole("button", { name: /add model limit/i }));
+ const modelInputs = screen.getAllByPlaceholderText("Model name (e.g. gpt-4)");
+ await user.type(modelInputs[0], "gpt-4");
+ await user.type(modelInputs[1], "gpt-4");
+ await submit(user);
+
+ expect(await screen.findByText("Duplicate model")).toBeInTheDocument();
+ expect(mutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.tsx
index 6c98a2f5b0b..7e2d74c0944 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/CreateProjectModal.tsx
@@ -1,8 +1,16 @@
-import { Modal, Form, Button, Typography } from "antd";
-import { FolderAddOutlined } from "@ant-design/icons";
+"use client";
+
+import { useState } from "react";
+import { Modal } from "antd";
+import { FolderPlus } from "lucide-react";
+
import { toast } from "@/lib/toast";
+import { useZodForm } from "@/lib/forms/useZodForm";
+import { Button } from "@/components/ui/button";
+import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";
import { useCreateProject, ProjectCreateParams } from "@/app/(dashboard)/hooks/projects/useCreateProject";
-import { ProjectBaseForm, ProjectFormValues } from "./ProjectBaseForm";
+import { ProjectBaseForm } from "./ProjectBaseForm";
+import { emptyProjectFormValues, projectFormSchema } from "./projectFormSchema";
import { buildProjectApiParams } from "./projectFormUtils";
interface CreateProjectModalProps {
@@ -10,65 +18,62 @@ interface CreateProjectModalProps {
onClose: () => void;
}
-export function CreateProjectModal({ isOpen, onClose }: CreateProjectModalProps) {
- const [form] = Form.useForm<ProjectFormValues>();
+function CreateProjectForm({ onClose }: { onClose: () => void }) {
+ const form = useZodForm(projectFormSchema, { defaultValues: emptyProjectFormValues });
const createMutation = useCreateProject();
+ const [advancedOpen, setAdvancedOpen] = useState(false);
- const handleSubmit = async () => {
- try {
- const values = await form.validateFields();
- const params: ProjectCreateParams = {
- ...buildProjectApiParams(values),
- team_id: values.team_id,
- };
+ const handleSubmit = form.handleSubmit((values) => {
+ const params: ProjectCreateParams = {
+ ...buildProjectApiParams(values),
+ team_id: values.team_id,
+ };
- createMutation.mutate(params, {
- onSuccess: () => {
- toast.success("Project created successfully");
- form.resetFields();
- onClose();
- },
- onError: (error) => {
- toast.error(error.message || "Failed to create project");
- },
- });
- } catch (error) {
- console.error("Validation failed:", error);
- }
- };
+ createMutation.mutate(params, {
+ onSuccess: () => {
+ toast.success("Project created successfully");
+ form.reset(emptyProjectFormValues);
+ onClose();
+ },
+ onError: (error) => {
+ toast.error(error.message || "Failed to create project");
+ },
+ });
+ });
const handleCancel = () => {
- form.resetFields();
+ form.reset(emptyProjectFormValues);
onClose();
};
+ return (
+ <form onSubmit={(event) => event.preventDefault()}>
+ <ProjectBaseForm form={form} advancedOpen={advancedOpen} onAdvancedOpenChange={setAdvancedOpen} />
+
+ <div className="mt-6 flex justify-end gap-2 border-t border-border pt-4">
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button type="button" onClick={() => void handleSubmit()} disabled={createMutation.isPending}>
+ {createMutation.isPending ? <UiLoadingSpinner /> : <FolderPlus />}
+ Create Project
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+export function CreateProjectModal({ isOpen, onClose }: CreateProjectModalProps) {
return (
<Modal
- title={
- <Typography.Text strong style={{ fontSize: 18 }}>
- Create New Project
- </Typography.Text>
- }
+ title={<span className="text-lg font-semibold text-foreground">Create New Project</span>}
open={isOpen}
- onCancel={handleCancel}
+ onCancel={onClose}
width={720}
destroyOnHidden
- footer={[
- <Button key="cancel" onClick={handleCancel}>
- Cancel
- </Button>,
- <Button
- key="submit"
- type="primary"
- icon={<FolderAddOutlined />}
- loading={createMutation.isPending}
- onClick={handleSubmit}
- >
- Create Project
- </Button>,
- ]}
+ footer={null}
>
- <ProjectBaseForm form={form} />
+ <CreateProjectForm onClose={onClose} />
</Modal>
);
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.integration.test.tsx
new file mode 100644
index 00000000000..7227531c2b3
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.integration.test.tsx
@@ -0,0 +1,194 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
+import { renderWithProviders, screen, waitFor } from "../../../../../../tests/test-utils";
+import { EditProjectModal } from "./EditProjectModal";
+import { ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";
+
+const mutate = vi.fn();
+
+vi.mock("@/app/(dashboard)/hooks/projects/useUpdateProject", () => ({
+ useUpdateProject: () => ({ mutate, isPending: false }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
+ default: () => ({ accessToken: "test-token", userId: "u-1", userRole: "Admin" }),
+}));
+
+vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({
+ useTeams: () => ({
+ data: [{ team_id: "team-1", team_alias: "Engineering", models: ["gpt-4"] }],
+ isLoading: false,
+ }),
+}));
+
+vi.mock("@/components/organisms/create_key_button", () => ({
+ fetchTeamModels: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/components/networking", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/components/networking")>()),
+ getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [{ guardrail_name: "pii-guard" }] }),
+}));
+
+vi.mock("@/components/key_team_helpers/fetch_available_models_team_key", () => ({
+ getModelDisplayName: (model: string) => model,
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
+}));
+
+const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
+type User = ReturnType<typeof setup>;
+
+const project: ProjectResponse = {
+ project_id: "proj-1",
+ project_alias: "My Project",
+ description: "A test project",
+ team_id: "team-1",
+ budget_id: null,
+ metadata: {
+ owner: "platform",
+ guardrails: ["pii-guard"],
+ model_rpm_limit: { "gpt-4": 20 },
+ model_tpm_limit: { "gpt-4": 100 },
+ },
+ models: ["gpt-4"],
+ spend: 10,
+ model_spend: null,
+ model_rpm_limit: null,
+ model_tpm_limit: null,
+ blocked: false,
+ object_permission_id: null,
+ created_at: "2024-01-01T00:00:00Z",
+ created_by: "user-1",
+ updated_at: "2024-01-02T00:00:00Z",
+ updated_by: "user-1",
+ litellm_budget_table: { max_budget: 50 },
+} as unknown as ProjectResponse;
+
+const renderModal = (data: ProjectResponse = project) =>
+ renderWithProviders(<EditProjectModal isOpen project={data} onClose={vi.fn()} />);
+
+const save = async (user: User) => user.click(screen.getByRole("button", { name: /save changes/i }));
+
+const variables = () => mutate.mock.calls.at(-1)?.[0] as { projectId: string; params: Record<string, unknown> };
+
+describe("EditProjectModal submit payload", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("sends exactly the antd payload for an untouched save", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("My Project");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(variables().projectId).toBe("proj-1");
+ expect(variables().params).toStrictEqual({
+ project_alias: "My Project",
+ description: "A test project",
+ models: ["gpt-4"],
+ max_budget: 50,
+ blocked: false,
+ team_id: "team-1",
+ });
+ });
+
+ it("includes the advanced fields once Advanced Settings has been opened, even after collapsing it again", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("My Project");
+
+ await user.click(screen.getByText("Advanced Settings"));
+ await screen.findByText("Model-Specific Limits");
+ await user.click(screen.getByText("Advanced Settings"));
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params).toStrictEqual({
+ project_alias: "My Project",
+ description: "A test project",
+ models: ["gpt-4"],
+ max_budget: 50,
+ blocked: false,
+ guardrails: ["pii-guard"],
+ model_rpm_limit: { "gpt-4": 20 },
+ model_tpm_limit: { "gpt-4": 100 },
+ metadata: { owner: "platform" },
+ team_id: "team-1",
+ });
+ });
+
+ it("never sends server-only fields from the loaded record", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("My Project");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params).not.toHaveProperty("created_at");
+ expect(variables().params).not.toHaveProperty("updated_at");
+ expect(variables().params).not.toHaveProperty("project_id");
+ expect(variables().params).not.toHaveProperty("spend");
+ expect(variables().params).not.toHaveProperty("budget_id");
+ expect(variables().params).not.toHaveProperty("litellm_budget_table");
+ });
+
+ it("keeps the internal metadata keys out of user metadata", async () => {
+ const user = setup();
+ renderModal();
+ await screen.findByDisplayValue("My Project");
+
+ await user.click(screen.getByText("Advanced Settings"));
+ await screen.findByText("Model-Specific Limits");
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.metadata).toStrictEqual({ owner: "platform" });
+ });
+
+ it("sends an edited project name", async () => {
+ const user = setup();
+ renderModal();
+ const nameInput = await screen.findByDisplayValue("My Project");
+
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed");
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.project_alias).toBe("Renamed");
+ });
+
+ it("omits max_budget when the project has no budget row", async () => {
+ const user = setup();
+ renderModal({ ...project, litellm_budget_table: null } as unknown as ProjectResponse);
+ await screen.findByDisplayValue("My Project");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params.max_budget).toBeUndefined();
+ });
+
+ it("omits guardrails, limits and metadata for a project with empty metadata", async () => {
+ const user = setup();
+ renderModal({ ...project, metadata: null } as unknown as ProjectResponse);
+ await screen.findByDisplayValue("My Project");
+
+ await save(user);
+
+ await waitFor(() => expect(mutate).toHaveBeenCalled());
+ expect(variables().params).not.toHaveProperty("guardrails");
+ expect(variables().params).not.toHaveProperty("model_rpm_limit");
+ expect(variables().params).not.toHaveProperty("model_tpm_limit");
+ expect(variables().params).not.toHaveProperty("metadata");
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.tsx
index ad3254a773c..d8b4076f404 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/EditProjectModal.tsx
@@ -1,10 +1,17 @@
-import { useEffect } from "react";
-import { Modal, Form, Button, Typography } from "antd";
-import { SaveOutlined } from "@ant-design/icons";
+"use client";
+
+import { useState } from "react";
+import { Modal } from "antd";
+import { Save } from "lucide-react";
+
import { toast } from "@/lib/toast";
+import { useZodForm } from "@/lib/forms/useZodForm";
+import { Button } from "@/components/ui/button";
+import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";
import { ProjectResponse } from "@/app/(dashboard)/hooks/projects/useProjects";
import { useUpdateProject, ProjectUpdateParams } from "@/app/(dashboard)/hooks/projects/useUpdateProject";
-import { ProjectBaseForm, ProjectFormValues } from "./ProjectBaseForm";
+import { ProjectBaseForm } from "./ProjectBaseForm";
+import { projectFormSchema, type ProjectFormValues } from "./projectFormSchema";
import { buildProjectApiParams } from "./projectFormUtils";
interface EditProjectModalProps {
@@ -14,105 +21,101 @@ interface EditProjectModalProps {
onSuccess?: () => void;
}
-export function EditProjectModal({ isOpen, project, onClose, onSuccess }: EditProjectModalProps) {
- const [form] = Form.useForm<ProjectFormValues>();
+const INTERNAL_METADATA_KEYS = new Set(["model_rpm_limit", "model_tpm_limit", "guardrails"]);
+
+const toFormValues = (project: ProjectResponse): ProjectFormValues => {
+ const metadataObj = (project.metadata ?? {}) as Record<string, unknown>;
+ const rpmLimits = (metadataObj.model_rpm_limit ?? {}) as Record<string, number>;
+ const tpmLimits = (metadataObj.model_tpm_limit ?? {}) as Record<string, number>;
+ const guardrails = (Array.isArray(metadataObj.guardrails) ? metadataObj.guardrails : []) as string[];
+
+ const modelLimits = Array.from(new Set([...Object.keys(rpmLimits), ...Object.keys(tpmLimits)])).map((model) => ({
+ model,
+ rpm: rpmLimits[model],
+ tpm: tpmLimits[model],
+ }));
+
+ const metadata = Object.entries(metadataObj)
+ .filter(([key]) => !INTERNAL_METADATA_KEYS.has(key))
+ .map(([key, value]) => ({ key, value: String(value) }));
+
+ return {
+ project_alias: project.project_alias ?? "",
+ team_id: project.team_id ?? "",
+ description: project.description ?? "",
+ models: project.models ?? [],
+ max_budget: project.litellm_budget_table?.max_budget ?? undefined,
+ isBlocked: project.blocked,
+ guardrails: guardrails.length > 0 ? guardrails : undefined,
+ modelLimits: modelLimits.length > 0 ? modelLimits : undefined,
+ metadata: metadata.length > 0 ? metadata : undefined,
+ };
+};
+
+function EditProjectForm({ project, onClose, onSuccess }: Omit<EditProjectModalProps, "isOpen">) {
+ const form = useZodForm(projectFormSchema, { defaultValues: toFormValues(project) });
const updateMutation = useUpdateProject();
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [advancedEverOpened, setAdvancedEverOpened] = useState(false);
- // Populate form with existing project data when modal opens
- useEffect(() => {
- if (isOpen && project) {
- // Model limits are stored inside metadata by the backend
- const metadataObj = (project.metadata ?? {}) as Record<string, unknown>;
- const rpmLimits = (metadataObj.model_rpm_limit ?? {}) as Record<string, number>;
- const tpmLimits = (metadataObj.model_tpm_limit ?? {}) as Record<string, number>;
- const guardrails = (Array.isArray(metadataObj.guardrails) ? metadataObj.guardrails : []) as string[];
-
- const modelLimits: ProjectFormValues["modelLimits"] = [];
- const allLimitModels = new Set([...Object.keys(rpmLimits), ...Object.keys(tpmLimits)]);
- for (const model of allLimitModels) {
- modelLimits.push({
- model,
- rpm: rpmLimits[model],
- tpm: tpmLimits[model],
- });
- }
-
- // Filter out internal keys from user-facing metadata
- const internalKeys = new Set(["model_rpm_limit", "model_tpm_limit", "guardrails"]);
- const metadata: ProjectFormValues["metadata"] = [];
- for (const [key, value] of Object.entries(metadataObj)) {
- if (!internalKeys.has(key)) {
- metadata.push({ key, value: String(value) });
- }
- }
-
- form.setFieldsValue({
- project_alias: project.project_alias ?? "",
- team_id: project.team_id ?? "",
- description: project.description ?? "",
- models: project.models ?? [],
- max_budget: project.litellm_budget_table?.max_budget ?? undefined,
- isBlocked: project.blocked,
- guardrails: guardrails.length > 0 ? guardrails : undefined,
- modelLimits: modelLimits.length > 0 ? modelLimits : undefined,
- metadata: metadata.length > 0 ? metadata : undefined,
- });
- }
- }, [isOpen, project, form]);
-
- const handleSubmit = async () => {
- try {
- const values = await form.validateFields();
- const params: ProjectUpdateParams = {
- ...buildProjectApiParams(values),
- team_id: values.team_id,
- };
-
- updateMutation.mutate(
- { projectId: project.project_id, params },
- {
- onSuccess: () => {
- toast.success("Project updated successfully");
- onSuccess?.();
- onClose();
- },
- onError: (error) => {
- toast.error(error.message || "Failed to update project");
- },
- },
- );
- } catch (error) {
- console.error("Validation failed:", error);
- }
+ const handleAdvancedOpenChange = (open: boolean) => {
+ setAdvancedOpen(open);
+ if (open) setAdvancedEverOpened(true);
};
+ const handleSubmit = form.handleSubmit((values) => {
+ const submitted: ProjectFormValues = advancedEverOpened
+ ? values
+ : { ...values, guardrails: undefined, modelLimits: undefined, metadata: undefined };
+
+ const params: ProjectUpdateParams = {
+ ...buildProjectApiParams(submitted),
+ team_id: submitted.team_id,
+ };
+
+ updateMutation.mutate(
+ { projectId: project.project_id, params },
+ {
+ onSuccess: () => {
+ toast.success("Project updated successfully");
+ onSuccess?.();
+ onClose();
+ },
+ onError: (error) => {
+ toast.error(error.message || "Failed to update project");
+ },
+ },
+ );
+ });
+
+ return (
+ <form onSubmit={(event) => event.preventDefault()}>
+ <ProjectBaseForm form={form} advancedOpen={advancedOpen} onAdvancedOpenChange={handleAdvancedOpenChange} />
+
+ <div className="mt-6 flex justify-end gap-2 border-t border-border pt-4">
+ <Button type="button" variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="button" onClick={() => void handleSubmit()} disabled={updateMutation.isPending}>
+ {updateMutation.isPending ? <UiLoadingSpinner /> : <Save />}
+ Save Changes
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+export function EditProjectModal({ isOpen, project, onClose, onSuccess }: EditProjectModalProps) {
return (
<Modal
- title={
- <Typography.Text strong style={{ fontSize: 18 }}>
- Edit Project
- </Typography.Text>
- }
+ title={<span className="text-lg font-semibold text-foreground">Edit Project</span>}
open={isOpen}
onCancel={onClose}
width={720}
destroyOnHidden
- footer={[
- <Button key="cancel" onClick={onClose}>
- Cancel
- </Button>,
- <Button
- key="submit"
- type="primary"
- icon={<SaveOutlined />}
- loading={updateMutation.isPending}
- onClick={handleSubmit}
- >
- Save Changes
- </Button>,
- ]}
+ footer={null}
>
- <ProjectBaseForm form={form} />
+ <EditProjectForm key={project.project_id} project={project} onClose={onClose} onSuccess={onSuccess} />
</Modal>
);
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.test.tsx
index a3d691e0a40..67abc6fb591 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.test.tsx
@@ -2,8 +2,9 @@ import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import userEvent from "@testing-library/user-event";
import { renderWithProviders, screen, waitFor } from "../../../../../../tests/test-utils";
-import { Form } from "antd";
-import { ProjectBaseForm, ProjectFormValues } from "./ProjectBaseForm";
+import { useZodForm } from "@/lib/forms/useZodForm";
+import { ProjectBaseForm } from "./ProjectBaseForm";
+import { emptyProjectFormValues, projectFormSchema } from "./projectFormSchema";
const mockUseTeams = vi.fn();
vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({
@@ -23,8 +24,9 @@ vi.mock("@/components/key_team_helpers/fetch_available_models_team_key", () => (
}));
function FormWrapper() {
- const [form] = Form.useForm<ProjectFormValues>();
- return <ProjectBaseForm form={form} />;
+ const [advancedOpen, setAdvancedOpen] = React.useState(false);
+ const form = useZodForm(projectFormSchema, { defaultValues: emptyProjectFormValues });
+ return <ProjectBaseForm form={form} advancedOpen={advancedOpen} onAdvancedOpenChange={setAdvancedOpen} />;
}
describe("ProjectBaseForm", () => {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.tsx
index 24ad8c40b98..d4b7e71dfe9 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/ProjectBaseForm.tsx
@@ -1,46 +1,45 @@
+"use client";
+
import { useEffect, useState } from "react";
-import {
- Alert,
- Col,
- Collapse,
- Divider,
- Flex,
- Form,
- Input,
- InputNumber,
- Row,
- Select,
- Space,
- Switch,
- Typography,
- Button,
-} from "antd";
-import type { FormInstance } from "antd";
-import { PlusOutlined, MinusCircleOutlined } from "@ant-design/icons";
+import { useFieldArray, useWatch, type UseFormReturn } from "react-hook-form";
+import { ChevronDown, CircleAlert, Minus, Plus } from "lucide-react";
+
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
+import { ALL_TEAM_MODELS, type ProjectFormValues } from "./projectFormSchema";
import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";
import { Team } from "@/components/key_team_helpers/key_list";
import { fetchTeamModels } from "@/components/organisms/create_key_button";
import { getModelDisplayName } from "@/components/key_team_helpers/fetch_available_models_team_key";
import { getGuardrailsList } from "@/components/networking";
+import { TagsInput } from "@/app/(dashboard)/guardrails/_components/content_filter/TagsInput";
+import { Alert, AlertTitle } from "@/components/shared/Alert";
+import { SearchSelect } from "@/components/shared/SearchSelect";
+import { FieldGroup } from "@/components/shared/form/field";
+import { FormField } from "@/components/shared/form/FormField";
+import { Button } from "@/components/ui/button";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Input } from "@/components/ui/input";
+import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from "@/components/ui/input-group";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Separator } from "@/components/ui/separator";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
-export interface ProjectFormValues {
- project_alias: string;
- team_id: string;
- description?: string;
- models: string[];
- max_budget?: number;
- isBlocked: boolean;
- guardrails?: string[];
- modelLimits?: { model: string; tpm?: number; rpm?: number }[];
- metadata?: { key: string; value: string }[];
-}
+const toOptionalNumber = (raw: string): number | undefined => {
+ if (raw.trim() === "") return undefined;
+ const parsed = Number(raw);
+ return Number.isNaN(parsed) ? undefined : parsed;
+};
interface ProjectBaseFormProps {
- form: FormInstance<ProjectFormValues>;
+ form: UseFormReturn<ProjectFormValues>;
+ advancedOpen: boolean;
+ onAdvancedOpenChange: (open: boolean) => void;
}
-export function ProjectBaseForm({ form }: ProjectBaseFormProps) {
+export type { ProjectFormValues } from "./projectFormSchema";
+
+export function ProjectBaseForm({ form, advancedOpen, onAdvancedOpenChange }: ProjectBaseFormProps) {
const { accessToken, userId, userRole } = useAuthorized();
const { data: teams } = useTeams();
@@ -48,6 +47,12 @@ export function ProjectBaseForm({ form }: ProjectBaseFormProps) {
const [modelsToPick, setModelsToPick] = useState<string[]>([]);
const [guardrailsList, setGuardrailsList] = useState<string[]>([]);
+ const modelLimits = useFieldArray({ control: form.control, name: "modelLimits" });
+ const metadata = useFieldArray({ control: form.control, name: "metadata" });
+
+ const teamIdValue = useWatch({ control: form.control, name: "team_id" });
+ const isBlocked = useWatch({ control: form.control, name: "isBlocked" });
+
useEffect(() => {
const fetchGuardrails = async () => {
if (!accessToken) return;
@@ -62,8 +67,6 @@ export function ProjectBaseForm({ form }: ProjectBaseFormProps) {
fetchGuardrails();
}, [accessToken]);
- // Sync selectedTeam from form value (needed for edit mode pre-fill)
- const teamIdValue = Form.useWatch("team_id", form);
useEffect(() => {
if (teamIdValue && teams) {
const team = teams.find((t) => t.team_id === teamIdValue) ?? null;
@@ -73,7 +76,6 @@ export function ProjectBaseForm({ form }: ProjectBaseFormProps) {
}
}, [teamIdValue, teams, selectedTeam?.team_id]);
- // Fetch team-scoped models when team selection changes
useEffect(() => {
if (userId && userRole && accessToken && selectedTeam) {
fetchTeamModels(userId, userRole, accessToken, selectedTeam.team_id).then((models) => {
@@ -88,274 +90,270 @@ export function ProjectBaseForm({ form }: ProjectBaseFormProps) {
const handleTeamChange = (teamId: string) => {
const team = teams?.find((t) => t.team_id === teamId) ?? null;
setSelectedTeam(team);
- form.setFieldValue("models", []);
+ form.setValue("models", []);
};
+ const teamOptions = (teams ?? []).map((team) => ({
+ value: team.team_id,
+ label: team.team_alias || team.team_id,
+ sublabel: team.team_id,
+ }));
+
+ const modelOptions = [
+ { value: ALL_TEAM_MODELS, label: "All Team Models" },
+ ...modelsToPick.map((model) => ({ value: model, label: getModelDisplayName(model) })),
+ ];
+ const modelsPlaceholder = selectedTeam ? "Select models" : "Select a team first";
+
return (
- <Form
- form={form}
- layout="vertical"
- name="project_form"
- initialValues={{ isBlocked: false }}
- style={{ marginTop: 24 }}
- >
- {/* Basic Info */}
- <Typography.Text
- strong
- style={{
- fontSize: 13,
- color: "#374151",
- textTransform: "uppercase",
- letterSpacing: "0.05em",
- }}
- >
- Basic Information
- </Typography.Text>
- <Divider style={{ marginTop: 8, marginBottom: 16 }} />
+ <div className="mt-6">
+ <p className="text-xs font-semibold tracking-[0.05em] text-foreground uppercase">Basic Information</p>
+ <Separator className="mt-2 mb-4" />
- <Row gutter={24}>
- <Col span={12}>
- <Form.Item
- name="project_alias"
- label="Project Name"
- rules={[{ required: true, message: "Please enter a project name" }]}
- >
- <Input placeholder="e.g. Customer Support Bot" />
- </Form.Item>
- </Col>
- <Col span={12}>
- <Form.Item name="team_id" label="Team" rules={[{ required: true, message: "Please select a team" }]}>
- <Select
- showSearch
- placeholder="Search or select a team"
- onChange={handleTeamChange}
- allowClear
- optionLabelProp="label"
- filterOption={(input, option) => {
- const team = teams?.find((t) => t.team_id === option?.value);
- if (!team) return false;
- const search = input.toLowerCase().trim();
- return (
- (team.team_alias || "").toLowerCase().includes(search) || team.team_id.toLowerCase().includes(search)
- );
- }}
- >
- {teams?.map((team) => (
- <Select.Option key={team.team_id} value={team.team_id} label={team.team_alias || team.team_id}>
- <span style={{ fontWeight: 500 }}>{team.team_alias}</span>{" "}
- <span style={{ color: "#9ca3af" }}>({team.team_id})</span>
- </Select.Option>
- ))}
- </Select>
- </Form.Item>
- </Col>
- </Row>
+ <FieldGroup>
+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
+ <FormField control={form.control} name="project_alias" label="Project Name">
+ {({ ref, ...field }) => (
+ <Input {...field} value={field.value ?? ""} ref={ref} placeholder="e.g. Customer Support Bot" />
+ )}
+ </FormField>
- <Row>
- <Col span={24}>
- <Form.Item name="description" label="Description">
- <Input.TextArea placeholder="Describe the purpose of this project" rows={3} />
- </Form.Item>
- </Col>
- </Row>
+ <FormField control={form.control} name="team_id" label="Team">
+ {({ id, value, onChange, ref: _ref, ...field }) => (
+ <SearchSelect
+ {...field}
+ inputId={id}
+ options={teamOptions}
+ value={value}
+ onValueChange={(next) => {
+ onChange(next);
+ handleTeamChange(next);
+ }}
+ placeholder="Search or select a team"
+ allowClear
+ />
+ )}
+ </FormField>
+ </div>
- <Row>
- <Col span={24}>
- <Form.Item
- name="models"
- label="Allowed Models (scoped to selected team's models)"
- help={!selectedTeam ? "Select a team first to see available models" : undefined}
- >
+ <FormField control={form.control} name="description" label="Description">
+ {({ ref, ...field }) => (
+ <Textarea
+ {...field}
+ value={field.value ?? ""}
+ ref={ref}
+ rows={3}
+ placeholder="Describe the purpose of this project"
+ />
+ )}
+ </FormField>
+
+ <FormField
+ control={form.control}
+ name="models"
+ label="Allowed Models (scoped to selected team's models)"
+ description={!selectedTeam ? "Select a team first to see available models" : undefined}
+ >
+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (
<Select
- mode="multiple"
- placeholder={selectedTeam ? "Select models" : "Select a team first"}
+ multiple
+ items={modelOptions}
+ value={value}
+ onValueChange={(next: string[]) => onChange(next.includes(ALL_TEAM_MODELS) ? [ALL_TEAM_MODELS] : next)}
disabled={!selectedTeam}
- allowClear
- maxTagCount="responsive"
- onChange={(values) => {
- if (values.includes("all-team-models")) {
- form.setFieldsValue({ models: ["all-team-models"] });
- }
- }}
>
- <Select.Option key="all-team-models" value="all-team-models">
- All Team Models
- </Select.Option>
- {modelsToPick.map((model) => (
- <Select.Option key={model} value={model}>
- {getModelDisplayName(model)}
- </Select.Option>
- ))}
+ <SelectTrigger id={id} aria-invalid={ariaInvalid} aria-describedby={ariaDescribedBy} className="w-full">
+ <SelectValue placeholder={modelsPlaceholder}>
+ {(selected: string[]) =>
+ selected.length === 0
+ ? modelsPlaceholder
+ : modelOptions
+ .filter((option) => selected.includes(option.value))
+ .map((option) => option.label)
+ .join(", ")
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {modelOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value} title={option.label}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
</Select>
- </Form.Item>
- </Col>
- </Row>
+ )}
+ </FormField>
- <Row gutter={24}>
- <Col span={12}>
- <Form.Item name="max_budget" label="Max Budget (USD)">
- <InputNumber prefix="$" style={{ width: "100%" }} placeholder="0.00" min={0} precision={2} />
- </Form.Item>
- </Col>
- </Row>
+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
+ <FormField control={form.control} name="max_budget" label="Max Budget (USD)">
+ {({ ref, value, onChange, ...field }) => (
+ <InputGroup>
+ <InputGroupAddon>
+ <InputGroupText>$</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ {...field}
+ ref={ref}
+ type="number"
+ min={0}
+ placeholder="0.00"
+ value={value ?? ""}
+ onChange={(event) => onChange(toOptionalNumber(event.target.value))}
+ />
+ </InputGroup>
+ )}
+ </FormField>
+ </div>
+ </FieldGroup>
- {/* Advanced Settings */}
- <Row>
- <Col span={24}>
- <Collapse
- ghost
- style={{
- background: "#f9fafb",
- borderRadius: 8,
- border: "1px solid #e5e7eb",
- }}
- items={[
- {
- key: "1",
- label: (
- <Typography.Text strong style={{ color: "#374151" }}>
- Advanced Settings
- </Typography.Text>
- ),
- children: (
- <>
- <Flex align="center" gap={12}>
- <Typography.Text strong>Block Project</Typography.Text>
- <Form.Item name="isBlocked" valuePropName="checked" noStyle>
- <Switch />
- </Form.Item>
- </Flex>
- <Form.Item noStyle shouldUpdate={(prev, cur) => prev.isBlocked !== cur.isBlocked}>
- {({ getFieldValue }) =>
- getFieldValue("isBlocked") ? (
- <Alert
- banner
- type="warning"
- showIcon
- message="All API requests using keys under this project will be rejected."
- style={{ marginTop: 12 }}
- />
- ) : null
- }
- </Form.Item>
+ <Collapsible
+ open={advancedOpen}
+ onOpenChange={onAdvancedOpenChange}
+ className="mt-6 rounded-lg border border-border bg-muted"
+ >
+ <CollapsibleTrigger
+ render={
+ <button type="button" className="flex w-full items-center gap-2 px-4 py-3 text-left">
+ <ChevronDown
+ className={`size-4 text-muted-foreground transition-transform ${advancedOpen ? "" : "-rotate-90"}`}
+ />
+ <span className="text-sm font-semibold text-foreground">Advanced Settings</span>
+ </button>
+ }
+ />
+ <CollapsibleContent className="px-4 pb-4">
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-semibold text-foreground">Block Project</span>
+ <FormField control={form.control} name="isBlocked" className="w-auto">
+ {({ id, value, onChange, ref: _ref, ...field }) => (
+ <Switch {...field} id={id} checked={value} onCheckedChange={onChange} />
+ )}
+ </FormField>
+ </div>
- <Divider />
+ {isBlocked ? (
+ <Alert variant="warning" className="mt-3">
+ <CircleAlert />
+ <AlertTitle>All API requests using keys under this project will be rejected.</AlertTitle>
+ </Alert>
+ ) : null}
- <Form.Item label="Guardrails" name="guardrails" help="Select existing guardrails or enter new ones">
- <Select
- mode="tags"
- style={{ width: "100%" }}
- placeholder="Select or enter guardrails"
- options={guardrailsList.map((name) => ({
- value: name,
- label: name,
- }))}
- />
- </Form.Item>
+ <Separator className="my-4" />
- <Divider />
+ <FormField
+ control={form.control}
+ name="guardrails"
+ label="Guardrails"
+ description="Select existing guardrails or enter new ones"
+ >
+ {({ id, value, onChange }) => (
+ <TagsInput
+ id={id}
+ value={value ?? []}
+ onValueChange={onChange}
+ options={guardrailsList.map((name) => ({ label: name, value: name }))}
+ placeholder="Select or enter guardrails"
+ />
+ )}
+ </FormField>
- <Typography.Text strong style={{ display: "block", marginBottom: 12 }}>
- Model-Specific Limits
- </Typography.Text>
- <Form.List name="modelLimits">
- {(fields, { add, remove }) => (
- <>
- {fields.map(({ key, name, ...restField }) => (
- <Space key={key} style={{ display: "flex", marginBottom: 8 }} align="baseline">
- <Form.Item
- {...restField}
- name={[name, "model"]}
- rules={[
- { required: true, message: "Missing model" },
- {
- validator: (_, value) => {
- if (!value) return Promise.resolve();
- const all = form.getFieldValue("modelLimits") ?? [];
- const dupes = all.filter((entry: { model?: string }) => entry?.model === value);
- if (dupes.length > 1) {
- return Promise.reject(new Error("Duplicate model"));
- }
- return Promise.resolve();
- },
- },
- ]}
- >
- <Input placeholder="Model name (e.g. gpt-4)" />
- </Form.Item>
- <Form.Item {...restField} name={[name, "tpm"]}>
- <InputNumber placeholder="TPM Limit" min={0} />
- </Form.Item>
- <Form.Item {...restField} name={[name, "rpm"]}>
- <InputNumber placeholder="RPM Limit" min={0} />
- </Form.Item>
- <MinusCircleOutlined onClick={() => remove(name)} style={{ color: "#ef4444" }} />
- </Space>
- ))}
- <Form.Item>
- <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
- Add Model Limit
- </Button>
- </Form.Item>
- </>
- )}
- </Form.List>
+ <Separator className="my-4" />
- <Divider />
+ <p className="mb-3 text-sm font-semibold text-foreground">Model-Specific Limits</p>
+ {modelLimits.fields.map((field, index) => (
+ <div key={field.id} className="mb-2 flex items-start gap-2">
+ <FormField control={form.control} name={`modelLimits.${index}.model`}>
+ {({ ref, ...control }) => (
+ <Input {...control} value={control.value ?? ""} ref={ref} placeholder="Model name (e.g. gpt-4)" />
+ )}
+ </FormField>
+ <FormField control={form.control} name={`modelLimits.${index}.tpm`}>
+ {({ ref, value, onChange, ...control }) => (
+ <Input
+ {...control}
+ ref={ref}
+ type="number"
+ min={0}
+ placeholder="TPM Limit"
+ value={value ?? ""}
+ onChange={(event) => onChange(toOptionalNumber(event.target.value))}
+ />
+ )}
+ </FormField>
+ <FormField control={form.control} name={`modelLimits.${index}.rpm`}>
+ {({ ref, value, onChange, ...control }) => (
+ <Input
+ {...control}
+ ref={ref}
+ type="number"
+ min={0}
+ placeholder="RPM Limit"
+ value={value ?? ""}
+ onChange={(event) => onChange(toOptionalNumber(event.target.value))}
+ />
+ )}
+ </FormField>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="mt-1 text-destructive"
+ onClick={() => modelLimits.remove(index)}
+ aria-label={`Remove model limit ${index + 1}`}
+ >
+ <Minus />
+ </Button>
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full border-dashed"
+ onClick={() => modelLimits.append({ model: "", tpm: undefined, rpm: undefined })}
+ >
+ <Plus />
+ Add Model Limit
+ </Button>
- <Typography.Text strong style={{ display: "block", marginBottom: 12 }}>
- Metadata
- </Typography.Text>
- <Form.List name="metadata">
- {(fields, { add, remove }) => (
- <>
- {fields.map(({ key, name, ...restField }) => (
- <Space key={key} style={{ display: "flex", marginBottom: 8 }} align="baseline">
- <Form.Item
- {...restField}
- name={[name, "key"]}
- rules={[
- { required: true, message: "Missing key" },
- {
- validator: (_, value) => {
- if (!value) return Promise.resolve();
- const all = form.getFieldValue("metadata") ?? [];
- const dupes = all.filter((entry: { key?: string }) => entry?.key === value);
- if (dupes.length > 1) {
- return Promise.reject(new Error("Duplicate key"));
- }
- return Promise.resolve();
- },
- },
- ]}
- >
- <Input placeholder="Key" />
- </Form.Item>
- <Form.Item
- {...restField}
- name={[name, "value"]}
- rules={[{ required: true, message: "Missing value" }]}
- >
- <Input placeholder="Value" />
- </Form.Item>
- <MinusCircleOutlined onClick={() => remove(name)} style={{ color: "#ef4444" }} />
- </Space>
- ))}
- <Form.Item>
- <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
- Add Key-Value Pair
- </Button>
- </Form.Item>
- </>
- )}
- </Form.List>
- </>
- ),
- },
- ]}
- />
- </Col>
- </Row>
- </Form>
+ <Separator className="my-4" />
+
+ <p className="mb-3 text-sm font-semibold text-foreground">Metadata</p>
+ {metadata.fields.map((field, index) => (
+ <div key={field.id} className="mb-2 flex items-start gap-2">
+ <FormField control={form.control} name={`metadata.${index}.key`}>
+ {({ ref, ...control }) => (
+ <Input {...control} value={control.value ?? ""} ref={ref} placeholder="Key" />
+ )}
+ </FormField>
+ <FormField control={form.control} name={`metadata.${index}.value`}>
+ {({ ref, ...control }) => (
+ <Input {...control} value={control.value ?? ""} ref={ref} placeholder="Value" />
+ )}
+ </FormField>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="mt-1 text-destructive"
+ onClick={() => metadata.remove(index)}
+ aria-label={`Remove metadata pair ${index + 1}`}
+ >
+ <Minus />
+ </Button>
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full border-dashed"
+ onClick={() => metadata.append({ key: "", value: "" })}
+ >
+ <Plus />
+ Add Key-Value Pair
+ </Button>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
);
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormSchema.ts b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormSchema.ts
new file mode 100644
index 00000000000..3fe1b0baacb
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormSchema.ts
@@ -0,0 +1,63 @@
+import { z } from "zod/v4";
+
+export const ALL_TEAM_MODELS = "all-team-models";
+
+const repeatsEarlierValue = (values: readonly string[], index: number): boolean =>
+ values[index] !== "" && values.indexOf(values[index]) !== index;
+
+export const projectFormSchema = z
+ .object({
+ project_alias: z.string().min(1, "Please enter a project name"),
+ team_id: z.string().min(1, "Please select a team"),
+ description: z.string().optional(),
+ models: z.array(z.string()),
+ max_budget: z.number().optional(),
+ isBlocked: z.boolean(),
+ guardrails: z.array(z.string()).optional(),
+ modelLimits: z
+ .array(
+ z.object({
+ model: z.string().min(1, "Missing model"),
+ tpm: z.number().optional(),
+ rpm: z.number().optional(),
+ }),
+ )
+ .optional(),
+ metadata: z
+ .array(
+ z.object({
+ key: z.string().min(1, "Missing key"),
+ value: z.string().min(1, "Missing value"),
+ }),
+ )
+ .optional(),
+ })
+ .superRefine((values, ctx) => {
+ const models = (values.modelLimits ?? []).map((entry) => entry.model);
+ models.forEach((_, index) => {
+ if (repeatsEarlierValue(models, index)) {
+ ctx.addIssue({ code: "custom", message: "Duplicate model", path: ["modelLimits", index, "model"] });
+ }
+ });
+
+ const keys = (values.metadata ?? []).map((entry) => entry.key);
+ keys.forEach((_, index) => {
+ if (repeatsEarlierValue(keys, index)) {
+ ctx.addIssue({ code: "custom", message: "Duplicate key", path: ["metadata", index, "key"] });
+ }
+ });
+ });
+
+export type ProjectFormValues = z.output<typeof projectFormSchema>;
+
+export const emptyProjectFormValues: ProjectFormValues = {
+ project_alias: "",
+ team_id: "",
+ description: undefined,
+ models: [],
+ max_budget: undefined,
+ isBlocked: false,
+ guardrails: undefined,
+ modelLimits: undefined,
+ metadata: undefined,
+};
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormUtils.ts b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormUtils.ts
index 45323bb47ec..71e1eb71aa5 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormUtils.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/projects/_components/ProjectModals/projectFormUtils.ts
@@ -23,7 +23,7 @@ export function buildProjectApiParams(values: ProjectFormValues) {
project_alias: values.project_alias,
description: values.description,
models: values.models ?? [],
- max_budget: values.max_budget,
+ max_budget: values.max_budget === undefined ? undefined : Math.round(values.max_budget * 100) / 100,
blocked: values.isBlocked ?? false,
...(values.guardrails &&
values.guardrails.length > 0 && {
diff --git a/ui/litellm-dashboard/src/components/add_pass_through.integration.test.tsx b/ui/litellm-dashboard/src/components/add_pass_through.integration.test.tsx
new file mode 100644
index 00000000000..7adc6958a6d
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_pass_through.integration.test.tsx
@@ -0,0 +1,217 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
+import { renderWithProviders, screen, waitFor } from "../../tests/test-utils";
+import AddPassThroughEndpoint from "./add_pass_through";
+
+const createPassThroughEndpoint = vi.fn();
+
+vi.mock("./networking", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./networking")>()),
+ createPassThroughEndpoint: (...args: unknown[]) => createPassThroughEndpoint(...args),
+ getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [] }),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
+}));
+
+const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
+
+type User = ReturnType<typeof setup>;
+
+const renderForm = (premiumUser = true) =>
+ renderWithProviders(
+ <AddPassThroughEndpoint
+ accessToken="test-token"
+ passThroughItems={[]}
+ setPassThroughItems={vi.fn()}
+ premiumUser={premiumUser}
+ />,
+ );
+
+const openModal = async (user: User) => {
+ await user.click(screen.getByRole("button", { name: "+ Add Pass-Through Endpoint" }));
+ await screen.findByText("Route Configuration");
+};
+
+const fillRequiredFields = async (user: User) => {
+ await user.type(screen.getByPlaceholderText("bria"), "bria");
+ await user.type(screen.getByPlaceholderText("https://engine.prod.bria-api.com"), "https://example.com");
+ await user.click(screen.getByRole("button", { name: /add header/i }));
+ await user.type(screen.getByPlaceholderText("Header Name"), "Authorization");
+ await user.type(screen.getByPlaceholderText("Header Value"), "Bearer abc");
+};
+
+const submit = async (user: User) => user.click(screen.getByRole("button", { name: "Add Pass-Through Endpoint" }));
+
+const lastPayload = () => createPassThroughEndpoint.mock.calls.at(-1)?.[1] as Record<string, unknown>;
+
+describe("add_pass_through submit payload", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ createPassThroughEndpoint.mockResolvedValue({ endpoints: [{ id: "generated-id", path: "/bria" }] });
+ });
+
+ it("sends exactly the antd payload, once, for a minimal endpoint", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+ await user.type(screen.getByPlaceholderText("600"), "900");
+ await user.type(screen.getByPlaceholderText("2.0000"), "1.5");
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+
+ expect(createPassThroughEndpoint).toHaveBeenCalledTimes(1);
+ expect(createPassThroughEndpoint.mock.calls[0][0]).toBe("test-token");
+ expect(lastPayload()).toStrictEqual({
+ path: "/bria",
+ target: "https://example.com",
+ headers: { Authorization: "Bearer abc" },
+ include_subpath: true,
+ methods: undefined,
+ default_query_params: undefined,
+ auth: undefined,
+ timeout: "900",
+ cost_per_request: "1.5",
+ });
+ });
+
+ it("submits numeric fields as strings, not numbers", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+ await user.type(screen.getByPlaceholderText("600"), "900");
+ await user.type(screen.getByPlaceholderText("2.0000"), "1.5");
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().timeout).toBe("900");
+ expect(lastPayload().cost_per_request).toBe("1.5");
+ });
+
+ it("prefixes the path with a slash when the user omits it", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().path).toBe("/bria");
+ });
+
+ it("includes selected HTTP methods as an array", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await user.click(screen.getByLabelText(/HTTP Methods/));
+ await user.click(await screen.findByTitle("POST"));
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().methods).toStrictEqual(["POST"]);
+ });
+
+ it("sends auth true once the premium security toggle is switched on", async () => {
+ const user = setup();
+ renderForm(true);
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ const switches = screen.getAllByRole("switch");
+ expect(switches).toHaveLength(2);
+ await user.click(switches[1]);
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().auth).toBe(true);
+ });
+
+ it("omits the auth key entirely for a non-premium user", async () => {
+ const user = setup();
+ renderForm(false);
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload()).not.toHaveProperty("auth");
+ });
+
+ it("drops include_subpath to false when the toggle is switched off", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await user.click(screen.getAllByRole("switch")[0]);
+
+ await submit(user);
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().include_subpath).toBe(false);
+ });
+
+ it("does not submit when required fields are missing", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+
+ await submit(user);
+
+ expect(await screen.findByText("Path is required")).toBeInTheDocument();
+ expect(screen.getByText("Target URL is required")).toBeInTheDocument();
+ expect(screen.getByText("Please configure the headers")).toBeInTheDocument();
+ expect(createPassThroughEndpoint).not.toHaveBeenCalled();
+ });
+
+ it("does not submit when the target is not a valid URL", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await user.clear(screen.getByPlaceholderText("https://engine.prod.bria-api.com"));
+ await user.type(screen.getByPlaceholderText("https://engine.prod.bria-api.com"), "not a url");
+
+ await submit(user);
+
+ expect(await screen.findByText("Please enter a valid URL")).toBeInTheDocument();
+ expect(createPassThroughEndpoint).not.toHaveBeenCalled();
+ });
+
+ it("submits when Enter is pressed in the path field", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await user.type(screen.getByPlaceholderText("bria"), "{Enter}");
+
+ await waitFor(() => expect(createPassThroughEndpoint).toHaveBeenCalled());
+ expect(createPassThroughEndpoint).toHaveBeenCalledTimes(1);
+ expect(lastPayload().path).toBe("/bria");
+ });
+
+ it("does not submit when Cancel is clicked", async () => {
+ const user = setup();
+ renderForm();
+ await openModal(user);
+ await fillRequiredFields(user);
+
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(createPassThroughEndpoint).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_pass_through.tsx b/ui/litellm-dashboard/src/components/add_pass_through.tsx
index 8788c8ef8db..6d6fe4b0dc7 100644
--- a/ui/litellm-dashboard/src/components/add_pass_through.tsx
+++ b/ui/litellm-dashboard/src/components/add_pass_through.tsx
@@ -1,14 +1,14 @@
-/**
- * Modal to add fallbacks to the proxy router config
- */
+"use client";
import React, { useState } from "react";
-import { Button, TextInput, Switch } from "@tremor/react";
import { Card, Title, Subtitle } from "@tremor/react";
+import { Modal, Alert } from "antd";
+import { CircleHelp, Plug } from "lucide-react";
+import { useWatch } from "react-hook-form";
+import { z } from "zod/v4";
+
import { createPassThroughEndpoint } from "./networking";
-import { Modal, Form, Select as Select2, Tooltip, Alert } from "antd";
import NumericalInput from "./shared/numerical_input";
-import { InfoCircleOutlined, ApiOutlined } from "@ant-design/icons";
import KeyValueInput from "./key_value_input";
import QueryParamInput from "./query_param_input";
import { passThroughItem } from "./PassThroughSettings/PassThroughSettings";
@@ -16,12 +16,61 @@ import RoutePreview from "./route_preview";
import { toast } from "@/lib/toast";
import PassThroughSecuritySection from "./common_components/PassThroughSecuritySection";
import PassThroughGuardrailsSection from "./common_components/PassThroughGuardrailsSection";
-const { Option } = Select2;
+import { FormField } from "@/components/shared/form/FormField";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { useZodForm } from "@/lib/forms/useZodForm";
+
+const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
+const HTTP_METHOD_OPTIONS = HTTP_METHODS.map((method) => ({ label: method, value: method }));
+
+type GuardrailSettings = Record<string, { request_fields?: string[]; response_fields?: string[] } | null>;
+
+const passThroughFormSchema = z.object({
+ path: z.string().min(1, "Path is required").regex(/^\//, "Path is required"),
+ target: z
+ .string()
+ .min(1, "Target URL is required")
+ .pipe(z.url({ error: "Please enter a valid URL" })),
+ methods: z.array(z.string()).optional(),
+ include_subpath: z.boolean(),
+ headers: z.record(z.string(), z.string(), { error: "Please configure the headers" }),
+ default_query_params: z.record(z.string(), z.string()).optional(),
+ auth: z.boolean().optional(),
+ timeout: z.string().optional(),
+ cost_per_request: z.string().optional(),
+});
-const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"];
+type PassThroughFormValues = z.output<typeof passThroughFormSchema>;
+
+const emptyFormValues = {
+ path: "",
+ target: "",
+ methods: undefined,
+ include_subpath: true,
+ headers: undefined,
+ default_query_params: undefined,
+ auth: undefined,
+ timeout: undefined,
+ cost_per_request: undefined,
+} as unknown as PassThroughFormValues;
+
+const labelWithHint = (label: React.ReactNode, hint: string): React.ReactNode => (
+ <>
+ {label}
+ <Tooltip>
+ <TooltipTrigger render={<CircleHelp className="size-3.5 shrink-0 cursor-help text-muted-foreground" />} />
+ <TooltipContent>{hint}</TooltipContent>
+ </Tooltip>
+ </>
+);
+
+const optionalText = (raw: string): string | undefined => (raw === "" ? undefined : raw);
interface AddFallbacksProps {
- // models: string[] | undefined;
accessToken: string;
passThroughItems: passThroughItem[];
setPassThroughItems: React.Dispatch<React.SetStateAction<passThroughItem[]>>;
@@ -34,69 +83,45 @@ const AddPassThroughEndpoint: React.FC<AddFallbacksProps> = ({
passThroughItems,
premiumUser = false,
}) => {
- const [form] = Form.useForm();
const [isModalVisible, setIsModalVisible] = useState(false);
const [isLoading, setIsLoading] = useState(false);
- const [pathValue, setPathValue] = useState("");
- const [targetValue, setTargetValue] = useState("");
- const [includeSubpath, setIncludeSubpath] = useState(true);
- const [authEnabled, setAuthEnabled] = useState(false);
- const [selectedMethods, setSelectedMethods] = useState<string[]>([]);
- const [guardrails, setGuardrails] = useState<
- Record<string, { request_fields?: string[]; response_fields?: string[] } | null>
- >({});
+ const [guardrails, setGuardrails] = useState<GuardrailSettings>({});
+ const form = useZodForm(passThroughFormSchema, { defaultValues: emptyFormValues });
+
+ const pathValue = useWatch({ control: form.control, name: "path" });
+ const targetValue = useWatch({ control: form.control, name: "target" });
+ const includeSubpath = useWatch({ control: form.control, name: "include_subpath" });
+ const selectedMethods = useWatch({ control: form.control, name: "methods" }) ?? [];
+
const handleCancel = () => {
- form.resetFields();
- setPathValue("");
- setTargetValue("");
- setIncludeSubpath(true);
- setSelectedMethods([]);
+ form.reset(emptyFormValues);
setGuardrails({});
setIsModalVisible(false);
};
- const handlePathChange = (value: string) => {
- // Auto-add leading slash if missing
- let formattedPath = value;
- if (value && !value.startsWith("/")) {
- formattedPath = "/" + value;
- }
- setPathValue(formattedPath);
- form.setFieldsValue({ path: formattedPath });
- };
-
- const addPassThrough = async (formValues: Record<string, any>) => {
+ const addPassThrough = async (values: PassThroughFormValues) => {
setIsLoading(true);
try {
- // Remove auth field if not premium user
- if (!premiumUser && "auth" in formValues) {
- delete formValues.auth;
- }
-
- // Add guardrails to formValues (only if not empty)
- if (guardrails && Object.keys(guardrails).length > 0) {
- formValues.guardrails = guardrails;
- }
-
- // Add methods to formValues (only if specific methods are selected)
- if (selectedMethods && selectedMethods.length > 0) {
- formValues.methods = selectedMethods;
- }
+ const formValues = {
+ path: values.path,
+ target: values.target,
+ methods: values.methods,
+ include_subpath: values.include_subpath,
+ headers: values.headers,
+ default_query_params: values.default_query_params,
+ ...(premiumUser ? { auth: values.auth } : {}),
+ timeout: values.timeout,
+ cost_per_request: values.cost_per_request,
+ ...(Object.keys(guardrails).length > 0 ? { guardrails } : {}),
+ };
const response = await createPassThroughEndpoint(accessToken, formValues);
-
- // Use the created endpoint from the API response (includes the generated ID)
const createdEndpoint = response.endpoints[0];
- const updatedPassThroughSettings = [...passThroughItems, createdEndpoint];
- setPassThroughItems(updatedPassThroughSettings);
+ setPassThroughItems([...passThroughItems, createdEndpoint]);
toast.success("Pass-through endpoint created successfully");
- form.resetFields();
- setPathValue("");
- setTargetValue("");
- setIncludeSubpath(true);
- setSelectedMethods([]);
+ form.reset(emptyFormValues);
setGuardrails({});
setIsModalVisible(false);
} catch (error) {
@@ -107,284 +132,260 @@ const AddPassThroughEndpoint: React.FC<AddFallbacksProps> = ({
};
return (
- <div>
- <Button className="mx-auto mb-4 mt-4" onClick={() => setIsModalVisible(true)}>
- + Add Pass-Through Endpoint
- </Button>
- <Modal
- title={
- <div className="flex items-center space-x-3 pb-4 border-b border-gray-100">
- <ApiOutlined className="text-xl text-blue-500" />
- <h2 className="text-xl font-semibold text-gray-900">Add Pass-Through Endpoint</h2>
- </div>
- }
- open={isModalVisible}
- width={1000}
- onCancel={handleCancel}
- footer={null}
- className="top-8"
- styles={{
- body: { padding: "24px" },
- header: { padding: "24px 24px 0 24px", border: "none" },
- }}
- >
- <div className="mt-6">
- <Alert
- message="What is a Pass-Through Endpoint?"
- description="Route requests from your LiteLLM proxy to any external API. Perfect for custom models, image generation APIs, or any service you want to proxy through LiteLLM."
- type="info"
- showIcon
- className="mb-6"
- />
-
- <Form
- form={form}
- onFinish={addPassThrough}
- layout="vertical"
- className="space-y-6"
- initialValues={{
- include_subpath: true,
- path: pathValue,
- target: targetValue,
- }}
- >
- {/* Route Configuration Section */}
- <Card className="p-5">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Route Configuration</Title>
- <Subtitle className="text-gray-600 mb-5">
- Configure how requests to your domain will be forwarded to the target API
- </Subtitle>
-
- <div className="space-y-5">
- <Form.Item
- label={<span className="text-sm font-medium text-gray-700">Path Prefix</span>}
- name="path"
- rules={[{ required: true, message: "Path is required", pattern: /^\// }]}
- extra={
- <div className="text-xs text-gray-500 mt-1">Example: /bria, /adobe-photoshop, /elasticsearch</div>
- }
- className="mb-4"
- >
- <div className="flex items-center">
- <TextInput
- placeholder="bria"
- value={pathValue}
- onChange={(e) => handlePathChange(e.target.value)}
- className="flex-1"
- />
- </div>
- </Form.Item>
-
- <Form.Item
- label={<span className="text-sm font-medium text-gray-700">Target URL</span>}
- name="target"
- rules={[
- { required: true, message: "Target URL is required" },
- { type: "url", message: "Please enter a valid URL" },
- ]}
- extra={<div className="text-xs text-gray-500 mt-1">Example:https://engine.prod.bria-api.com</div>}
- className="mb-4"
- >
- <TextInput
- placeholder="https://engine.prod.bria-api.com"
- value={targetValue}
- onChange={(e) => {
- setTargetValue(e.target.value);
- form.setFieldsValue({ target: e.target.value });
- }}
- />
- </Form.Item>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- HTTP Methods (Optional)
- <Tooltip title="Select specific HTTP methods. Leave empty to support all methods (GET, POST, PUT, DELETE, PATCH). Useful when the same path needs different targets for different methods.">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- name="methods"
- extra={
- <div className="text-xs text-gray-500 mt-1">
- {selectedMethods.length === 0
+ <TooltipProvider>
+ <div>
+ <Button className="mx-auto mb-4 mt-4" onClick={() => setIsModalVisible(true)}>
+ + Add Pass-Through Endpoint
+ </Button>
+ <Modal
+ title={
+ <div className="flex items-center space-x-3 border-b border-border pb-4">
+ <Plug className="size-5 text-blue-500" />
+ <h2 className="text-xl font-semibold text-foreground">Add Pass-Through Endpoint</h2>
+ </div>
+ }
+ open={isModalVisible}
+ width={1000}
+ onCancel={handleCancel}
+ footer={null}
+ className="top-8"
+ styles={{
+ body: { padding: "24px" },
+ header: { padding: "24px 24px 0 24px", border: "none" },
+ }}
+ >
+ <div className="mt-6">
+ <Alert
+ message="What is a Pass-Through Endpoint?"
+ description="Route requests from your LiteLLM proxy to any external API. Perfect for custom models, image generation APIs, or any service you want to proxy through LiteLLM."
+ type="info"
+ showIcon
+ className="mb-6"
+ />
+
+ <form onSubmit={form.handleSubmit(addPassThrough)} className="space-y-6">
+ <Card className="p-5">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Route Configuration</Title>
+ <Subtitle className="mb-5 text-muted-foreground">
+ Configure how requests to your domain will be forwarded to the target API
+ </Subtitle>
+
+ <div className="space-y-5">
+ <FormField
+ control={form.control}
+ name="path"
+ label="Path Prefix"
+ description="Example: /bria, /adobe-photoshop, /elasticsearch"
+ >
+ {({ value, onChange, ...field }) => (
+ <Input
+ {...field}
+ placeholder="bria"
+ value={value ?? ""}
+ onChange={(event) => {
+ const raw = event.target.value;
+ onChange(raw && !raw.startsWith("/") ? "/" + raw : raw);
+ }}
+ />
+ )}
+ </FormField>
+
+ <FormField
+ control={form.control}
+ name="target"
+ label="Target URL"
+ description="Example:https://engine.prod.bria-api.com"
+ >
+ {({ value, ...field }) => (
+ <Input {...field} placeholder="https://engine.prod.bria-api.com" value={value ?? ""} />
+ )}
+ </FormField>
+
+ <FormField
+ control={form.control}
+ name="methods"
+ label={labelWithHint(
+ "HTTP Methods (Optional)",
+ "Select specific HTTP methods. Leave empty to support all methods (GET, POST, PUT, DELETE, PATCH). Useful when the same path needs different targets for different methods.",
+ )}
+ description={
+ selectedMethods.length === 0
? "All HTTP methods supported (default)"
- : `Only ${selectedMethods.join(", ")} requests will be routed to this endpoint`}
- </div>
- }
- className="mb-4"
- >
- <Select2
- mode="multiple"
- placeholder="Select methods (leave empty for all)"
- value={selectedMethods}
- onChange={setSelectedMethods}
- allowClear
- style={{ width: "100%" }}
+ : `Only ${selectedMethods.join(", ")} requests will be routed to this endpoint`
+ }
>
- {HTTP_METHODS.map((method) => (
- <Option key={method} value={method}>
- {method}
- </Option>
- ))}
- </Select2>
- </Form.Item>
-
- <div className="flex items-center justify-between py-3">
- <div>
- <div className="text-sm font-medium text-gray-700">Include Subpaths</div>
- <div className="text-xs text-gray-500 mt-0.5">
- Forward all subpaths to the target API (recommended for REST APIs)
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <Select multiple items={HTTP_METHOD_OPTIONS} value={value ?? []} onValueChange={onChange}>
+ <SelectTrigger {...field} className="w-full">
+ <SelectValue placeholder="Select methods (leave empty for all)">
+ {(selected: string[]) =>
+ selected.length === 0 ? "Select methods (leave empty for all)" : selected.join(", ")
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {HTTP_METHODS.map((method) => (
+ <SelectItem key={method} value={method} title={method}>
+ {method}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </FormField>
+
+ <div className="flex items-center justify-between py-3">
+ <div>
+ <div className="text-sm font-medium text-foreground">Include Subpaths</div>
+ <div className="mt-0.5 text-xs text-muted-foreground">
+ Forward all subpaths to the target API (recommended for REST APIs)
+ </div>
</div>
+ <FormField control={form.control} name="include_subpath">
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <Switch {...field} checked={value} onCheckedChange={onChange} />
+ )}
+ </FormField>
</div>
- <Form.Item name="include_subpath" valuePropName="checked" className="mb-0">
- <Switch checked={includeSubpath} onChange={setIncludeSubpath} />
- </Form.Item>
</div>
- </div>
- </Card>
-
- {/* Route Preview Section */}
- <RoutePreview pathValue={pathValue} targetValue={targetValue} includeSubpath={includeSubpath} />
-
- {/* Headers Section */}
- <Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Headers</Title>
- <Subtitle className="text-gray-600 mb-6">
- Add headers that will be sent with every request to the target API
- </Subtitle>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- Authentication Headers
- <Tooltip title="Authentication and other headers to forward with requests">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- name="headers"
- rules={[{ required: true, message: "Please configure the headers" }]}
- extra={
- <div className="text-xs text-gray-500 mt-2">
- <div className="font-medium mb-1">Add authentication tokens and other required headers</div>
- <div>Common examples: auth_token, Authorization, x-api-key</div>
- </div>
- }
- >
- <KeyValueInput />
- </Form.Item>
- </Card>
-
- {/* Default Query Parameters Section */}
- <Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Default Query Parameters</Title>
- <Subtitle className="text-gray-600 mb-6">
- Add query parameters that will be automatically sent with every request to the target API
- </Subtitle>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- Default Query Parameters (Optional)
- <Tooltip title="Query parameters that will be added to all requests. Clients can override these by providing their own values.">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- name="default_query_params"
- extra={
- <div className="text-xs text-gray-500 mt-2">
- <div className="font-medium mb-1">Parameters are sent with all GET, POST, PUT, PATCH requests</div>
- <div>Client parameters override defaults. Examples: version=v1, format=json, key=default</div>
- </div>
- }
- >
- <QueryParamInput />
- </Form.Item>
- </Card>
-
- {/* Security Section */}
- <PassThroughSecuritySection
- premiumUser={premiumUser}
- authEnabled={authEnabled}
- onAuthChange={(checked) => {
- setAuthEnabled(checked);
- form.setFieldsValue({ auth: checked });
- }}
- />
+ </Card>
- {/* Guardrails Section */}
- <PassThroughGuardrailsSection accessToken={accessToken} value={guardrails} onChange={setGuardrails} />
-
- {/* Performance Section */}
- <Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Performance</Title>
- <Subtitle className="text-gray-600 mb-6">Configure upstream request timeout for this endpoint</Subtitle>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- Request Timeout (seconds)
- <Tooltip title="Max time to wait for the upstream API to respond. Leave empty to use general_settings.pass_through_request_timeout (default 600s).">
- <InfoCircleOutlined className="ml-2 text-gray-400 hover:text-gray-600" />
- </Tooltip>
- </span>
- }
- name="timeout"
- extra={
- <div className="text-xs text-gray-500 mt-2">
- Use a higher value for slow upstream APIs (e.g. 1200 for long-running LLM calls)
- </div>
- }
- >
- <NumericalInput min={1} step={1} precision={0} placeholder="600" size="large" />
- </Form.Item>
- </Card>
-
- {/* Billing Section */}
- <Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Billing</Title>
- <Subtitle className="text-gray-600 mb-6">Optional cost tracking for this endpoint</Subtitle>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- Cost Per Request (USD)
- <Tooltip title="Optional: Track costs for requests to this endpoint">
- <InfoCircleOutlined className="ml-2 text-gray-400 hover:text-gray-600" />
- </Tooltip>
- </span>
- }
- name="cost_per_request"
- extra={
- <div className="text-xs text-gray-500 mt-2">
- The cost charged for each request through this endpoint
- </div>
- }
- >
- <NumericalInput min={0} step={0.001} precision={4} placeholder="2.0000" size="large" />
- </Form.Item>
- </Card>
-
- <div className="flex items-center justify-end space-x-3 pt-6 border-t border-gray-100">
- <Button variant="secondary" onClick={handleCancel}>
- Cancel
- </Button>
- <Button
- variant="primary"
- loading={isLoading}
- onClick={() => {
- form.submit();
- }}
- >
- {isLoading ? "Creating..." : "Add Pass-Through Endpoint"}
- </Button>
- </div>
- </Form>
- </div>
- </Modal>
- </div>
+ <RoutePreview pathValue={pathValue} targetValue={targetValue} includeSubpath={includeSubpath} />
+
+ <Card className="p-6">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Headers</Title>
+ <Subtitle className="mb-6 text-muted-foreground">
+ Add headers that will be sent with every request to the target API
+ </Subtitle>
+
+ <FormField
+ control={form.control}
+ name="headers"
+ label={labelWithHint(
+ "Authentication Headers",
+ "Authentication and other headers to forward with requests",
+ )}
+ description={
+ <>
+ <span className="mb-1 block font-medium">
+ Add authentication tokens and other required headers
+ </span>
+ <span className="block">Common examples: auth_token, Authorization, x-api-key</span>
+ </>
+ }
+ >
+ {({ value, onChange }) => <KeyValueInput value={value} onChange={onChange} />}
+ </FormField>
+ </Card>
+
+ <Card className="p-6">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Default Query Parameters</Title>
+ <Subtitle className="mb-6 text-muted-foreground">
+ Add query parameters that will be automatically sent with every request to the target API
+ </Subtitle>
+
+ <FormField
+ control={form.control}
+ name="default_query_params"
+ label={labelWithHint(
+ "Default Query Parameters (Optional)",
+ "Query parameters that will be added to all requests. Clients can override these by providing their own values.",
+ )}
+ description={
+ <>
+ <span className="mb-1 block font-medium">
+ Parameters are sent with all GET, POST, PUT, PATCH requests
+ </span>
+ <span className="block">
+ Client parameters override defaults. Examples: version=v1, format=json, key=default
+ </span>
+ </>
+ }
+ >
+ {({ value, onChange }) => <QueryParamInput value={value} onChange={onChange} />}
+ </FormField>
+ </Card>
+
+ <FormField control={form.control} name="auth">
+ {({ value, onChange }) => (
+ <PassThroughSecuritySection
+ premiumUser={premiumUser}
+ authEnabled={value ?? false}
+ onAuthChange={onChange}
+ />
+ )}
+ </FormField>
+
+ <PassThroughGuardrailsSection accessToken={accessToken} value={guardrails} onChange={setGuardrails} />
+
+ <Card className="p-6">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Performance</Title>
+ <Subtitle className="mb-6 text-muted-foreground">
+ Configure upstream request timeout for this endpoint
+ </Subtitle>
+
+ <FormField
+ control={form.control}
+ name="timeout"
+ label={labelWithHint(
+ "Request Timeout (seconds)",
+ "Max time to wait for the upstream API to respond. Leave empty to use general_settings.pass_through_request_timeout (default 600s).",
+ )}
+ description="Use a higher value for slow upstream APIs (e.g. 1200 for long-running LLM calls)"
+ >
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <NumericalInput
+ {...field}
+ min={1}
+ step={1}
+ placeholder="600"
+ value={value ?? ""}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
+ onChange(optionalText(event.target.value))
+ }
+ />
+ )}
+ </FormField>
+ </Card>
+
+ <Card className="p-6">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Billing</Title>
+ <Subtitle className="mb-6 text-muted-foreground">Optional cost tracking for this endpoint</Subtitle>
+
+ <FormField
+ control={form.control}
+ name="cost_per_request"
+ label={labelWithHint("Cost Per Request (USD)", "Optional: Track costs for requests to this endpoint")}
+ description="The cost charged for each request through this endpoint"
+ >
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <NumericalInput
+ {...field}
+ min={0}
+ step={0.001}
+ placeholder="2.0000"
+ value={value ?? ""}
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
+ onChange(optionalText(event.target.value))
+ }
+ />
+ )}
+ </FormField>
+ </Card>
+
+ <div className="flex items-center justify-end space-x-3 border-t border-border pt-6">
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isLoading}>
+ {isLoading ? "Creating..." : "Add Pass-Through Endpoint"}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </Modal>
+ </div>
+ </TooltipProvider>
);
};
diff --git a/ui/litellm-dashboard/src/components/common_components/PassThroughGuardrailsSection.tsx b/ui/litellm-dashboard/src/components/common_components/PassThroughGuardrailsSection.tsx
index 733b91b1d3e..21d013624fc 100644
--- a/ui/litellm-dashboard/src/components/common_components/PassThroughGuardrailsSection.tsx
+++ b/ui/litellm-dashboard/src/components/common_components/PassThroughGuardrailsSection.tsx
@@ -1,252 +1,226 @@
-import React, { useState, useEffect } from "react";
+import React from "react";
import { Card, Title, Subtitle } from "@tremor/react";
-import { Form, Select, Tooltip, Alert } from "antd";
-import { InfoCircleOutlined } from "@ant-design/icons";
+import { Alert } from "antd";
+import { CircleHelp } from "lucide-react";
+
import GuardrailSelector from "../guardrails/GuardrailSelector";
+import { TagsInput } from "@/app/(dashboard)/guardrails/_components/content_filter/TagsInput";
+import { Field, FieldLabel } from "@/components/shared/form/field";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+
+type GuardrailFields = { request_fields?: string[]; response_fields?: string[] };
+type GuardrailSettings = Record<string, GuardrailFields | null>;
interface PassThroughGuardrailsSectionProps {
accessToken: string;
- value?: Record<string, { request_fields?: string[]; response_fields?: string[] } | null>;
- onChange?: (guardrails: Record<string, { request_fields?: string[]; response_fields?: string[] } | null>) => void;
+ value?: GuardrailSettings;
+ onChange?: (guardrails: GuardrailSettings) => void;
disabled?: boolean;
}
+const labelWithHint = (label: React.ReactNode, hint: React.ReactNode): React.ReactNode => (
+ <>
+ {label}
+ <Tooltip>
+ <TooltipTrigger render={<CircleHelp className="size-3.5 shrink-0 cursor-help text-muted-foreground" />} />
+ <TooltipContent>{hint}</TooltipContent>
+ </Tooltip>
+ </>
+);
+
const PassThroughGuardrailsSection: React.FC<PassThroughGuardrailsSectionProps> = ({
accessToken,
value = {},
onChange,
disabled = false,
}) => {
- const [selectedGuardrails, setSelectedGuardrails] = useState<string[]>(Object.keys(value));
- const [guardrailSettings, setGuardrailSettings] =
- useState<Record<string, { request_fields?: string[]; response_fields?: string[] } | null>>(value);
+ const selectedGuardrails = Object.keys(value);
- // Sync external value changes
- useEffect(() => {
- setGuardrailSettings(value);
- setSelectedGuardrails(Object.keys(value));
- }, [value]);
+ const emit = (next: GuardrailSettings) => {
+ onChange?.(next);
+ };
const handleGuardrailChange = (guardrails: string[]) => {
- setSelectedGuardrails(guardrails);
-
- // Create new settings object with selected guardrails
- const newSettings: Record<string, { request_fields?: string[]; response_fields?: string[] } | null> = {};
- guardrails.forEach((name) => {
- // Preserve existing settings or set to null (uses entire payload)
- newSettings[name] = guardrailSettings[name] || null;
- });
-
- setGuardrailSettings(newSettings);
- if (onChange) {
- onChange(newSettings);
- }
+ emit(Object.fromEntries(guardrails.map((name) => [name, value[name] ?? null])));
};
- const handleFieldChange = (
- guardrailName: string,
- fieldType: "request_fields" | "response_fields",
- fields: string[],
- ) => {
- const currentSettings = guardrailSettings[guardrailName] || {};
- const newSettings = {
- ...guardrailSettings,
- [guardrailName]: {
- ...currentSettings,
- [fieldType]: fields.length > 0 ? fields : undefined,
- },
+ const handleFieldChange = (guardrailName: string, fieldType: keyof GuardrailFields, fields: string[]) => {
+ const updated: GuardrailFields = {
+ ...(value[guardrailName] ?? {}),
+ [fieldType]: fields.length > 0 ? fields : undefined,
};
+ const isEmpty = !updated.request_fields && !updated.response_fields;
+ emit({ ...value, [guardrailName]: isEmpty ? null : updated });
+ };
- // If no fields are set, set to null (entire payload)
- if (!newSettings[guardrailName]?.request_fields && !newSettings[guardrailName]?.response_fields) {
- newSettings[guardrailName] = null;
- }
-
- setGuardrailSettings(newSettings);
- if (onChange) {
- onChange(newSettings);
- }
+ const appendField = (guardrailName: string, fieldType: keyof GuardrailFields, field: string) => {
+ handleFieldChange(guardrailName, fieldType, [...(value[guardrailName]?.[fieldType] ?? []), field]);
};
return (
- <Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Guardrails</Title>
- <Subtitle className="text-gray-600 mb-6">
- Configure guardrails to enforce policies on requests and responses. Guardrails are opt-in for passthrough
- endpoints.
- </Subtitle>
+ <TooltipProvider>
+ <Card className="p-6">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Guardrails</Title>
+ <Subtitle className="mb-6 text-muted-foreground">
+ Configure guardrails to enforce policies on requests and responses. Guardrails are opt-in for passthrough
+ endpoints.
+ </Subtitle>
- <Alert
- message={
- <span>
- Field-Level Targeting{" "}
- <a
- href="https://docs.litellm.ai/docs/proxy/pass_through_guardrails#field-level-targeting"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-600 hover:text-blue-800 underline"
- >
- (Learn More)
- </a>
- </span>
- }
- description={
- <div className="space-y-2">
- <div>
- Optionally specify which fields to check. If left empty, the entire request/response is sent to the
- guardrail.
- </div>
- <div className="text-xs space-y-1 mt-2">
- <div className="font-medium">Common Examples:</div>
+ <Alert
+ message={
+ <span>
+ Field-Level Targeting{" "}
+ <a
+ href="https://docs.litellm.ai/docs/proxy/pass_through_guardrails#field-level-targeting"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-600 underline hover:text-blue-800"
+ >
+ (Learn More)
+ </a>
+ </span>
+ }
+ description={
+ <div className="space-y-2">
<div>
- • <code className="bg-gray-100 px-1 rounded-sm">query</code> - Single field
+ Optionally specify which fields to check. If left empty, the entire request/response is sent to the
+ guardrail.
</div>
- <div>
- • <code className="bg-gray-100 px-1 rounded-sm">documents[*].text</code> - All text in documents array
- </div>
- <div>
- • <code className="bg-gray-100 px-1 rounded-sm">messages[*].content</code> - All message contents
+ <div className="mt-2 space-y-1 text-xs">
+ <div className="font-medium">Common Examples:</div>
+ <div>
+ • <code className="rounded-sm bg-muted px-1">query</code> - Single field
+ </div>
+ <div>
+ • <code className="rounded-sm bg-muted px-1">documents[*].text</code> - All text in documents array
+ </div>
+ <div>
+ • <code className="rounded-sm bg-muted px-1">messages[*].content</code> - All message contents
+ </div>
</div>
</div>
- </div>
- }
- type="info"
- showIcon
- className="mb-4"
- />
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- Select Guardrails
- <Tooltip title="Choose which guardrails should run on this endpoint. Org/team/key level guardrails will also be included.">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- >
- <GuardrailSelector
- accessToken={accessToken}
- value={selectedGuardrails}
- onChange={handleGuardrailChange}
- disabled={disabled}
+ }
+ type="info"
+ showIcon
+ className="mb-4"
/>
- </Form.Item>
- {selectedGuardrails.length > 0 && (
- <div className="mt-6 space-y-4">
- <div className="flex items-center justify-between mb-3">
- <div className="text-sm font-medium text-gray-700">Field Targeting (Optional)</div>
- <div className="text-xs text-gray-500">💡 Tip: Leave empty to check entire payload</div>
- </div>
- {selectedGuardrails.map((guardrailName) => (
- <Card key={guardrailName} className="p-4 bg-gray-50">
- <div className="text-sm font-medium text-gray-900 mb-3">{guardrailName}</div>
- <div className="space-y-3">
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="text-xs text-gray-600 flex items-center">
- Request Fields (pre_call)
- <Tooltip
- title={
+ <Field>
+ <FieldLabel htmlFor="pass-through-guardrails">
+ {labelWithHint(
+ "Select Guardrails",
+ "Choose which guardrails should run on this endpoint. Org/team/key level guardrails will also be included.",
+ )}
+ </FieldLabel>
+ <GuardrailSelector
+ accessToken={accessToken}
+ value={selectedGuardrails}
+ onChange={handleGuardrailChange}
+ disabled={disabled}
+ />
+ </Field>
+
+ {selectedGuardrails.length > 0 && (
+ <div className="mt-6 space-y-4">
+ <div className="mb-3 flex items-center justify-between">
+ <div className="text-sm font-medium text-foreground">Field Targeting (Optional)</div>
+ <div className="text-xs text-muted-foreground">💡 Tip: Leave empty to check entire payload</div>
+ </div>
+ {selectedGuardrails.map((guardrailName) => (
+ <Card key={guardrailName} className="bg-muted/50 p-4">
+ <div className="mb-3 text-sm font-medium text-foreground">{guardrailName}</div>
+ <div className="space-y-3">
+ <Field>
+ <div className="flex items-center justify-between">
+ <FieldLabel htmlFor={`${guardrailName}-request-fields`} className="text-xs text-muted-foreground">
+ {labelWithHint(
+ "Request Fields (pre_call)",
<div>
- <div className="font-medium mb-1">Specify which request fields to check</div>
- <div className="text-xs space-y-1">
+ <div className="mb-1 font-medium">Specify which request fields to check</div>
+ <div className="space-y-1 text-xs">
<div>Examples:</div>
<div>• query</div>
<div>• documents[*].text</div>
<div>• messages[*].content</div>
</div>
- </div>
- }
- >
- <InfoCircleOutlined className="ml-1 text-gray-400" />
- </Tooltip>
- </label>
- <div className="flex gap-1">
- <button
- type="button"
- onClick={() => {
- const current = guardrailSettings[guardrailName]?.request_fields || [];
- handleFieldChange(guardrailName, "request_fields", [...current, "query"]);
- }}
- className="text-xs px-2 py-1 bg-white border border-gray-300 rounded-sm hover:bg-gray-50"
- disabled={disabled}
- >
- + query
- </button>
- <button
- type="button"
- onClick={() => {
- const current = guardrailSettings[guardrailName]?.request_fields || [];
- handleFieldChange(guardrailName, "request_fields", [...current, "documents[*]"]);
- }}
- className="text-xs px-2 py-1 bg-white border border-gray-300 rounded-sm hover:bg-gray-50"
- disabled={disabled}
- >
- + documents[*]
- </button>
+ </div>,
+ )}
+ </FieldLabel>
+ <div className="flex gap-1">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => appendField(guardrailName, "request_fields", "query")}
+ >
+ + query
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => appendField(guardrailName, "request_fields", "documents[*]")}
+ >
+ + documents[*]
+ </Button>
+ </div>
</div>
- </div>
- <Select
- mode="tags"
- style={{ width: "100%" }}
- placeholder="Type field name or use + buttons above (e.g., query, documents[*].text)"
- value={guardrailSettings[guardrailName]?.request_fields || []}
- onChange={(fields) => handleFieldChange(guardrailName, "request_fields", fields)}
- disabled={disabled}
- tokenSeparators={[","]}
- />
- </div>
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="text-xs text-gray-600 flex items-center">
- Response Fields (post_call)
- <Tooltip
- title={
+ <TagsInput
+ id={`${guardrailName}-request-fields`}
+ placeholder="Type field name or use + buttons above (e.g., query, documents[*].text)"
+ value={value[guardrailName]?.request_fields ?? []}
+ onValueChange={(fields) => handleFieldChange(guardrailName, "request_fields", fields)}
+ tokenSeparators={[","]}
+ />
+ </Field>
+ <Field>
+ <div className="flex items-center justify-between">
+ <FieldLabel
+ htmlFor={`${guardrailName}-response-fields`}
+ className="text-xs text-muted-foreground"
+ >
+ {labelWithHint(
+ "Response Fields (post_call)",
<div>
- <div className="font-medium mb-1">Specify which response fields to check</div>
- <div className="text-xs space-y-1">
+ <div className="mb-1 font-medium">Specify which response fields to check</div>
+ <div className="space-y-1 text-xs">
<div>Examples:</div>
<div>• results[*].text</div>
<div>• choices[*].message.content</div>
</div>
- </div>
- }
- >
- <InfoCircleOutlined className="ml-1 text-gray-400" />
- </Tooltip>
- </label>
- <div className="flex gap-1">
- <button
- type="button"
- onClick={() => {
- const current = guardrailSettings[guardrailName]?.response_fields || [];
- handleFieldChange(guardrailName, "response_fields", [...current, "results[*]"]);
- }}
- className="text-xs px-2 py-1 bg-white border border-gray-300 rounded-sm hover:bg-gray-50"
- disabled={disabled}
- >
- + results[*]
- </button>
+ </div>,
+ )}
+ </FieldLabel>
+ <div className="flex gap-1">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => appendField(guardrailName, "response_fields", "results[*]")}
+ >
+ + results[*]
+ </Button>
+ </div>
</div>
- </div>
- <Select
- mode="tags"
- style={{ width: "100%" }}
- placeholder="Type field name or use + buttons above (e.g., results[*].text)"
- value={guardrailSettings[guardrailName]?.response_fields || []}
- onChange={(fields) => handleFieldChange(guardrailName, "response_fields", fields)}
- disabled={disabled}
- tokenSeparators={[","]}
- />
+ <TagsInput
+ id={`${guardrailName}-response-fields`}
+ placeholder="Type field name or use + buttons above (e.g., results[*].text)"
+ value={value[guardrailName]?.response_fields ?? []}
+ onValueChange={(fields) => handleFieldChange(guardrailName, "response_fields", fields)}
+ tokenSeparators={[","]}
+ />
+ </Field>
</div>
- </div>
- </Card>
- ))}
- </div>
- )}
- </Card>
+ </Card>
+ ))}
+ </div>
+ )}
+ </Card>
+ </TooltipProvider>
);
};
diff --git a/ui/litellm-dashboard/src/components/common_components/PassThroughSecuritySection.tsx b/ui/litellm-dashboard/src/components/common_components/PassThroughSecuritySection.tsx
index c63770d3c85..226b5c7e284 100644
--- a/ui/litellm-dashboard/src/components/common_components/PassThroughSecuritySection.tsx
+++ b/ui/litellm-dashboard/src/components/common_components/PassThroughSecuritySection.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { Card, Title, Subtitle, Text } from "@tremor/react";
-import { Form, Switch } from "antd";
+
+import { Switch } from "@/components/ui/switch";
export interface PassThroughSecuritySectionProps {
premiumUser: boolean;
@@ -8,10 +9,6 @@ export interface PassThroughSecuritySectionProps {
onAuthChange: (checked: boolean) => void;
}
-/**
- * Reusable Security section for pass-through endpoints
- * Shows authentication toggle for premium users or upgrade message for free users
- */
const PassThroughSecuritySection: React.FC<PassThroughSecuritySectionProps> = ({
premiumUser,
authEnabled,
@@ -19,27 +16,20 @@ const PassThroughSecuritySection: React.FC<PassThroughSecuritySectionProps> = ({
}) => {
return (
<Card className="p-6">
- <Title className="text-lg font-semibold text-gray-900 mb-2">Security</Title>
- <Subtitle className="text-gray-600 mb-4">
+ <Title className="mb-2 text-lg font-semibold text-foreground">Security</Title>
+ <Subtitle className="mb-4 text-muted-foreground">
When enabled, requests to this endpoint will require a valid LiteLLM Virtual Key
</Subtitle>
{premiumUser ? (
- <Form.Item name="auth" valuePropName="checked" className="mb-0">
- <Switch
- checked={authEnabled}
- onChange={(checked) => {
- onAuthChange(checked);
- }}
- />
- </Form.Item>
+ <Switch checked={authEnabled} onCheckedChange={onAuthChange} />
) : (
<div>
- <div className="flex items-center mb-3">
- <Switch disabled checked={false} style={{ outline: "2px solid #d1d5db", outlineOffset: "2px" }} />
- <span className="ml-2 text-sm text-gray-400">Authentication (Premium)</span>
+ <div className="mb-3 flex items-center">
+ <Switch disabled checked={false} />
+ <span className="ml-2 text-sm text-muted-foreground">Authentication (Premium)</span>
</div>
- <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
- <Text className="text-sm text-yellow-800">
+ <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-3 dark:border-yellow-900 dark:bg-yellow-950">
+ <Text className="text-sm text-yellow-800 dark:text-yellow-300">
Setting authentication for pass-through endpoints is a LiteLLM Enterprise feature. Get a trial key{" "}
<a href="https://www.litellm.ai/#pricing" target="_blank" rel="noopener noreferrer" className="underline">
here
diff --git a/ui/litellm-dashboard/src/components/pass_through_info.integration.test.tsx b/ui/litellm-dashboard/src/components/pass_through_info.integration.test.tsx
new file mode 100644
index 00000000000..90994a8a2cd
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/pass_through_info.integration.test.tsx
@@ -0,0 +1,182 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
+import { renderWithProviders, screen, waitFor } from "../../tests/test-utils";
+import PassThroughInfoView from "./pass_through_info";
+
+const updatePassThroughEndpoint = vi.fn();
+
+vi.mock("./networking", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./networking")>()),
+ updatePassThroughEndpoint: (...args: unknown[]) => updatePassThroughEndpoint(...args),
+ deletePassThroughEndpointsCall: vi.fn().mockResolvedValue({}),
+ getGuardrailsList: vi.fn().mockResolvedValue({ guardrails: [] }),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
+}));
+
+const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
+type User = ReturnType<typeof setup>;
+
+const endpoint = {
+ id: "ep-1",
+ path: "/bria",
+ target: "https://engine.prod.bria-api.com",
+ headers: { Authorization: "Bearer abc" },
+ include_subpath: true,
+ cost_per_request: 2,
+ timeout: 600,
+ auth: false,
+ methods: ["GET"],
+};
+
+const renderView = (premiumUser = true, data = endpoint) =>
+ renderWithProviders(
+ <PassThroughInfoView
+ endpointData={data}
+ onClose={vi.fn()}
+ accessToken="test-token"
+ isAdmin
+ premiumUser={premiumUser}
+ />,
+ );
+
+const openEditForm = async (user: User) => {
+ await user.click(screen.getByRole("tab", { name: "Settings" }));
+ await user.click(await screen.findByRole("button", { name: "Edit Settings" }));
+ await screen.findByLabelText("Target URL");
+};
+
+const save = async (user: User) => user.click(screen.getByRole("button", { name: "Save Changes" }));
+
+const lastPayload = () => updatePassThroughEndpoint.mock.calls.at(-1)?.[2] as Record<string, unknown>;
+
+describe("pass_through_info update payload", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updatePassThroughEndpoint.mockResolvedValue({});
+ });
+
+ it("sends exactly the antd payload, once, for an untouched save", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+
+ expect(updatePassThroughEndpoint).toHaveBeenCalledTimes(1);
+ expect(updatePassThroughEndpoint.mock.calls[0][0]).toBe("test-token");
+ expect(updatePassThroughEndpoint.mock.calls[0][1]).toBe("ep-1");
+ expect(lastPayload()).toStrictEqual({
+ path: "/bria",
+ target: "https://engine.prod.bria-api.com",
+ headers: { Authorization: "Bearer abc" },
+ include_subpath: true,
+ cost_per_request: 2,
+ timeout: 600,
+ auth: false,
+ methods: ["GET"],
+ guardrails: undefined,
+ });
+ });
+
+ it("submits numeric fields as numbers, not strings", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().cost_per_request).toBe(2);
+ expect(lastPayload().timeout).toBe(600);
+ });
+
+ it("keeps the path from the loaded endpoint rather than the form", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await user.clear(screen.getByLabelText("Target URL"));
+ await user.type(screen.getByLabelText("Target URL"), "https://new.example.com");
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().path).toBe("/bria");
+ expect(lastPayload().target).toBe("https://new.example.com");
+ });
+
+ it("parses the headers textarea from JSON into an object", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await user.clear(screen.getByLabelText("Headers (JSON)"));
+ await user.type(screen.getByLabelText("Headers (JSON)"), '{{"x-api-key": "k"}');
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().headers).toStrictEqual({ "x-api-key": "k" });
+ });
+
+ it("sends auth undefined for a non-premium user", async () => {
+ const user = setup();
+ renderView(false);
+ await openEditForm(user);
+
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().auth).toBeUndefined();
+ });
+
+ it("sends methods undefined when the endpoint has none", async () => {
+ const user = setup();
+ renderView(true, { ...endpoint, methods: [] });
+ await openEditForm(user);
+
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().methods).toBeUndefined();
+ });
+
+ it("rounds cost_per_request to two decimals", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await user.clear(screen.getByLabelText("Cost per Request"));
+ await user.type(screen.getByLabelText("Cost per Request"), "1.239");
+ await save(user);
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(lastPayload().cost_per_request).toBe(1.24);
+ });
+
+ it("does not send when the target is cleared", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await user.clear(screen.getByLabelText("Target URL"));
+ await save(user);
+
+ expect(await screen.findByText("Please input a target URL")).toBeInTheDocument();
+ expect(updatePassThroughEndpoint).not.toHaveBeenCalled();
+ });
+
+ it("submits when Enter is pressed in the target field", async () => {
+ const user = setup();
+ renderView();
+ await openEditForm(user);
+
+ await user.type(screen.getByLabelText("Target URL"), "{Enter}");
+
+ await waitFor(() => expect(updatePassThroughEndpoint).toHaveBeenCalled());
+ expect(updatePassThroughEndpoint).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/pass_through_info.tsx b/ui/litellm-dashboard/src/components/pass_through_info.tsx
index c6c12effecb..a4114f4d8d5 100644
--- a/ui/litellm-dashboard/src/components/pass_through_info.tsx
+++ b/ui/litellm-dashboard/src/components/pass_through_info.tsx
@@ -11,18 +11,90 @@ import {
TabList,
TabPanel,
TabPanels,
- TextInput,
} from "@tremor/react";
-import { Button, Form, Input, Switch, InputNumber, Select } from "antd";
import { updatePassThroughEndpoint, deletePassThroughEndpointsCall } from "./networking";
import { Eye, EyeOff } from "lucide-react";
+import { useWatch } from "react-hook-form";
+import { z } from "zod/v4";
import RoutePreview from "./route_preview";
import { toast } from "@/lib/toast";
import PassThroughSecuritySection from "./common_components/PassThroughSecuritySection";
import PassThroughGuardrailsSection from "./common_components/PassThroughGuardrailsSection";
+import { FormField } from "@/components/shared/form/FormField";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from "@/components/ui/input-group";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { useZodForm } from "@/lib/forms/useZodForm";
+
+const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
+const HTTP_METHOD_OPTIONS = HTTP_METHODS.map((method) => ({ label: method, value: method }));
+
+const endpointSettingsSchema = z.object({
+ target: z.string().min(1, "Please input a target URL"),
+ headers: z.string(),
+ methods: z.array(z.string()),
+ include_subpath: z.boolean(),
+ cost_per_request: z.number().optional(),
+ timeout: z.number().optional(),
+ auth: z.boolean(),
+});
+
+type EndpointSettingsValues = z.output<typeof endpointSettingsSchema>;
+
+const roundToPrecision = (raw: string, precision: number): number | undefined => {
+ if (raw.trim() === "") return undefined;
+ const parsed = Number(raw);
+ if (Number.isNaN(parsed)) return undefined;
+ const factor = 10 ** precision;
+ return Math.round(parsed * factor) / factor;
+};
+
+interface PrecisionNumberInputProps extends Omit<React.ComponentPropsWithoutRef<"input">, "value" | "onChange"> {
+ value: number | undefined;
+ precision: number;
+ onValueChange: (value: number | undefined) => void;
+ prefix?: string;
+}
+
+const PrecisionNumberInput = ({
+ value,
+ precision,
+ onValueChange,
+ onBlur,
+ prefix,
+ ...rest
+}: PrecisionNumberInputProps) => {
+ const [draft, setDraft] = useState(value === undefined ? "" : String(value));
+
+ const inputProps = {
+ ...rest,
+ type: "number" as const,
+ value: draft,
+ onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
+ setDraft(event.target.value);
+ onValueChange(roundToPrecision(event.target.value, precision));
+ },
+ onBlur: (event: React.FocusEvent<HTMLInputElement>) => {
+ const rounded = roundToPrecision(draft, precision);
+ setDraft(rounded === undefined ? "" : String(rounded));
+ onBlur?.(event);
+ },
+ };
-const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"];
-const { Option } = Select;
+ if (prefix === undefined) return <Input {...inputProps} />;
+
+ return (
+ <InputGroup>
+ <InputGroupAddon>
+ <InputGroupText>{prefix}</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput {...inputProps} />
+ </InputGroup>
+ );
+};
export interface PassThroughInfoProps {
endpointData: PassThroughEndpoint;
@@ -74,26 +146,41 @@ const PassThroughInfoView: React.FC<PassThroughInfoProps> = ({
const [endpointData, setEndpointData] = useState<PassThroughEndpoint | null>(initialEndpointData);
const [loading] = useState(false);
const [isEditing, setIsEditing] = useState(false);
- const [authEnabled, setAuthEnabled] = useState(initialEndpointData?.auth || false);
- const [selectedMethods, setSelectedMethods] = useState<string[]>(initialEndpointData?.methods || []);
const [guardrails, setGuardrails] = useState<
Record<string, { request_fields?: string[]; response_fields?: string[] } | null>
>(initialEndpointData?.guardrails || {});
- const [form] = Form.useForm();
- const handleEndpointUpdate = async (values: any) => {
+ const form = useZodForm(endpointSettingsSchema, {
+ defaultValues: {
+ target: initialEndpointData.target,
+ headers: initialEndpointData.headers ? JSON.stringify(initialEndpointData.headers, null, 2) : "",
+ methods: initialEndpointData.methods || [],
+ include_subpath: initialEndpointData.include_subpath || false,
+ cost_per_request: initialEndpointData.cost_per_request,
+ timeout: initialEndpointData.timeout,
+ auth: initialEndpointData.auth || false,
+ },
+ });
+
+ const selectedMethods = useWatch({ control: form.control, name: "methods" });
+
+ const parseHeaders = (raw: string): Record<string, unknown> | null => {
+ if (!raw) return {};
+ try {
+ return JSON.parse(raw) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+ };
+
+ const handleEndpointUpdate = async (values: EndpointSettingsValues) => {
try {
if (!accessToken || !endpointData?.id) return;
- // Parse headers if provided as string
- let headers = {};
- if (values.headers) {
- try {
- headers = typeof values.headers === "string" ? JSON.parse(values.headers) : values.headers;
- } catch (e) {
- toast.fromError("Invalid JSON format for headers");
- return;
- }
+ const headers = parseHeaders(values.headers);
+ if (headers === null) {
+ toast.fromError("Invalid JSON format for headers");
+ return;
}
const updateData = {
@@ -104,13 +191,12 @@ const PassThroughInfoView: React.FC<PassThroughInfoProps> = ({
cost_per_request: values.cost_per_request,
timeout: values.timeout,
auth: premiumUser ? values.auth : undefined,
- methods: selectedMethods && selectedMethods.length > 0 ? selectedMethods : undefined,
+ methods: values.methods.length > 0 ? values.methods : undefined,
guardrails: guardrails && Object.keys(guardrails).length > 0 ? guardrails : undefined,
};
await updatePassThroughEndpoint(accessToken, endpointData.id, updateData);
- // Update local state with the new values
setEndpointData({
...endpointData,
...updateData,
@@ -291,84 +377,103 @@ const PassThroughInfoView: React.FC<PassThroughInfoProps> = ({
</div>
{isEditing ? (
- <Form
- form={form}
- onFinish={handleEndpointUpdate}
- initialValues={{
- target: endpointData.target,
- headers: endpointData.headers ? JSON.stringify(endpointData.headers, null, 2) : "",
- include_subpath: endpointData.include_subpath || false,
- cost_per_request: endpointData.cost_per_request,
- timeout: endpointData.timeout,
- auth: endpointData.auth || false,
- methods: endpointData.methods || [],
- }}
- layout="vertical"
- >
- <Form.Item
- label="Target URL"
- name="target"
- rules={[{ required: true, message: "Please input a target URL" }]}
- >
- <TextInput placeholder="https://api.example.com" />
- </Form.Item>
-
- <Form.Item label="Headers (JSON)" name="headers">
- <Input.TextArea
- rows={5}
- placeholder='{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'
- />
- </Form.Item>
+ <form onSubmit={form.handleSubmit(handleEndpointUpdate)}>
+ <FormField control={form.control} name="target" label="Target URL">
+ {({ value, ...field }) => (
+ <Input {...field} placeholder="https://api.example.com" value={value ?? ""} />
+ )}
+ </FormField>
+
+ <FormField control={form.control} name="headers" label="Headers (JSON)">
+ {({ value, ...field }) => (
+ <Textarea
+ {...field}
+ rows={5}
+ value={value ?? ""}
+ placeholder='{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'
+ />
+ )}
+ </FormField>
- <Form.Item
- label="HTTP Methods (Optional)"
+ <FormField
+ control={form.control}
name="methods"
- extra={
+ label="HTTP Methods (Optional)"
+ description={
selectedMethods.length === 0
? "All HTTP methods supported (default)"
: `Only ${selectedMethods.join(", ")} requests will be routed to this endpoint`
}
>
- <Select
- mode="multiple"
- placeholder="Select methods (leave empty for all)"
- value={selectedMethods}
- onChange={setSelectedMethods}
- allowClear
- style={{ width: "100%" }}
- >
- {HTTP_METHODS.map((method) => (
- <Option key={method} value={method}>
- {method}
- </Option>
- ))}
- </Select>
- </Form.Item>
-
- <Form.Item label="Include Subpath" name="include_subpath" valuePropName="checked">
- <Switch />
- </Form.Item>
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <Select multiple items={HTTP_METHOD_OPTIONS} value={value} onValueChange={onChange}>
+ <SelectTrigger {...field} className="w-full">
+ <SelectValue placeholder="Select methods (leave empty for all)">
+ {(selected: string[]) =>
+ selected.length === 0 ? "Select methods (leave empty for all)" : selected.join(", ")
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {HTTP_METHODS.map((method) => (
+ <SelectItem key={method} value={method} title={method}>
+ {method}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </FormField>
- <Form.Item label="Cost per Request" name="cost_per_request">
- <InputNumber min={0} step={0.01} precision={2} placeholder="0.00" addonBefore="$" />
- </Form.Item>
+ <FormField control={form.control} name="include_subpath" label="Include Subpath">
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <Switch {...field} checked={value} onCheckedChange={onChange} />
+ )}
+ </FormField>
+
+ <FormField control={form.control} name="cost_per_request" label="Cost per Request">
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <PrecisionNumberInput
+ {...field}
+ min={0}
+ step={0.01}
+ precision={2}
+ placeholder="0.00"
+ prefix="$"
+ value={value}
+ onValueChange={onChange}
+ />
+ )}
+ </FormField>
- <Form.Item
- label="Request Timeout (seconds)"
+ <FormField
+ control={form.control}
name="timeout"
- extra="Max time to wait for upstream response. Leave empty to use the global pass_through_request_timeout (default 600s)."
+ label="Request Timeout (seconds)"
+ description="Max time to wait for upstream response. Leave empty to use the global pass_through_request_timeout (default 600s)."
>
- <InputNumber min={1} step={1} precision={0} placeholder="600" style={{ width: "100%" }} />
- </Form.Item>
-
- <PassThroughSecuritySection
- premiumUser={premiumUser}
- authEnabled={authEnabled}
- onAuthChange={(checked) => {
- setAuthEnabled(checked);
- form.setFieldsValue({ auth: checked });
- }}
- />
+ {({ value, onChange, ref: _ref, ...field }) => (
+ <PrecisionNumberInput
+ {...field}
+ min={1}
+ step={1}
+ precision={0}
+ placeholder="600"
+ value={value}
+ onValueChange={onChange}
+ />
+ )}
+ </FormField>
+
+ <FormField control={form.control} name="auth">
+ {({ value, onChange }) => (
+ <PassThroughSecuritySection
+ premiumUser={premiumUser}
+ authEnabled={value}
+ onAuthChange={onChange}
+ />
+ )}
+ </FormField>
<div className="mt-4">
<PassThroughGuardrailsSection
@@ -378,11 +483,13 @@ const PassThroughInfoView: React.FC<PassThroughInfoProps> = ({
/>
</div>
- <div className="flex justify-end gap-2 mt-6">
- <Button onClick={() => setIsEditing(false)}>Cancel</Button>
- <TremorButton>Save Changes</TremorButton>
+ <div className="mt-6 flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={() => setIsEditing(false)}>
+ Cancel
+ </Button>
+ <Button type="submit">Save Changes</Button>
</div>
- </Form>
+ </form>
) : (
<div className="space-y-4">
<div>