The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(ui): migrate the teams form graph off antd Form onto react-hook-form (#37417)
yuneng-jiangb9a267c69378
diff --git a/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx b/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsxindex d3ede5f4318..c3936cc456d 100644--- a/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx+++ b/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx@@ -40,6 +40,7 @@ export const MODEL_SENTINEL_OPTIONS = [const MAX_VISIBLE_MODEL_CHIPS = 5;export interface ModelSelectProps {+ id?: string;teamID?: string;organizationID?: string;options?: {@@ -122,7 +123,7 @@ const filterModels = (export const ModelSelect = (props: ModelSelectProps) => {const anchor = useComboboxAnchor();- const { teamID, organizationID, options, context, dataTestId, value = [], onChange, style } = props;+ const { id, teamID, organizationID, options, context, dataTestId, value = [], onChange, style } = props;const { showAllProxyModelsOverride, includeSpecialOptions } = options || {};const { data: allProxyModels, isLoading: isLoadingAllProxyModels } = useAllProxyModels();const { data: team, isLoading: isLoadingTeam } = useTeam(teamID);@@ -256,7 +257,7 @@ export const ModelSelect = (props: ModelSelectProps) => {</>)}</ComboboxValue>- <ComboboxChipsInput placeholder="Select Models" aria-label="Select Models" className="min-w-24" />+ <ComboboxChipsInput id={id} placeholder="Select Models" aria-label="Select Models" className="min-w-24" /></ComboboxChips><ComboboxContent anchor={anchor}><ComboboxEmpty>No models found</ComboboxEmpty>diff --git a/ui/litellm-dashboard/src/components/Teams.test.tsx b/ui/litellm-dashboard/src/components/Teams.test.tsxindex 0ef4357e73f..d0d41837dce 100644--- a/ui/litellm-dashboard/src/components/Teams.test.tsx+++ b/ui/litellm-dashboard/src/components/Teams.test.tsx@@ -1223,3 +1223,261 @@ describe("Teams - which fields reach the create payload depends on the open sectexpect(payload.team_id).toBe("tid-kept");});});++describe("Teams - the exact bytes the create call sends", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ can.mockReturnValue(true);+ vi.mocked(fetchAvailableModelsForTeamOrKey).mockResolvedValue(["gpt-4"]);+ vi.mocked(fetchMCPAccessGroups).mockResolvedValue([]);+ vi.mocked(getGuardrailsList).mockResolvedValue({ guardrails: [] });+ vi.mocked(getPoliciesList).mockResolvedValue({ policies: [] });+ vi.mocked(getDefaultTeamSettings).mockResolvedValue({ values: {} });+ vi.mocked(teamCreateCall).mockResolvedValue({ team_id: "new-team-1" });+ vi.mocked(useTeamMetadataSchema).mockReturnValue({ data: [], isLoading: false } as any);+ mockUseOrganizations.mockReturnValue({ data: null });+ });++ const openCreateModal = async (options?: { premiumUser?: boolean }) => {+ renderWithQueryClient(+ <Teams accessToken="test-token" userID="user-123" userRole="Admin" premiumUser={options?.premiumUser ?? false} />,+ );+ act(() => {+ fireEvent.click(screen.getAllByRole("button", { name: /create team/i })[0]);+ });+ await waitFor(() => {+ expect(screen.getByLabelText(/team name/i)).toBeInTheDocument();+ });+ fireEvent.change(screen.getByLabelText(/team name/i), { target: { value: "Byte Contract Team" } });+ };++ const submit = async () => {+ const buttons = screen.getAllByRole("button", { name: /create team/i });+ fireEvent.click(buttons[buttons.length - 1]);+ await waitFor(() => {+ expect(teamCreateCall).toHaveBeenCalled();+ });+ return vi.mocked(teamCreateCall).mock.calls[0][1] as Record<string, unknown>;+ };++ const wireBody = (payload: Record<string, unknown>) => JSON.parse(JSON.stringify(payload)) as Record<string, unknown>;++ const openSection = async (title: string, mountedProbe: RegExp | string) => {+ fireEvent.click(screen.getByText(title));+ await waitFor(() => {+ expect(screen.getAllByText(mountedProbe).length).toBeGreaterThan(0);+ });+ };++ it("sends three keys and nothing else when every section is left closed", async () => {+ await openCreateModal();++ const payload = await submit();++ expect(payload).toStrictEqual({+ team_alias: "Byte Contract Team",+ organization_id: null,+ models: ["no-default-models"],+ max_budget: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ rpm_limit: undefined,+ metadata: undefined,+ });+ expect(wireBody(payload)).toStrictEqual({+ team_alias: "Byte Contract Team",+ organization_id: null,+ models: ["no-default-models"],+ });+ });++ it("keeps every newly mounted but untouched field out of the request body", async () => {+ await openCreateModal();++ await openSection("Additional Settings", /Team Member Key Duration/);+ await openSection("MCP Settings", /Allowed MCP Servers/);+ await openSection("Agent Settings", /Allowed Agents/);+ await openSection("Search Tool Settings", /Allowed Search Tools/);++ const payload = await submit();++ expect(payload).toStrictEqual({+ team_alias: "Byte Contract Team",+ organization_id: null,+ models: ["no-default-models"],+ max_budget: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ rpm_limit: undefined,+ metadata: undefined,+ team_id: undefined,+ team_member_budget: undefined,+ team_member_key_duration: undefined,+ team_member_rpm_limit: undefined,+ team_member_tpm_limit: undefined,+ secret_manager_settings: undefined,+ guardrails: undefined,+ disable_global_guardrails: undefined,+ policies: undefined,+ access_group_ids: undefined,+ allowed_vector_store_ids: undefined,+ allowed_passthrough_routes: undefined,+ allowed_mcp_servers_and_groups: undefined,+ mcp_tool_permissions: {},+ allowed_agents_and_groups: undefined,+ object_permission_search_tools: undefined,+ });+ expect(wireBody(payload)).toStrictEqual({+ team_alias: "Byte Contract Team",+ organization_id: null,+ models: ["no-default-models"],+ mcp_tool_permissions: {},+ });+ });++ it.each([+ ["MCP Settings", /Allowed MCP Servers/, ["allowed_mcp_servers_and_groups", "mcp_tool_permissions"]],+ ["Agent Settings", /Allowed Agents/, ["allowed_agents_and_groups"]],+ ["Search Tool Settings", /Allowed Search Tools/, ["object_permission_search_tools"]],+ ])("registers %s fields only while that one section is open", async (title, probe, keys) => {+ await openCreateModal();++ const closedPayload = await submit();+ for (const key of keys as string[]) {+ expect(closedPayload).not.toHaveProperty(key);+ }+ });++ it("carries every typed value to the payload at the type antd sends today", async () => {+ await openCreateModal();++ fireEvent.change(screen.getByLabelText("Max Budget (USD)"), { target: { value: "150.75" } });+ fireEvent.change(screen.getByLabelText("Tokens per minute Limit (TPM)"), { target: { value: "900" } });+ fireEvent.change(screen.getByLabelText("Requests per minute Limit (RPM)"), { target: { value: "800" } });++ await openSection("Additional Settings", /Team Member Key Duration/);++ fireEvent.change(screen.getByLabelText("Team ID"), { target: { value: "tid-1" } });+ fireEvent.change(screen.getByLabelText("Team Member Budget (USD)"), { target: { value: "12.5" } });+ fireEvent.change(screen.getByLabelText(/Team Member Key Duration/), { target: { value: "30d" } });+ fireEvent.change(screen.getByLabelText("Team Member RPM Limit"), { target: { value: "7" } });+ fireEvent.change(screen.getByLabelText("Team Member TPM Limit"), { target: { value: "8" } });+ fireEvent.change(screen.getByLabelText("Secret Manager Settings"), {+ target: { value: '{"namespace":"admin"}' },+ });++ const payload = await submit();++ expect(payload.max_budget).toBe("150.75");+ expect(payload.tpm_limit).toBe("900");+ expect(payload.rpm_limit).toBe("800");+ expect(payload.team_id).toBe("tid-1");+ expect(payload.team_member_budget).toBe(12.5);+ expect(payload.team_member_key_duration).toBe("30d");+ expect(payload.team_member_rpm_limit).toBe("7");+ expect(payload.team_member_tpm_limit).toBe("8");+ expect(payload.secret_manager_settings).toStrictEqual({ namespace: "admin" });+ });++ it("blocks the create on an invalid secret manager config, with the rule message suppressed by help", async () => {+ await openCreateModal();+ await openSection("Additional Settings", /Team Member Key Duration/);++ fireEvent.change(screen.getByLabelText("Secret Manager Settings"), { target: { value: " " } });++ const buttons = screen.getAllByRole("button", { name: /create team/i });+ fireEvent.click(buttons[buttons.length - 1]);++ await waitFor(() => {+ expect(screen.getByLabelText("Secret Manager Settings")).toHaveAttribute("aria-invalid", "true");+ });+ expect(teamCreateCall).not.toHaveBeenCalled();+ expect(screen.queryByText("Please enter valid JSON")).not.toBeInTheDocument();+ });++ it("turns the disable-global-guardrails switch into a boolean for a premium user", async () => {+ await openCreateModal({ premiumUser: true });+ await openSection("Additional Settings", /Team Member Key Duration/);++ const switches = screen.getAllByRole("switch");+ fireEvent.click(switches[switches.length - 1]);++ const payload = await submit();++ expect(payload.disable_global_guardrails).toBe(true);+ });++ it("leaves the disable-global-guardrails switch inert for a non-premium user", async () => {+ await openCreateModal();+ await openSection("Additional Settings", /Team Member Key Duration/);++ const switches = screen.getAllByRole("switch");+ fireEvent.click(switches[switches.length - 1]);++ const payload = await submit();++ expect(payload.disable_global_guardrails).toBeUndefined();+ });++ it.each([+ ["MCP Settings", /Allowed MCP Servers/, ["allowed_mcp_servers_and_groups", "mcp_tool_permissions"]],+ ["Agent Settings", /Allowed Agents/, ["allowed_agents_and_groups"]],+ ["Search Tool Settings", /Allowed Search Tools/, ["object_permission_search_tools"]],+ ])("adds the %s keys as soon as that one section is opened", async (title, probe, keys) => {+ await openCreateModal();++ await openSection(title as string, probe as RegExp);+ const payload = await submit();++ for (const key of keys as string[]) {+ expect(payload).toHaveProperty(key);+ }+ });++ it("leaves policies out of the request body for a caller without the viewPolicies capability", async () => {+ can.mockReturnValue(false);++ await openCreateModal();+ await openSection("Additional Settings", /Team Member Key Duration/);++ const payload = await submit();++ expect(payload).toStrictEqual({+ team_alias: "Byte Contract Team",+ organization_id: null,+ models: ["no-default-models"],+ max_budget: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ rpm_limit: undefined,+ metadata: undefined,+ team_id: undefined,+ team_member_budget: undefined,+ team_member_key_duration: undefined,+ team_member_rpm_limit: undefined,+ team_member_tpm_limit: undefined,+ secret_manager_settings: undefined,+ guardrails: undefined,+ disable_global_guardrails: undefined,+ access_group_ids: undefined,+ allowed_vector_store_ids: undefined,+ allowed_passthrough_routes: undefined,+ });+ });++ it("blocks the create on an empty team name and names the rule", async () => {+ renderWithQueryClient(<Teams accessToken="test-token" userID="user-123" userRole="Admin" />);+ act(() => {+ fireEvent.click(screen.getAllByRole("button", { name: /create team/i })[0]);+ });+ await waitFor(() => {+ expect(screen.getByLabelText(/team name/i)).toBeInTheDocument();+ });++ const buttons = screen.getAllByRole("button", { name: /create team/i });+ fireEvent.click(buttons[buttons.length - 1]);++ expect(await screen.findByText("Please input a team name")).toBeInTheDocument();+ expect(teamCreateCall).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/components/Teams.tsx b/ui/litellm-dashboard/src/components/Teams.tsxindex b1f96f51028..94e84c6e721 100644--- a/ui/litellm-dashboard/src/components/Teams.tsx+++ b/ui/litellm-dashboard/src/components/Teams.tsx@@ -4,12 +4,21 @@ import AvailableTeamsPanel from "@/components/team/AvailableTeamsPanel";import TeamInfoView from "@/components/team/TeamInfo";import TeamSSOSettings from "@/components/TeamSSOSettings";import { isProxyAdminRole } from "@/utils/roles";-import { InfoCircleOutlined } from "@ant-design/icons";import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";import { Input as UIInput } from "@/components/ui/input";-import { Button, Form, Input, Layout, Modal, Select, Switch, Tabs, theme, Tooltip, Typography } from "antd";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { TooltipProvider } from "@/components/ui/tooltip";+import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/shared/form/field";+import { FormField } from "@/components/shared/form/FormField";+import { SearchSelect } from "@/components/shared/SearchSelect";+import { labelWithDocsHint, labelWithHint } from "@/components/shared/form/LabelWithHint";+import { useZodForm } from "@/lib/forms/useZodForm";+import { TagsInput } from "@/app/(dashboard)/guardrails/_components/content_filter/TagsInput";+import { Layout, Modal, Tabs, theme } from "antd";import { ChevronDown, Plus, Users } from "lucide-react";-import React, { useEffect, useState } from "react";+import React, { useEffect, useMemo, useState } from "react";+import { z } from "zod/v4";import { useQuery, useQueryClient } from "@tanstack/react-query";import { PageHeader } from "@/components/shared/PageHeader";import { Button as UIButton } from "@/components/ui/button";@@ -17,7 +26,10 @@ import { teamsTableKeys } from "@/app/(dashboard)/hooks/teams/useTeams";import { parseAsString, useQueryState } from "nuqs";import { TeamsTable } from "./TeamsPage/TeamsTable";import AccessGroupSelector from "./common_components/AccessGroupSelector";-import MetadataKeyValueFields, { metadataPairsToObject } from "./common_components/MetadataKeyValueFields";+import MetadataKeyValueFields, {+ metadataPairsSchema,+ metadataPairsToObject,+} from "./common_components/MetadataKeyValueFields";import { useTeamMetadataSchema } from "@/app/(dashboard)/hooks/teams/useTeamMetadataSchema";import PassThroughRoutesSelector from "./common_components/PassThroughRoutesSelector";import AgentSelector from "./agent_management/AgentSelector";@@ -51,6 +63,102 @@ import { teamCreateCall } from "./networking";import { normalizeTeamModelSelection } from "./team/teamModelAccess";import { ModelSelect } from "./ModelSelect/ModelSelect";+const SUPPRESSED_BY_DESCRIPTION = "";++const numericInputSchema = z.union([z.string(), z.number()]).optional();++const teamCreateFieldsSchema = z.object({+ team_alias: z.string().min(1, "Please input a team name"),+ organization_id: z.string().nullish(),+ models: z.array(z.string()).optional(),+ max_budget: numericInputSchema,+ budget_duration: z.string().nullish(),+ tpm_limit: numericInputSchema,+ rpm_limit: numericInputSchema,+ metadata: metadataPairsSchema.optional(),+ team_id: z.string().optional(),+ team_member_budget: z.number().optional(),+ team_member_key_duration: z.string().optional(),+ team_member_rpm_limit: numericInputSchema,+ team_member_tpm_limit: numericInputSchema,+ secret_manager_settings: z.string().optional(),+ guardrails: z.array(z.string()).optional(),+ disable_global_guardrails: z.boolean().optional(),+ policies: z.array(z.string()).optional(),+ access_group_ids: z.array(z.string()).optional(),+ allowed_vector_store_ids: z.array(z.string()).optional(),+ allowed_passthrough_routes: z.array(z.string()).optional(),+ allowed_mcp_servers_and_groups: z+ .object({+ servers: z.array(z.string()),+ accessGroups: z.array(z.string()),+ toolsets: z.array(z.string()).optional(),+ })+ .optional(),+ mcp_tool_permissions: z.record(z.string(), z.array(z.string())).optional(),+ allowed_agents_and_groups: z.object({ agents: z.array(z.string()), accessGroups: z.array(z.string()) }).optional(),+ object_permission_search_tools: z.array(z.string()).optional(),+});++type TeamCreateFormValues = z.infer<typeof teamCreateFieldsSchema>;++const EMPTY_TEAM_CREATE_VALUES: TeamCreateFormValues = {+ team_alias: "",+ organization_id: null,+ models: [],+ max_budget: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ rpm_limit: undefined,+ metadata: [],+ team_id: undefined,+ team_member_budget: undefined,+ team_member_key_duration: undefined,+ team_member_rpm_limit: undefined,+ team_member_tpm_limit: undefined,+ secret_manager_settings: undefined,+ guardrails: undefined,+ disable_global_guardrails: undefined,+ policies: undefined,+ access_group_ids: undefined,+ allowed_vector_store_ids: undefined,+ allowed_passthrough_routes: undefined,+ allowed_mcp_servers_and_groups: undefined,+ mcp_tool_permissions: {},+ allowed_agents_and_groups: undefined,+ object_permission_search_tools: undefined,+};++const ADDITIONAL_SETTINGS_FIELDS = [+ "team_id",+ "team_member_budget",+ "team_member_key_duration",+ "team_member_rpm_limit",+ "team_member_tpm_limit",+ "secret_manager_settings",+ "guardrails",+ "disable_global_guardrails",+ "policies",+ "access_group_ids",+ "allowed_vector_store_ids",+ "allowed_passthrough_routes",+] as const;+const MCP_SETTINGS_FIELDS = ["allowed_mcp_servers_and_groups", "mcp_tool_permissions"] as const;+const AGENT_SETTINGS_FIELDS = ["allowed_agents_and_groups"] as const;+const SEARCH_TOOL_SETTINGS_FIELDS = ["object_permission_search_tools"] as const;++const isParsableJson = (value: string | undefined): boolean => {+ if (!value) {+ return true;+ }+ try {+ JSON.parse(value);+ return true;+ } catch {+ return false;+ }+};+const canCreateOrManageTeams = (userRole: string | null,userID: string | null,@@ -101,7 +209,29 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUserconst [currentOrg] = useState<Organization | null>(null);const [currentOrgForCreateTeam, setCurrentOrgForCreateTeam] = useState<Organization | null>(null);- const [form] = Form.useForm();+ const isOrgAdmin = userRole !== "Admin";+ const [additionalSettingsOpen, setAdditionalSettingsOpen] = useState(false);+ const [mcpSettingsOpen, setMcpSettingsOpen] = useState(false);+ const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);+ const [searchToolSettingsOpen, setSearchToolSettingsOpen] = useState(false);++ const teamCreateSchema = useMemo(+ () =>+ teamCreateFieldsSchema.superRefine((values, ctx) => {+ if (isOrgAdmin && !values.organization_id) {+ ctx.addIssue({ code: "custom", message: SUPPRESSED_BY_DESCRIPTION, path: ["organization_id"] });+ }+ if (additionalSettingsOpen && !isParsableJson(values.secret_manager_settings)) {+ ctx.addIssue({ code: "custom", message: SUPPRESSED_BY_DESCRIPTION, path: ["secret_manager_settings"] });+ }+ }),+ [isOrgAdmin, additionalSettingsOpen],+ );++ const form = useZodForm(teamCreateSchema, { defaultValues: EMPTY_TEAM_CREATE_VALUES });+ const watchedOrganizationId = form.watch("organization_id");+ const watchedMcpSelection = form.watch("allowed_mcp_servers_and_groups");+ const watchedToolPermissions = form.watch("mcp_tool_permissions");const [selectedTeam, setSelectedTeam] = useState<Team | null>(null);const [selectedTeamId, setSelectedTeamId] = useQueryState("team", parseAsString.withOptions({ history: "push" }));@@ -134,27 +264,26 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUser: "n/a";useEffect(() => {- form.setFieldValue("models", []);+ form.setValue("models", []);}, [currentOrgForCreateTeam, userModels]);// Handle organization preselection when modal opensuseEffect(() => {if (isTeamModalVisible) {const adminOrgs = getAdminOrganizations(userRole, userID, organizations);- const isOrgAdmin = userRole !== "Admin";// Org admins must scope a team to an org, so with exactly one we preselect it.// Proxy admins can create org-less teams, so the field stays optional regardless of org count.if (isOrgAdmin && adminOrgs.length === 1) {const org = adminOrgs[0];- form.setFieldValue("organization_id", org.organization_id);+ form.setValue("organization_id", org.organization_id);setCurrentOrgForCreateTeam(org);} else {- form.setFieldValue("organization_id", currentOrg?.organization_id || null);+ form.setValue("organization_id", currentOrg?.organization_id || null);setCurrentOrgForCreateTeam(currentOrg);}}- }, [isTeamModalVisible, userRole, userID, organizations, currentOrg]);+ }, [isTeamModalVisible, isOrgAdmin, userRole, userID, organizations, currentOrg]);// Add this useEffect to fetch guardrailsuseEffect(() => {@@ -190,22 +319,26 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUserif (canViewPolicies) fetchPolicies();}, [accessToken, canViewPolicies]);- const handleOk = () => {- setIsTeamModalVisible(false);- form.resetFields();+ const resetCreateForm = () => {+ form.reset(EMPTY_TEAM_CREATE_VALUES);+ setAdditionalSettingsOpen(false);+ setMcpSettingsOpen(false);+ setAgentSettingsOpen(false);+ setSearchToolSettingsOpen(false);setLoggingSettings([]);setModelAliases({});setRouterSettings(null);setRouterSettingsKey((prev) => prev + 1);};+ const handleOk = () => {+ setIsTeamModalVisible(false);+ resetCreateForm();+ };+const handleCancel = () => {setIsTeamModalVisible(false);- form.resetFields();- setLoggingSettings([]);- setModelAliases({});- setRouterSettings(null);- setRouterSettingsKey((prev) => prev + 1);+ resetCreateForm();};const handleDelete = async (team: Team) => {@@ -378,11 +511,7 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUserawait teamCreateCall(accessToken, { ...formValues, models: normalizeTeamModelSelection(formValues.models) });toast.success("Team created");await refreshTeams();- form.resetFields();- setLoggingSettings([]);- setModelAliases({});- setRouterSettings(null);- setRouterSettingsKey((prev) => prev + 1);+ resetCreateForm();setIsTeamModalVisible(false);}} catch (error) {@@ -391,6 +520,19 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUser}};+ const mountedCreateValues = (values: TeamCreateFormValues): Record<string, unknown> => {+ const unmounted = new Set<string>([+ ...(additionalSettingsOpen ? [] : ADDITIONAL_SETTINGS_FIELDS),+ ...(additionalSettingsOpen && canViewPolicies ? [] : ["policies"]),+ ...(mcpSettingsOpen ? [] : MCP_SETTINGS_FIELDS),+ ...(agentSettingsOpen ? [] : AGENT_SETTINGS_FIELDS),+ ...(searchToolSettingsOpen ? [] : SEARCH_TOOL_SETTINGS_FIELDS),+ ]);+ return Object.fromEntries(Object.entries(values).filter(([key]) => !unmounted.has(key)));+ };++ const onCreateSubmit = (values: TeamCreateFormValues) => handleCreate(mountedCreateValues(values));+const is_team_admin = (team: any) => {if (team == null || team.members_with_roles == null) {return false;@@ -405,7 +547,6 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUser};const { token } = theme.useToken();- const { Text } = Typography;const { Content } = Layout;const tabItems = [@@ -531,556 +672,538 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUseronCancel={handleCancel}destroyOnHidden>- <Form form={form} onFinish={handleCreate} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} labelAlign="left">- <>- <Form.Item- label="Team Name"- name="team_alias"- rules={[- {- required: true,- message: "Please input a team name",- },- ]}- >- <UIInput data-testid="team-name-input" />- </Form.Item>- {(() => {- const adminOrgs = getAdminOrganizations(userRole, userID, organizations);- const isOrgAdmin = userRole !== "Admin";- const isSingleOrg = adminOrgs.length === 1;- const hasNoOrgs = adminOrgs.length === 0;-- return (- <>- <Form.Item- label={- <span>- Organization{" "}- <Tooltip- title={- <span>- Organizations can have multiple teams. Learn more about{" "}- <a- href="https://docs.litellm.ai/docs/proxy/user_management_heirarchy"- target="_blank"- rel="noopener noreferrer"- style={{- color: "#1890ff",- textDecoration: "underline",- }}- onClick={(e) => e.stopPropagation()}- >- user management hierarchy- </a>- </span>- }- >- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="organization_id"- initialValue={currentOrg ? currentOrg.organization_id : null}- className="mt-8"- rules={- isOrgAdmin- ? [- {- required: true,- message: "Please select an organization",- },- ]- : []- }- help={- isOrgAdmin && isSingleOrg- ? "You can only create teams within this organization"- : isOrgAdmin- ? "required"- : ""- }- >- <Select- showSearch- allowClear={!isOrgAdmin}- disabled={isOrgAdmin && isSingleOrg}- placeholder={hasNoOrgs ? "No organizations available" : "Search or select an Organization"}- onChange={(value) => {- form.setFieldValue("organization_id", value);- setCurrentOrgForCreateTeam(adminOrgs?.find((org) => org.organization_id === value) || null);- }}- filterOption={(input, option) => {- if (!option) return false;- const optionValue = option.children?.toString() || "";- return optionValue.toLowerCase().includes(input.toLowerCase());- }}- optionFilterProp="children"+ <TooltipProvider>+ <form onSubmit={form.handleSubmit(onCreateSubmit)}>+ <FieldGroup>+ <FormField control={form.control} name="team_alias" label="Team Name">+ {({ ref, value, ...field }) => (+ <UIInput {...field} ref={ref} value={value ?? ""} data-testid="team-name-input" />+ )}+ </FormField>+ {(() => {+ const adminOrgs = getAdminOrganizations(userRole, userID, organizations);+ const isSingleOrg = adminOrgs.length === 1;+ const hasNoOrgs = adminOrgs.length === 0;++ return (+ <>+ <FormField+ control={form.control}+ name="organization_id"+ className="mt-8"+ label={labelWithDocsHint(+ "Organization",+ "Organizations can have multiple teams. Learn more about the user management hierarchy",+ "https://docs.litellm.ai/docs/proxy/user_management_heirarchy",+ )}+ description={+ isOrgAdmin && isSingleOrg+ ? "You can only create teams within this organization"+ : isOrgAdmin+ ? "required"+ : undefined+ }>- {adminOrgs?.map((org) => (- <Select.Option key={org.organization_id} value={org.organization_id}>- <span className="font-medium">{org.organization_alias}</span>{" "}- <span className="text-gray-500">({org.organization_id})</span>- </Select.Option>- ))}- </Select>- </Form.Item>-- {/* Show message when org admin needs to select organization */}- {isOrgAdmin && !isSingleOrg && adminOrgs.length > 1 && (- <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md">- <Text style={{ color: "#1e40af", fontSize: 14 }}>- Please select an organization to create a team for. You can only create teams within- organizations where you are an admin.- </Text>- </div>- )}- </>- );- })()}- <Form.Item- label={- <span>- Models{" "}- <Tooltip title="These are the models that your selected team has access to. Leave empty to grant no models directly, e.g. when the team gets its models from access groups">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="models"- >- <ModelSelect- value={form.getFieldValue("models") || []}- onChange={(values) => form.setFieldValue("models", values)}- organizationID={form.getFieldValue("organization_id")}- options={{- includeSpecialOptions: true,- showAllProxyModelsOverride: !form.getFieldValue("organization_id"),- }}- context="team"- dataTestId="create-team-models-select"- />- </Form.Item>-- <Form.Item label="Max Budget (USD)" name="max_budget">- <NumericalInput step={0.01} precision={2} width={200} />- </Form.Item>- <Form.Item className="mt-8" label="Reset Budget" name="budget_duration">- <BudgetDurationDropdown showNeverResets placeholder={budgetDurationPlaceholder} />- </Form.Item>- <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">- <NumericalInput step={1} width={400} />- </Form.Item>- <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">- <NumericalInput step={1} width={400} />- </Form.Item>- <Form.Item- label="Metadata"- help='Values are saved as text. Enter JSON for typed values, e.g. 3, true, or {"region": "us"}.'- >- <MetadataKeyValueFields- form={form}- schemaFields={teamMetadataSchemaFields}- schemaLoading={isTeamMetadataSchemaLoading}- />- </Form.Item>-- <Collapsible className="mt-20 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Additional Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <Form.Item- label="Team ID"- name="team_id"- help="ID of the team you want to create. If not provided, it will be generated automatically."- >- <UIInput- onChange={(e) => {- e.target.value = e.target.value.trim();+ {({ id, value, onChange }) => (+ <SearchSelect+ inputId={id}+ value={value ?? ""}+ options={adminOrgs.map((org) => ({+ value: org.organization_id ?? "",+ label: org.organization_alias ?? "",+ sublabel: org.organization_id ?? "",+ }))}+ disabled={isOrgAdmin && isSingleOrg}+ allowClear={!isOrgAdmin}+ placeholder={hasNoOrgs ? "No organizations available" : "Search or select an Organization"}+ emptyText="No organizations available"+ onValueChange={(next) => {+ onChange(next === "" ? null : next);+ setCurrentOrgForCreateTeam(adminOrgs.find((org) => org.organization_id === next) ?? null);+ }}+ />+ )}+ </FormField>++ {isOrgAdmin && !isSingleOrg && adminOrgs.length > 1 && (+ <div className="mb-8 rounded-md border border-blue-200 bg-blue-50 p-4">+ <span className="text-sm text-blue-800">+ Please select an organization to create a team for. You can only create teams within+ organizations where you are an admin.+ </span>+ </div>+ )}+ </>+ );+ })()}+ <FormField+ control={form.control}+ name="models"+ label={labelWithHint(+ "Models",+ "These are the models that your selected team has access to. Leave empty to grant no models directly, e.g. when the team gets its models from access groups",+ )}+ >+ {({ id, value, onChange }) => (+ <ModelSelect+ id={id}+ value={value ?? []}+ onChange={onChange}+ organizationID={watchedOrganizationId ?? undefined}+ options={{+ includeSpecialOptions: true,+ showAllProxyModelsOverride: !watchedOrganizationId,}}+ context="team"+ dataTestId="create-team-models-select"/>- </Form.Item>- <Form.Item- label="Team Member Budget (USD)"- name="team_member_budget"- normalize={(value) => (value ? Number(value) : undefined)}- tooltip="This is the individual budget for a user in the team."- >- <NumericalInput step={0.01} precision={2} width={200} />- </Form.Item>- <Form.Item- label="Team Member Key Duration (eg: 1d, 1mo)"- name="team_member_key_duration"- tooltip="Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)"- >- <UIInput placeholder="e.g., 30d" />- </Form.Item>- <Form.Item- label="Team Member RPM Limit"- name="team_member_rpm_limit"- tooltip="The RPM (Requests Per Minute) limit for individual team members"- >- <NumericalInput step={1} width={400} />- </Form.Item>- <Form.Item- label="Team Member TPM Limit"- name="team_member_tpm_limit"- tooltip="The TPM (Tokens Per Minute) limit for individual team members"- >- <NumericalInput step={1} width={400} />- </Form.Item>- <Form.Item- label="Secret Manager Settings"- name="secret_manager_settings"- help={- premiumUser- ? "Enter secret manager configuration as a JSON object."- : "Premium feature - Upgrade to manage secret manager settings."- }- rules={[- {- validator: async (_, value) => {- if (!value) {- return Promise.resolve();- }- try {- JSON.parse(value);- return Promise.resolve();- } catch (error) {- return Promise.reject(new Error("Please enter valid JSON"));- }- },- },- ]}- >- <Input.TextArea- rows={4}- placeholder='{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}'- disabled={!premiumUser}- />- </Form.Item>- <Form.Item- label={- <span>- Guardrails{" "}- <Tooltip title="Setup your first guardrail">- <a- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"- target="_blank"- rel="noopener noreferrer"- onClick={(e) => e.stopPropagation()}- >- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </a>- </Tooltip>- </span>- }- name="guardrails"- className="mt-8"- 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>- <Form.Item- label={- <span>- Disable Global Guardrails{" "}- <Tooltip title="When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="disable_global_guardrails"- className="mt-4"- valuePropName="checked"- help="Bypass global guardrails for this team"- >- <Switch- disabled={!premiumUser}- checkedChildren={- premiumUser ? "Yes" : "Premium feature - Upgrade to disable global guardrails by team"- }- unCheckedChildren={- premiumUser ? "No" : "Premium feature - Upgrade to disable global guardrails by team"- }+ )}+ </FormField>++ <FormField control={form.control} name="max_budget" label="Max Budget (USD)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={0.01} precision={2} width={200} />+ )}+ </FormField>+ <FormField control={form.control} name="budget_duration" className="mt-8" label="Reset Budget">+ {({ id, value, onChange }) => (+ <BudgetDurationDropdown+ id={id}+ showNeverResets+ placeholder={budgetDurationPlaceholder}+ value={value}+ onChange={onChange}/>- </Form.Item>- {canViewPolicies && (- <Form.Item- label={- <span>- Policies{" "}- <Tooltip title="Apply policies to this team to control guardrails and other settings">- <a- href="https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies"- target="_blank"- rel="noopener noreferrer"- onClick={(e) => e.stopPropagation()}- >- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </a>- </Tooltip>- </span>- }- name="policies"- className="mt-8"- help="Select existing policies or enter new ones"+ )}+ </FormField>+ <FormField control={form.control} name="tpm_limit" label="Tokens per minute Limit (TPM)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} width={400} />+ )}+ </FormField>+ <FormField control={form.control} name="rpm_limit" label="Requests per minute Limit (RPM)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} width={400} />+ )}+ </FormField>+ <Field>+ <FieldLabel>Metadata</FieldLabel>+ <MetadataKeyValueFields+ control={form.control}+ getValues={form.getValues}+ name="metadata"+ schemaFields={teamMetadataSchemaFields}+ schemaLoading={isTeamMetadataSchemaLoading}+ />+ <FieldDescription>+ Values are saved as text. Enter JSON for typed values, e.g. 3, true, or {'{"region": "us"}'}.+ </FieldDescription>+ </Field>++ <Collapsible+ open={additionalSettingsOpen}+ onOpenChange={setAdditionalSettingsOpen}+ className="mt-20 mb-8 overflow-hidden rounded-lg border"+ >+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Additional Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <FieldGroup>+ <FormField+ control={form.control}+ name="team_id"+ label="Team ID"+ description="ID of the team you want to create. If not provided, it will be generated automatically."+ >+ {({ ref, value, ...field }) => <UIInput {...field} ref={ref} value={value ?? ""} />}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_budget"+ label={labelWithHint(+ "Team Member Budget (USD)",+ "This is the individual budget for a user in the team.",+ )}+ >+ {({ ref, value, onChange, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ onChange(event.target.value ? Number(event.target.value) : undefined)+ }+ step={0.01}+ precision={2}+ width={200}+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_key_duration"+ label={labelWithHint(+ "Team Member Key Duration (eg: 1d, 1mo)",+ "Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",+ )}+ >+ {({ ref, value, ...field }) => (+ <UIInput {...field} ref={ref} value={value ?? ""} placeholder="e.g., 30d" />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_rpm_limit"+ label={labelWithHint(+ "Team Member RPM Limit",+ "The RPM (Requests Per Minute) limit for individual team members",+ )}+ >+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} width={400} />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_tpm_limit"+ label={labelWithHint(+ "Team Member TPM Limit",+ "The TPM (Tokens Per Minute) limit for individual team members",+ )}+ >+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} width={400} />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="secret_manager_settings"+ label="Secret Manager Settings"+ description={+ premiumUser+ ? "Enter secret manager configuration as a JSON object."+ : "Premium feature - Upgrade to manage secret manager settings."+ }+ >+ {({ ref, value, ...field }) => (+ <Textarea+ {...field}+ ref={ref}+ value={value ?? ""}+ rows={4}+ placeholder='{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}'+ disabled={!premiumUser}+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="guardrails"+ className="mt-8"+ label={labelWithDocsHint(+ "Guardrails",+ "Setup your first guardrail",+ "https://docs.litellm.ai/docs/proxy/guardrails/quick_start",+ )}+ description="Select existing guardrails or enter new ones"+ >+ {({ id, value, onChange }) => (+ <TagsInput+ id={id}+ value={value ?? []}+ onValueChange={onChange}+ options={guardrailsList.map((name) => ({ value: name, label: name }))}+ placeholder="Select or enter guardrails"+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="disable_global_guardrails"+ className="mt-4"+ label={labelWithHint(+ "Disable Global Guardrails",+ "When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)",+ )}+ description={+ premiumUser+ ? "Bypass global guardrails for this team"+ : "Premium feature - Upgrade to disable global guardrails by team"+ }+ >+ {({ id, value, onChange }) => (+ <Switch id={id} disabled={!premiumUser} checked={value === true} onCheckedChange={onChange} />+ )}+ </FormField>+ {canViewPolicies && (+ <FormField+ control={form.control}+ name="policies"+ className="mt-8"+ label={labelWithDocsHint(+ "Policies",+ "Apply policies to this team to control guardrails and other settings",+ "https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",+ )}+ description="Select existing policies or enter new ones"+ >+ {({ id, value, onChange }) => (+ <TagsInput+ id={id}+ value={value ?? []}+ onValueChange={onChange}+ options={policiesList.map((name) => ({ value: name, label: name }))}+ placeholder="Select or enter policies"+ />+ )}+ </FormField>+ )}+ <FormField+ control={form.control}+ name="access_group_ids"+ className="mt-8"+ label={labelWithHint(+ "Access Groups",+ "Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use",+ )}+ description="Select access groups to assign to this team"+ >+ {({ value, onChange }) => (+ <AccessGroupSelector+ value={value}+ onChange={onChange}+ placeholder="Select access groups (optional)"+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="allowed_vector_store_ids"+ className="mt-8"+ label={labelWithHint(+ "Allowed Vector Stores",+ "Select which vector stores this team can access by default. Leave empty for access to all vector stores",+ )}+ description="Select vector stores this team can access. Leave empty for access to all vector stores"+ >+ {({ value, onChange }) => (+ <VectorStoreSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select vector stores (optional)"+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="allowed_passthrough_routes"+ className="mt-8"+ label={+ !premiumUser+ ? labelWithHint(+ "Allowed Pass Through Routes",+ "Premium feature - Upgrade to set allowed pass through routes",+ )+ : !isProxyAdminRole(userRole || "")+ ? labelWithHint(+ "Allowed Pass Through Routes",+ "Only proxy admins can set allowed pass through routes",+ )+ : "Allowed Pass Through Routes"+ }+ >+ {({ value, onChange }) => (+ <PassThroughRoutesSelector+ value={value}+ onChange={onChange}+ accessToken={accessToken || ""}+ placeholder="Select pass through routes (optional)"+ disabled={!premiumUser || !isProxyAdminRole(userRole || "")}+ />+ )}+ </FormField>+ </FieldGroup>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible+ open={mcpSettingsOpen}+ onOpenChange={setMcpSettingsOpen}+ className="mt-8 mb-8 overflow-hidden rounded-lg border"+ >+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>MCP Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <FormField+ control={form.control}+ name="allowed_mcp_servers_and_groups"+ className="mt-4"+ label={labelWithHint(+ "Allowed MCP Servers",+ "Select which MCP servers or access groups this team can access",+ )}+ description="Select MCP servers or access groups this team can access">- <Select- mode="tags"- style={{ width: "100%" }}- placeholder="Select or enter policies"- options={policiesList.map((name) => ({- value: name,- label: name,- }))}+ {({ value, onChange }) => (+ <MCPServerSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select MCP servers or access groups (optional)"+ allowAllProxyMcpServers={isProxyAdminRole(userRole || "")}+ />+ )}+ </FormField>++ <div className="mt-6">+ <MCPToolPermissions+ accessToken={accessToken || ""}+ selectedServers={watchedMcpSelection?.servers || []}+ toolPermissions={watchedToolPermissions || {}}+ onChange={(toolPerms) => form.setValue("mcp_tool_permissions", toolPerms)}/>- </Form.Item>- )}- <Form.Item- label={- <span>- Access Groups{" "}- <Tooltip title="Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="access_group_ids"- className="mt-8"- help="Select access groups to assign to this team"- >- <AccessGroupSelector placeholder="Select access groups (optional)" />- </Form.Item>- <Form.Item- label={- <span>- Allowed Vector Stores{" "}- <Tooltip title="Select which vector stores this team can access by default. Leave empty for access to all vector stores">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="allowed_vector_store_ids"- className="mt-8"- help="Select vector stores this team can access. Leave empty for access to all vector stores"- >- <VectorStoreSelector- onChange={(values: string[]) => form.setFieldValue("allowed_vector_store_ids", values)}- value={form.getFieldValue("allowed_vector_store_ids")}- accessToken={accessToken || ""}- placeholder="Select vector stores (optional)"- />- </Form.Item>- <Form.Item- label="Allowed Pass Through Routes"- name="allowed_passthrough_routes"- className="mt-8"- tooltip={- !premiumUser- ? "Premium feature - Upgrade to set allowed pass through routes"- : !isProxyAdminRole(userRole || "")- ? "Only proxy admins can set allowed pass through routes"- : undefined- }- >- <PassThroughRoutesSelector- accessToken={accessToken || ""}- placeholder="Select pass through routes (optional)"- disabled={!premiumUser || !isProxyAdminRole(userRole || "")}- />- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>MCP Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <Form.Item- label={- <span>- Allowed MCP Servers{" "}- <Tooltip title="Select which MCP servers or access groups this team can access">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="allowed_mcp_servers_and_groups"- className="mt-4"- help="Select MCP servers or access groups this team can access"- >- <MCPServerSelector- onChange={(val: any) => form.setFieldValue("allowed_mcp_servers_and_groups", val)}- value={form.getFieldValue("allowed_mcp_servers_and_groups")}- accessToken={accessToken || ""}- placeholder="Select MCP servers or access groups (optional)"- allowAllProxyMcpServers={isProxyAdminRole(userRole || "")}- />- </Form.Item>-- {/* Hidden field to register mcp_tool_permissions with the form */}- <Form.Item name="mcp_tool_permissions" initialValue={{}} hidden>- <Input type="hidden" />- </Form.Item>-- <Form.Item- noStyle- shouldUpdate={(prevValues, currentValues) =>- prevValues.allowed_mcp_servers_and_groups !== currentValues.allowed_mcp_servers_and_groups ||- prevValues.mcp_tool_permissions !== currentValues.mcp_tool_permissions- }- >- {() => (- <div className="mt-6">- <MCPToolPermissions+ </div>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible+ open={agentSettingsOpen}+ onOpenChange={setAgentSettingsOpen}+ className="mt-8 mb-8 overflow-hidden rounded-lg border"+ >+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Agent Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <FormField+ control={form.control}+ name="allowed_agents_and_groups"+ className="mt-4"+ label={labelWithHint(+ "Allowed Agents",+ "Select which agents or access groups this team can access",+ )}+ description="Select agents or access groups this team can access"+ >+ {({ value, onChange }) => (+ <AgentSelector+ onChange={onChange}+ value={value}accessToken={accessToken || ""}- selectedServers={form.getFieldValue("allowed_mcp_servers_and_groups")?.servers || []}- toolPermissions={form.getFieldValue("mcp_tool_permissions") || {}}- onChange={(toolPerms) => form.setFieldsValue({ mcp_tool_permissions: toolPerms })}+ placeholder="Select agents or access groups (optional)"/>- </div>- )}- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Agent Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <Form.Item- label={- <span>- Allowed Agents{" "}- <Tooltip title="Select which agents or access groups this team can access">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="allowed_agents_and_groups"- className="mt-4"- help="Select agents or access groups this team can access"- >- <AgentSelector- onChange={(val: any) => form.setFieldValue("allowed_agents_and_groups", val)}- value={form.getFieldValue("allowed_agents_and_groups")}- accessToken={accessToken || ""}- placeholder="Select agents or access groups (optional)"- />- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Search Tool Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <Form.Item- label={- <span>- Allowed Search Tools{" "}- <Tooltip title="Select which search tools this team can access. Leave empty to allow all search tools.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="object_permission_search_tools"- className="mt-4"- help="Restrict which configured search tools keys on this team may call."- >- <SearchToolSelector- onChange={(vals: string[]) => form.setFieldValue("object_permission_search_tools", vals)}- value={form.getFieldValue("object_permission_search_tools")}- accessToken={accessToken || ""}- placeholder="Select search tools (optional, empty = all allowed)"- />- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Logging Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <div className="mt-4">- <PremiumLoggingSettings- value={loggingSettings}- onChange={setLoggingSettings}- premiumUser={premiumUser}- />- </div>- </CollapsibleContent>- </Collapsible>-- <Collapsible- key={`router-settings-accordion-${routerSettingsKey}`}- className="mt-8 mb-8 overflow-hidden rounded-lg border"- >- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Router Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <div className="mt-4 w-full">- <RouterSettingsAccordion- key={routerSettingsKey}- accessToken={accessToken || ""}- value={routerSettings || undefined}- onChange={setRouterSettings}- modelData={- userModels.length > 0 ? { data: userModels.map((model) => ({ model_name: model })) } : undefined- }- />- </div>- </CollapsibleContent>- </Collapsible>-- <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Model Aliases</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <div className="mt-4">- <Text type="secondary" style={{ fontSize: 14, marginBottom: 16, display: "block" }}>- Create custom aliases for models that can be used by team members in API calls. This allows you to- create shortcuts for specific models.- </Text>- <ModelAliasManager- accessToken={accessToken || ""}- initialModelAliases={modelAliases}- onAliasUpdate={setModelAliases}- showExampleConfig={false}- />- </div>- </CollapsibleContent>- </Collapsible>- </>- <div style={{ textAlign: "right", marginTop: "10px" }}>- <Button htmlType="submit" data-testid="create-team-submit">- Create Team- </Button>- </div>- </Form>+ )}+ </FormField>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible+ open={searchToolSettingsOpen}+ onOpenChange={setSearchToolSettingsOpen}+ className="mt-8 mb-8 overflow-hidden rounded-lg border"+ >+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Search Tool Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <FormField+ control={form.control}+ name="object_permission_search_tools"+ className="mt-4"+ label={labelWithHint(+ "Allowed Search Tools",+ "Select which search tools this team can access. Leave empty to allow all search tools.",+ )}+ description="Restrict which configured search tools keys on this team may call."+ >+ {({ value, onChange }) => (+ <SearchToolSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select search tools (optional, empty = all allowed)"+ />+ )}+ </FormField>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Logging Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <div className="mt-4">+ <PremiumLoggingSettings+ value={loggingSettings}+ onChange={setLoggingSettings}+ premiumUser={premiumUser}+ />+ </div>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible+ key={`router-settings-accordion-${routerSettingsKey}`}+ className="mt-8 mb-8 overflow-hidden rounded-lg border"+ >+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Router Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <div className="mt-4 w-full">+ <RouterSettingsAccordion+ key={routerSettingsKey}+ accessToken={accessToken || ""}+ value={routerSettings || undefined}+ onChange={setRouterSettings}+ modelData={+ userModels.length > 0+ ? { data: userModels.map((model) => ({ model_name: model })) }+ : undefined+ }+ />+ </div>+ </CollapsibleContent>+ </Collapsible>++ <Collapsible className="mt-8 mb-8 overflow-hidden rounded-lg border">+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Model Aliases</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <div className="mt-4">+ <p className="mb-4 block text-sm text-muted-foreground">+ Create custom aliases for models that can be used by team members in API calls. This allows you+ to create shortcuts for specific models.+ </p>+ <ModelAliasManager+ accessToken={accessToken || ""}+ initialModelAliases={modelAliases}+ onAliasUpdate={setModelAliases}+ showExampleConfig={false}+ />+ </div>+ </CollapsibleContent>+ </Collapsible>+ </FieldGroup>+ <div className="mt-[10px] text-right">+ <UIButton type="submit" data-testid="create-team-submit">+ Create Team+ </UIButton>+ </div>+ </form>+ </TooltipProvider></Modal>)}</Content>diff --git a/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.test.tsx b/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.test.tsxindex 365cc8bbff5..073b11947a5 100644--- a/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.test.tsx+++ b/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.test.tsx@@ -1,12 +1,14 @@import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { Form } from "antd";import React from "react";import { describe, expect, it, vi } from "vitest";+import { z } from "zod/v4";import { TeamMetadataField } from "@/app/(dashboard)/hooks/teams/useTeamMetadataSchema";+import { useZodForm } from "@/lib/forms/useZodForm";import MetadataKeyValueFields, {MetadataPair,metadataObjectToPairs,+ metadataPairsSchema,metadataPairsToObject,} from "./MetadataKeyValueFields";@@ -95,13 +97,21 @@ interface HarnessProps {schemaLoading?: boolean;}+const harnessSchema = z.object({ metadata: metadataPairsSchema });+const Harness: React.FC<HarnessProps> = ({ onFinish, initialMetadata, schemaFields, schemaLoading }) => {- const [form] = Form.useForm();+ const form = useZodForm(harnessSchema, { defaultValues: { metadata: initialMetadata ?? [] } });return (- <Form form={form} onFinish={onFinish} initialValues={{ metadata: initialMetadata }}>- <MetadataKeyValueFields form={form} schemaFields={schemaFields} schemaLoading={schemaLoading} />+ <form onSubmit={form.handleSubmit((values) => onFinish(values))}>+ <MetadataKeyValueFields+ control={form.control}+ getValues={form.getValues}+ name="metadata"+ schemaFields={schemaFields}+ schemaLoading={schemaLoading}+ /><button type="submit">Save</button>- </Form>+ </form>);};diff --git a/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.tsx b/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.tsxindex da085f95ad8..1c67d48128f 100644--- a/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.tsx+++ b/ui/litellm-dashboard/src/components/common_components/MetadataKeyValueFields.tsx@@ -1,14 +1,36 @@-import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";-import { Button, Form, FormInstance, Input, Skeleton, Space } from "antd";+import { CircleMinus, Plus } from "lucide-react";import React, { useEffect, useRef } from "react";+import {+ useFieldArray,+ type Control,+ type FieldArrayPath,+ type FieldPath,+ type FieldValues,+ type UseFormGetValues,+} from "react-hook-form";+import { z } from "zod/v4";import { TeamMetadataField } from "@/app/(dashboard)/hooks/teams/useTeamMetadataSchema";+import { FormField } from "@/components/shared/form/FormField";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";export interface MetadataPair {key: string;value: string;}+export const metadataPairsSchema = z+ .array(z.object({ key: z.string().min(1, "Missing key"), value: z.string().optional() }))+ .superRefine((pairs, ctx) => {+ pairs.forEach((pair, index) => {+ if (pair.key && pairs.filter((other) => other.key === pair.key).length > 1) {+ ctx.addIssue({ code: "custom", message: "Duplicate key", path: [index, "key"] });+ }+ });+ });+function formatMetadataValue(value: unknown): string {if (typeof value !== "string") {return JSON.stringify(value) ?? "";@@ -48,87 +70,82 @@ export function metadataPairsToObject();}-interface MetadataKeyValueFieldsProps {- form: FormInstance;- name?: string;+interface MetadataKeyValueFieldsProps<TFieldValues extends FieldValues> {+ control: Control<TFieldValues>;+ getValues: UseFormGetValues<TFieldValues>;+ name: FieldArrayPath<TFieldValues>;schemaFields?: readonly TeamMetadataField[];schemaLoading?: boolean;}-const MetadataKeyValueFields: React.FC<MetadataKeyValueFieldsProps> = ({- form,- name = "metadata",+const MetadataKeyValueFields = <TFieldValues extends FieldValues>({+ control,+ getValues,+ name,schemaFields = [],schemaLoading = false,-}) => {+}: MetadataKeyValueFieldsProps<TFieldValues>) => {+ const { fields, append, remove } = useFieldArray({ control, name });const seededRef = useRef(false);useEffect(() => {if (seededRef.current || schemaLoading || schemaFields.length === 0) return;seededRef.current = true;- const pairs: (Partial<MetadataPair> | undefined)[] = form.getFieldValue(name) ?? [];+ const pairs: (Partial<MetadataPair> | undefined)[] = getValues(name as unknown as FieldPath<TFieldValues>) ?? [];if (!Array.isArray(pairs)) return;const existingKeys = new Set(pairs.map((pair) => pair?.key).filter(Boolean));const seeded = schemaFields.filter((field) => !existingKeys.has(field.key)).map((field) => ({ key: field.key, value: "" }));if (seeded.length > 0) {- form.setFieldValue(name, [...pairs, ...seeded]);+ append(seeded as never, { shouldFocus: false });}- }, [form, name, schemaFields, schemaLoading]);+ }, [append, getValues, name, schemaFields, schemaLoading]);if (schemaLoading) {return (- <div data-testid="metadata-schema-skeleton">- <Skeleton active title={false} paragraph={{ rows: 3 }} />+ <div data-testid="metadata-schema-skeleton" className="space-y-2">+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" /></div>);}return (- <Form.List name={name}>- {(fields, { add, remove }) => (- <>- {fields.map(({ key, name: fieldName, ...restField }) => (- <Space key={key} style={{ display: "flex", marginBottom: 8 }} align="baseline">- <Form.Item- {...restField}- name={[fieldName, "key"]}- rules={[- { required: true, message: "Missing key" },- {- validator: (_, value) => {- if (!value) return Promise.resolve();- const all: (Partial<MetadataPair> | undefined)[] = form.getFieldValue(name) ?? [];- const dupes = all.filter((entry) => 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={[fieldName, "value"]}>- <Input placeholder="Value" />- </Form.Item>- <MinusCircleOutlined- aria-label="Remove key-value pair"- onClick={() => remove(fieldName)}- style={{ color: "#ef4444" }}- />- </Space>- ))}- <Form.Item style={{ marginBottom: 0 }}>- <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>- Add Key-Value Pair- </Button>- </Form.Item>- </>- )}- </Form.List>+ <>+ {fields.map((field, index) => (+ <div key={field.id} className="mb-2 flex items-start gap-2">+ <FormField control={control} name={`${name}.${index}.key` as FieldPath<TFieldValues>}>+ {({ ref, value, ...rest }) => (+ <Input {...rest} ref={ref} value={(value as string) ?? ""} placeholder="Key" />+ )}+ </FormField>+ <FormField control={control} name={`${name}.${index}.value` as FieldPath<TFieldValues>}>+ {({ ref, value, ...rest }) => (+ <Input {...rest} ref={ref} value={(value as string) ?? ""} placeholder="Value" />+ )}+ </FormField>+ <Button+ variant="ghost"+ size="icon"+ aria-label="Remove key-value pair"+ className="mt-1 text-destructive"+ onClick={() => remove(index)}+ >+ <CircleMinus className="size-4" />+ </Button>+ </div>+ ))}+ <Button+ variant="outline"+ className="w-full border-dashed"+ onClick={() => append({ key: "", value: "" } as never, { shouldFocus: false })}+ >+ <Plus className="size-4" />+ Add Key-Value Pair+ </Button>+ </>);};diff --git a/ui/litellm-dashboard/src/components/shared/form/LabelWithHint.tsx b/ui/litellm-dashboard/src/components/shared/form/LabelWithHint.tsxnew file mode 100644index 00000000000..475351e6272--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/form/LabelWithHint.tsx@@ -0,0 +1,34 @@+"use client";++import { CircleHelp } from "lucide-react";+import React from "react";++import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";++const hintIconClassName = "size-3.5 shrink-0 cursor-help text-muted-foreground";++export const labelWithHint = (label: React.ReactNode, hint: React.ReactNode): React.ReactNode => (+ <>+ {label}+ <Tooltip>+ <TooltipTrigger render={<CircleHelp className={hintIconClassName} />} />+ <TooltipContent>{hint}</TooltipContent>+ </Tooltip>+ </>+);++export const labelWithDocsHint = (label: React.ReactNode, hint: React.ReactNode, href: string): React.ReactNode => (+ <>+ {label}+ <Tooltip>+ <TooltipTrigger+ render={+ <a href={href} target="_blank" rel="noopener noreferrer" onClick={(event) => event.stopPropagation()}>+ <CircleHelp className={hintIconClassName} />+ </a>+ }+ />+ <TooltipContent>{hint}</TooltipContent>+ </Tooltip>+ </>+);diff --git a/ui/litellm-dashboard/src/components/team/GuardrailsSelect.tsx b/ui/litellm-dashboard/src/components/team/GuardrailsSelect.tsxnew file mode 100644index 00000000000..74d5048d82b--- /dev/null+++ b/ui/litellm-dashboard/src/components/team/GuardrailsSelect.tsx@@ -0,0 +1,133 @@+"use client";++import { Globe } from "lucide-react";+import React, { useState } from "react";++import {+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxCollection,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxGroup,+ ComboboxItem,+ ComboboxLabel,+ ComboboxList,+ ComboboxValue,+ useComboboxAnchor,+} from "@/components/ui/combobox";++export interface GuardrailOption {+ name: string;+ disabled: boolean;+}++interface GuardrailGroup {+ label: string;+ icon: boolean;+ items: GuardrailOption[];+}++interface GuardrailsSelectProps {+ id?: string;+ value: string[];+ onValueChange: (value: string[]) => void;+ globalGuardrails: readonly GuardrailOption[];+ otherGuardrails: readonly GuardrailOption[];+ globalGuardrailNames: ReadonlySet<string>;+ placeholder?: string;+ emptyText?: string;+}++const matchesQuery = (option: GuardrailOption, query: string): boolean =>+ option.name.toLowerCase().includes(query.trim().toLowerCase());++export const GuardrailsSelect: React.FC<GuardrailsSelectProps> = ({+ id,+ value,+ onValueChange,+ globalGuardrails,+ otherGuardrails,+ globalGuardrailNames,+ placeholder = "Select guardrails",+ emptyText = "No guardrails found",+}) => {+ const anchor = useComboboxAnchor();+ const [query, setQuery] = useState("");++ const known = [...globalGuardrails, ...otherGuardrails];+ const selected = value.map((name) => known.find((option) => option.name === name) ?? { name, disabled: false });+ const grouped = globalGuardrails.length > 0 && otherGuardrails.length > 0;+ const groups: GuardrailGroup[] = grouped+ ? [+ { label: "Global", icon: true, items: [...globalGuardrails] },+ { label: "Other", icon: false, items: [...otherGuardrails] },+ ]+ : [{ label: "", icon: false, items: known }];++ return (+ <Combobox+ multiple+ items={groups}+ value={selected}+ onValueChange={(next: GuardrailOption[]) => {+ setQuery("");+ onValueChange(next.map((option) => option.name));+ }}+ inputValue={query}+ onInputValueChange={setQuery}+ isItemEqualToValue={(option: GuardrailOption, other: GuardrailOption) => option.name === other.name}+ itemToStringLabel={(option: GuardrailOption) => option.name}+ filter={matchesQuery}+ openOnInputClick+ >+ <ComboboxChips render={<div ref={anchor} />} className="min-h-8 py-1 text-sm">+ <ComboboxValue>+ {(chips: GuardrailOption[]) => (+ <>+ {chips.map((option) => (+ <ComboboxChip key={option.name} aria-label={option.name}>+ {globalGuardrailNames.has(option.name) && <Globe className="size-3" aria-label="Global guardrail" />}+ {option.name}+ </ComboboxChip>+ ))}+ <ComboboxChipsInput id={id} placeholder={placeholder} className="min-w-24" aria-label={placeholder} />+ </>+ )}+ </ComboboxValue>+ </ComboboxChips>+ <ComboboxContent anchor={anchor}>+ <ComboboxEmpty>{emptyText}</ComboboxEmpty>+ <ComboboxList>+ {(group: GuardrailGroup) => (+ <ComboboxGroup key={group.label} items={group.items}>+ {group.label !== "" && (+ <ComboboxLabel>+ {group.icon ? <Globe className="mr-1 inline size-3" aria-hidden="true" /> : null}+ {group.label}+ </ComboboxLabel>+ )}+ <ComboboxCollection>+ {(option: GuardrailOption) => (+ <ComboboxItem+ key={option.name}+ value={option}+ title={option.name}+ disabled={option.disabled}+ aria-label={option.name}+ >+ {option.name}+ </ComboboxItem>+ )}+ </ComboboxCollection>+ </ComboboxGroup>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ );+};++export default GuardrailsSelect;diff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsxindex 9df13a982ed..aeba85088bb 100644--- a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx@@ -122,7 +122,9 @@ vi.mock("@/components/common_components/ModelAliasManager", () => ({<div><div data-testid="alias-editor-initial">{JSON.stringify(initialModelAliases)}</div><button onClick={() => onAliasUpdate({ "gpt-4o": "gpt-4" })}>Set Alias</button>- <button onClick={() => onAliasUpdate({})}>Clear Aliases</button>+ <button type="button" onClick={() => onAliasUpdate({})}>+ Clear Aliases+ </button></div>)),}));@@ -658,7 +660,7 @@ describe("TeamInfoView", () => {});describe("settings and editing", () => {- const policiesFormFieldLabel = () => screen.queryByText("Policies", { selector: "span" });+ const policiesFormFieldLabel = () => screen.queryByText("Policies", { selector: "label" });it("should offer the policies field and load it for a caller with the viewPolicies capability", async () => {const user = userEvent.setup({ delay: null });@@ -1462,8 +1464,7 @@ describe("TeamInfoView", () => {await user.click(screen.getByLabelText(/^Guardrails/));const listbox = await screen.findByRole("listbox", {}, { timeout: 5000 });- // eslint-disable-next-line local/no-antd-class-selectors -- antd renders group headers outside the listbox and its popup container exposes no role or accessible name- return listbox.closest(".ant-select-dropdown") as HTMLElement;+ return listbox.closest('[data-slot="combobox-content"]') as HTMLElement;};beforeEach(() => {@@ -1660,3 +1661,310 @@ describe("TeamInfoView - which team member fields reach the update payload depenexpect(payload.object_permission).toHaveProperty("search_tools");});});++describe("TeamInfoView - the exact bytes the update call sends", () => {+ const props = {+ teamId: "123",+ onUpdate: vi.fn(),+ onClose: vi.fn(),+ accessToken: "test-token",+ is_team_admin: true,+ is_proxy_admin: true,+ userModels: ["gpt-4"],+ editTeam: false,+ };++ beforeEach(seedDefaultMocks);++ afterEach(() => {+ vi.clearAllMocks();+ });++ const storedTeam = () =>+ createMockTeamData({+ models: ["gpt-4"],+ max_budget: 100,+ budget_duration: "1d",+ tpm_limit: 1000,+ rpm_limit: 1000,+ team_member_budget_table: { max_budget: 42, budget_duration: "30d", tpm_limit: 11, rpm_limit: 22 },+ default_team_member_models: ["gpt-4"],+ object_permission: { search_tools: ["tool-a"], vector_stores: ["vs-1"] },+ });++ const openEditor = async (user: ReturnType<typeof userEvent.setup>) => {+ vi.mocked(networking.teamInfoCall).mockResolvedValue(storedTeam());+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: {}, team_id: "123" } as any);++ renderWithProviders(<TeamInfoView {...props} />);+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));+ await user.click(screen.getByRole("tab", { name: "Settings" }));+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));+ await screen.findByLabelText("Team Name");+ };++ const save = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole("button", { name: /save changes/i }));+ await waitFor(() => expect(networking.teamUpdateCall).toHaveBeenCalled());+ return vi.mocked(networking.teamUpdateCall).mock.calls[0][1] as Record<string, unknown>;+ };++ const wireBody = (payload: Record<string, unknown>) => JSON.parse(JSON.stringify(payload)) as Record<string, unknown>;++ const alwaysSent = {+ team_id: "123",+ team_alias: "Test Team",+ models: ["gpt-4"],+ tpm_limit: 1000,+ rpm_limit: 1000,+ model_tpm_limit: {},+ model_rpm_limit: {},+ max_budget: 100,+ soft_budget: null,+ budget_duration: "1d",+ metadata: {+ allowed_passthrough_routes: [],+ guardrails: [],+ opted_out_global_guardrails: [],+ disable_global_guardrails: false,+ soft_budget_alerting_emails: [],+ },+ access_group_ids: [],+ };++ const mcpPermissions = {+ mcp_servers: [],+ mcp_access_groups: [],+ mcp_tool_permissions: {},+ mcp_toolsets: [],+ vector_stores: ["vs-1"],+ };++ it("leaves every team member key out of the request body for an untouched save with both sections closed", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ const payload = await save(user);++ expect(payload).toStrictEqual({+ ...alwaysSent,+ team_member_budget_duration: undefined,+ object_permission: mcpPermissions,+ });+ expect(wireBody(payload)).toStrictEqual({+ ...alwaysSent,+ object_permission: mcpPermissions,+ });+ });++ it("resends every stored value once both sections are opened", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ await user.click(screen.getByText("Team Member Settings"));+ await screen.findByLabelText("Default Budget (USD)");+ await user.click(screen.getByText("Search Tool Settings"));+ await screen.findByPlaceholderText("Select search tools (optional, empty = all allowed)");++ const payload = await save(user);++ const expected = {+ ...alwaysSent,+ team_member_budget_duration: "30d",+ team_member_budget: 42,+ team_member_tpm_limit: 11,+ team_member_rpm_limit: 22,+ default_team_member_models: ["gpt-4"],+ object_permission: { ...mcpPermissions, search_tools: ["tool-a"] },+ };+ expect(payload).toStrictEqual(expected);+ expect(wireBody(payload)).toStrictEqual(expected);+ });++ it("carries every typed value to the update payload at the type and shape antd sends today", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ const alias = screen.getByLabelText("Team Name");+ await user.clear(alias);+ await user.type(alias, "Renamed Team");++ const softBudget = screen.getByLabelText("Soft Budget (USD)");+ await user.clear(softBudget);+ await user.type(softBudget, "9.5");++ const emails = screen.getByLabelText(/Soft Budget Alerting Emails/);+ await user.clear(emails);+ await user.type(emails, "[email protected], [email protected] ");++ const tpm = screen.getByLabelText("Tokens per minute Limit (TPM)");+ await user.clear(tpm);+ await user.type(tpm, "555");++ const payload = await save(user);++ expect(payload.team_alias).toBe("Renamed Team");+ expect(payload.soft_budget).toBe("9.5");+ expect(payload.tpm_limit).toBe("555");+ expect((payload.metadata as Record<string, unknown>).soft_budget_alerting_emails).toStrictEqual([+ "[email protected]",+ "[email protected]",+ ]);+ });++ it("builds model_tpm_limit and model_rpm_limit from the model-specific rate limit rows", async () => {+ const user = userEvent.setup({ delay: null });+ vi.mocked(networking.teamInfoCall).mockResolvedValue(+ createMockTeamData({+ models: ["gpt-4"],+ max_budget: 100,+ budget_duration: "1d",+ tpm_limit: 1000,+ rpm_limit: 1000,+ object_permission: { vector_stores: ["vs-1"] },+ metadata: { model_tpm_limit: { "gpt-4": 30 }, model_rpm_limit: { "gpt-4": 40 } },+ }),+ );+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: {}, team_id: "123" } as any);++ renderWithProviders(<TeamInfoView {...props} />);+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));+ await user.click(screen.getByRole("tab", { name: "Settings" }));+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));+ await screen.findByLabelText("Team Name");++ const payload = await save(user);++ expect(payload.model_tpm_limit).toStrictEqual({ "gpt-4": 30 });+ expect(payload.model_rpm_limit).toStrictEqual({ "gpt-4": 40 });+ });++ it("keeps a team member budget edited before the section is collapsed and resends it on reopen", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ await user.click(screen.getByText("Team Member Settings"));+ const budgetInput = await screen.findByLabelText("Default Budget (USD)");+ await user.clear(budgetInput);+ await user.type(budgetInput, "77");++ await user.click(screen.getByText("Team Member Settings"));+ await waitFor(() => expect(screen.queryByLabelText("Default Budget (USD)")).not.toBeInTheDocument());++ await user.click(screen.getByText("Team Member Settings"));+ expect(await screen.findByLabelText("Default Budget (USD)")).toHaveValue(77);++ const payload = await save(user);+ expect(payload.team_member_budget).toBe(77);+ });++ it("sends no team member key at all when the section is collapsed again after an edit", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ await user.click(screen.getByText("Team Member Settings"));+ const budgetInput = await screen.findByLabelText("Default Budget (USD)");+ await user.clear(budgetInput);+ await user.type(budgetInput, "77");++ await user.click(screen.getByText("Team Member Settings"));+ await waitFor(() => expect(screen.queryByLabelText("Default Budget (USD)")).not.toBeInTheDocument());++ const payload = await save(user);++ expect(Object.keys(wireBody(payload)).filter((key) => key.startsWith("team_member"))).toEqual([]);+ expect(wireBody(payload)).not.toHaveProperty("default_team_member_models");+ });++ it("puts the global guardrails back on the team when the kill switch is turned off again", async () => {+ const user = userEvent.setup({ delay: null });+ testQueryClient.clear();+ vi.mocked(networking.getGuardrailsList).mockResolvedValue({+ guardrails: [+ { guardrail_name: "always-on", litellm_params: { default_on: true } },+ { guardrail_name: "opt-in", litellm_params: { default_on: false } },+ ],+ });+ vi.mocked(networking.teamInfoCall).mockResolvedValue(+ createMockTeamData({+ models: ["gpt-4"],+ metadata: { guardrails: ["opt-in"], disable_global_guardrails: true },+ }),+ );+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: {}, team_id: "123" } as any);++ renderWithProviders(<TeamInfoView {...props} premiumUser={true} />);+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));+ await user.click(screen.getByRole("tab", { name: "Settings" }));+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));+ await screen.findByLabelText("Team Name");++ expect(screen.queryAllByLabelText("always-on")).toHaveLength(0);++ await user.click(screen.getByRole("switch", { name: /Disable all global guardrails/ }));++ expect(await screen.findAllByLabelText("always-on")).toHaveLength(1);++ const payload = await save(user);++ expect(payload.metadata).toStrictEqual(+ expect.objectContaining({+ guardrails: ["opt-in"],+ opted_out_global_guardrails: [],+ disable_global_guardrails: false,+ }),+ );+ });++ it("sends a typed model rate limit as a number", async () => {+ const user = userEvent.setup({ delay: null });+ vi.mocked(networking.teamInfoCall).mockResolvedValue(+ createMockTeamData({ models: ["gpt-4"], metadata: { model_tpm_limit: { "gpt-4": 30 } } }),+ );+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: {}, team_id: "123" } as any);++ renderWithProviders(<TeamInfoView {...props} />);+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));+ await user.click(screen.getByRole("tab", { name: "Settings" }));+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));+ await screen.findByLabelText("Team Name");++ const rpmInput = await screen.findByPlaceholderText("RPM Limit");+ await user.clear(rpmInput);+ await user.type(rpmInput, "45");++ const payload = await save(user);++ expect(payload.model_rpm_limit).toStrictEqual({ "gpt-4": 45 });+ expect(payload.model_tpm_limit).toStrictEqual({ "gpt-4": 30 });+ });++ it("leaves stored policies out of the update body for a caller without the viewPolicies capability", async () => {+ const user = userEvent.setup({ delay: null });+ can.mockReturnValue(false);+ vi.mocked(networking.teamInfoCall).mockResolvedValue(createMockTeamData({ models: ["gpt-4"], policies: ["pci"] }));+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: {}, team_id: "123" } as any);++ renderWithProviders(<TeamInfoView {...props} />);+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));+ await user.click(screen.getByRole("tab", { name: "Settings" }));+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));+ await screen.findByLabelText("Team Name");++ const payload = await save(user);++ expect(payload).toHaveProperty("team_alias");+ expect(wireBody(payload)).not.toHaveProperty("policies");+ });++ it("blocks the save on an empty team name and names the rule", async () => {+ const user = userEvent.setup({ delay: null });+ await openEditor(user);++ await user.clear(screen.getByLabelText("Team Name"));+ await user.click(screen.getByRole("button", { name: /save changes/i }));++ expect(await screen.findByText("Please input a team name")).toBeInTheDocument();+ expect(networking.teamUpdateCall).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.tsxindex 0f1d22e5b9a..c20f47a155b 100644--- a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamInfo.tsx@@ -20,24 +20,32 @@ import { formatNumberWithCommas } from "@/utils/dataUtils";import { mapEmptyStringToNull } from "@/utils/keyUpdateUtils";import type { ObjectPermission } from "@/components/object_permission_types";import { isProxyAdminRole } from "@/utils/roles";-import {- EditOutlined,- GlobalOutlined,- InfoCircleOutlined,- MinusCircleOutlined,- PlusOutlined,- SaveOutlined,-} from "@ant-design/icons";+import { EditOutlined, InfoCircleOutlined } from "@ant-design/icons";import { ArrowLeftIcon } from "@heroicons/react/outline";import { StatusBadge, type StatusTone } from "@/components/shared/table_cells/status_badge";import { Badge } from "@/components/ui/badge";import { Card } from "@/components/ui/card";import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";import { Input as UIInput } from "@/components/ui/input";-import { Button, Form, Input, InputNumber, Select, Space, Switch, Tabs, Tag, Tooltip } from "antd";+import { Button as UIButton } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { TooltipProvider } from "@/components/ui/tooltip";+import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";+import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/shared/form/field";+import { FormField } from "@/components/shared/form/FormField";+import { labelWithDocsHint, labelWithHint } from "@/components/shared/form/LabelWithHint";+import { MultiSelect } from "@/components/shared/MultiSelect";+import { SearchSelect } from "@/components/shared/SearchSelect";+import { useZodForm } from "@/lib/forms/useZodForm";+import { TagsInput } from "@/app/(dashboard)/guardrails/_components/content_filter/TagsInput";+import { Button, Tabs, Tooltip } from "antd";import { toast } from "@/lib/toast";-import { CheckIcon, ChevronDown, CopyIcon } from "lucide-react";+import { CheckIcon, ChevronDown, CircleMinus, CopyIcon, Plus, Save } from "lucide-react";import React, { useEffect, useMemo, useState } from "react";+import { useFieldArray } from "react-hook-form";+import { z } from "zod/v4";+import GuardrailsSelect from "./GuardrailsSelect";import { copyToClipboard as utilCopyToClipboard } from "../../utils/dataUtils";import AccessGroupSelector from "../common_components/AccessGroupSelector";import BudgetDurationDropdown from "../common_components/budget_duration_dropdown";@@ -49,6 +57,7 @@ import {} from "./teamModelAccess";import MetadataKeyValueFields, {metadataObjectToPairs,+ metadataPairsSchema,metadataPairsToObject,} from "../common_components/MetadataKeyValueFields";import { useTeamMetadataSchema } from "@/app/(dashboard)/hooks/teams/useTeamMetadataSchema";@@ -63,7 +72,7 @@ import LoggingSettingsView from "../logging_settings_view";import MCPServerSelector from "../mcp_server_management/MCPServerSelector";import MCPToolPermissions from "../mcp_server_management/MCPToolPermissions";import { ModelSelect } from "../ModelSelect/ModelSelect";-import { estimateRules, estimateTooltips } from "../templates/estimatedOutputTokens";+import { estimateChecks, estimateTooltips } from "../templates/estimatedOutputTokens";import ObjectPermissionsView from "../object_permissions_view";import NumericalInput from "../shared/numerical_input";import VectorStoreSelector from "../vector_store_management/VectorStoreSelector";@@ -182,6 +191,201 @@ export interface TeamInfoProps {premiumUser?: boolean;}+const SUPPRESSED_BY_DESCRIPTION = "";++const numericInputSchema = z.union([z.string(), z.number()]).nullish();++const teamUpdateFieldsSchema = z.object({+ team_alias: z.string().min(1, "Please input a team name"),+ models: z.array(z.string()).optional(),+ max_budget: numericInputSchema,+ soft_budget: numericInputSchema,+ soft_budget_alerting_emails: z.union([z.string(), z.array(z.string())]).optional(),+ default_team_member_models: z.array(z.string()).optional(),+ team_member_budget: numericInputSchema,+ team_member_budget_duration: z.string().nullish(),+ team_member_key_duration: z.string().optional(),+ team_member_tpm_limit: numericInputSchema,+ team_member_rpm_limit: numericInputSchema,+ budget_duration: z.string().nullish(),+ tpm_limit: numericInputSchema,+ rpm_limit: numericInputSchema,+ modelLimits: z+ .array(+ z.object({+ model: z.string().min(1, "Missing model"),+ tpm: z.number().nullish(),+ rpm: z.number().nullish(),+ }),+ )+ .superRefine((rows, ctx) => {+ rows.forEach((row, index) => {+ if (row.model && rows.filter((other) => other.model === row.model).length > 1) {+ ctx.addIssue({ code: "custom", message: "Duplicate model", path: [index, "model"] });+ }+ if (row.model && row.tpm == null && row.rpm == null) {+ ctx.addIssue({ code: "custom", message: "Set at least one of TPM or RPM", path: [index, "tpm"] });+ }+ });+ }),+ default_estimated_output_tokens: numericInputSchema.refine(+ estimateChecks.positive.isValid,+ estimateChecks.positive.message,+ ),+ default_estimated_output_tokens_per_model: z+ .string()+ .optional()+ .refine(estimateChecks.perModel.isValid, estimateChecks.perModel.message),+ guardrails: z.array(z.string()).optional(),+ disable_global_guardrails: z.boolean().optional(),+ policies: z.array(z.string()).optional(),+ access_group_ids: z.array(z.string()).optional(),+ vector_stores: z.array(z.string()).optional(),+ allowed_passthrough_routes: z.array(z.string()).optional(),+ mcp_servers_and_groups: z+ .object({+ servers: z.array(z.string()),+ accessGroups: z.array(z.string()),+ toolsets: z.array(z.string()).optional(),+ })+ .optional(),+ mcp_tool_permissions: z.record(z.string(), z.array(z.string())).optional(),+ agents_and_groups: z.object({ agents: z.array(z.string()), accessGroups: z.array(z.string()) }).optional(),+ object_permission_search_tools: z.array(z.string()).optional(),+ organization_id: z.string().nullish(),+ logging_settings: z.array(z.unknown()).optional(),+ secret_manager_settings: z.string().optional(),+ metadata: metadataPairsSchema.optional(),+});++type TeamUpdateFormValues = z.infer<typeof teamUpdateFieldsSchema>;++type TeamInfoRecord = TeamData["team_info"] & { team_member_key_duration?: string };++const TEAM_MEMBER_SETTINGS_FIELDS = [+ "default_team_member_models",+ "team_member_budget",+ "team_member_budget_duration",+ "team_member_key_duration",+ "team_member_tpm_limit",+ "team_member_rpm_limit",+] as const;+const SEARCH_TOOL_SETTINGS_FIELDS = ["object_permission_search_tools"] as const;++const EMPTY_TEAM_UPDATE_VALUES: TeamUpdateFormValues = {+ team_alias: "",+ models: [],+ max_budget: undefined,+ soft_budget: undefined,+ soft_budget_alerting_emails: "",+ default_team_member_models: [],+ team_member_budget: undefined,+ team_member_budget_duration: undefined,+ team_member_key_duration: undefined,+ team_member_tpm_limit: undefined,+ team_member_rpm_limit: undefined,+ budget_duration: undefined,+ tpm_limit: undefined,+ rpm_limit: undefined,+ modelLimits: [],+ default_estimated_output_tokens: undefined,+ default_estimated_output_tokens_per_model: "",+ guardrails: [],+ disable_global_guardrails: false,+ policies: [],+ access_group_ids: [],+ vector_stores: [],+ allowed_passthrough_routes: [],+ mcp_servers_and_groups: { servers: [], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: {},+ agents_and_groups: { agents: [], accessGroups: [] },+ object_permission_search_tools: [],+ organization_id: null,+ logging_settings: [],+ secret_manager_settings: "",+ metadata: [],+};++const computeEffectiveGuardrails = (info: TeamInfoRecord, globalGuardrailNames: ReadonlySet<string>): string[] => {+ const optedOutGlobals = new Set<string>(+ Array.isArray(info.metadata?.opted_out_global_guardrails) ? info.metadata.opted_out_global_guardrails : [],+ );+ const nonGlobalOptIns: string[] = (Array.isArray(info.metadata?.guardrails) ? info.metadata.guardrails : []).filter(+ (name: string) => !globalGuardrailNames.has(name),+ );+ return info.metadata?.disable_global_guardrails === true+ ? nonGlobalOptIns+ : [...Array.from(globalGuardrailNames).filter((name) => !optedOutGlobals.has(name)), ...nonGlobalOptIns];+};++const toTeamFormValues = (info: TeamInfoRecord, effectiveGuardrails: string[]): TeamUpdateFormValues => ({+ team_alias: info.team_alias,+ models: info.models,+ max_budget: info.max_budget,+ soft_budget: info.soft_budget,+ soft_budget_alerting_emails: Array.isArray(info.metadata?.soft_budget_alerting_emails)+ ? info.metadata.soft_budget_alerting_emails.join(", ")+ : "",+ default_team_member_models: info.default_team_member_models || [],+ team_member_budget: info.team_member_budget_table?.max_budget,+ team_member_budget_duration: info.team_member_budget_table?.budget_duration,+ team_member_key_duration: info.team_member_key_duration,+ team_member_tpm_limit: info.team_member_budget_table?.tpm_limit,+ team_member_rpm_limit: info.team_member_budget_table?.rpm_limit,+ budget_duration: info.budget_duration,+ tpm_limit: info.tpm_limit,+ rpm_limit: info.rpm_limit,+ modelLimits: Array.from(+ new Set([+ ...Object.keys(info.metadata?.model_tpm_limit ?? {}),+ ...Object.keys(info.metadata?.model_rpm_limit ?? {}),+ ]),+ ).map((model) => ({+ model,+ tpm: info.metadata?.model_tpm_limit?.[model],+ rpm: info.metadata?.model_rpm_limit?.[model],+ })),+ default_estimated_output_tokens: info.metadata?.default_estimated_output_tokens,+ default_estimated_output_tokens_per_model: info.metadata?.default_estimated_output_tokens_per_model+ ? JSON.stringify(info.metadata.default_estimated_output_tokens_per_model)+ : "",+ guardrails: effectiveGuardrails,+ disable_global_guardrails: info.metadata?.disable_global_guardrails || false,+ policies: info.policies || [],+ access_group_ids: info.access_group_ids || [],+ vector_stores: info.object_permission?.vector_stores || [],+ allowed_passthrough_routes: info.metadata?.allowed_passthrough_routes || [],+ mcp_servers_and_groups: {+ servers: info.object_permission?.mcp_servers || [],+ accessGroups: info.object_permission?.mcp_access_groups || [],+ toolsets: info.object_permission?.mcp_toolsets || [],+ },+ mcp_tool_permissions: info.object_permission?.mcp_tool_permissions || {},+ agents_and_groups: {+ agents: info.object_permission?.agents || [],+ accessGroups: info.object_permission?.agent_access_groups || [],+ },+ object_permission_search_tools: info.object_permission?.search_tools || [],+ organization_id: info.organization_id,+ logging_settings: info.metadata?.logging || [],+ secret_manager_settings: info.metadata?.secret_manager_settings+ ? JSON.stringify(info.metadata.secret_manager_settings, null, 2)+ : "",+ metadata: metadataObjectToPairs(info.metadata, UI_MANAGED_METADATA_KEYS),+});++const isParsableJson = (value: string | undefined): boolean => {+ if (!value) {+ return true;+ }+ try {+ JSON.parse(value);+ return true;+ } catch {+ return false;+ }+};+const TeamInfoView: React.FC<TeamInfoProps> = ({teamId,onClose,@@ -194,10 +398,26 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({premiumUser = false,onUpdate,}) => {+ const teamUpdateSchema = useMemo(+ () =>+ teamUpdateFieldsSchema.superRefine((values, ctx) => {+ if (!isParsableJson(values.secret_manager_settings)) {+ ctx.addIssue({ code: "custom", message: SUPPRESSED_BY_DESCRIPTION, path: ["secret_manager_settings"] });+ }+ }),+ [],+ );const [teamData, setTeamData] = useState<TeamData | null>(null);const [loading, setLoading] = useState(true);const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);- const [form] = Form.useForm();+ const form = useZodForm(teamUpdateSchema, { defaultValues: EMPTY_TEAM_UPDATE_VALUES });+ const {+ fields: modelLimitRows,+ append: appendModelLimit,+ remove: removeModelLimit,+ } = useFieldArray({ control: form.control, name: "modelLimits" });+ const [teamMemberSettingsOpen, setTeamMemberSettingsOpen] = useState(false);+ const [searchToolSettingsOpen, setSearchToolSettingsOpen] = useState(false);const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false);const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(null);const [isEditing, setIsEditing] = useState(false);@@ -232,15 +452,17 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({// Models currently selected in the team edit form, used to scope the per-model// rate limit dropdown to models this team actually has access to.- const selectedModelsInForm = Form.useWatch("models", form) as string[] | undefined;- const killSwitchOn = Form.useWatch("disable_global_guardrails", form) as boolean | undefined;+ const watchedModels = form.watch("models");+ const killSwitchOn = form.watch("disable_global_guardrails");+ const watchedMcpSelection = form.watch("mcp_servers_and_groups");+ const watchedToolPermissions = form.watch("mcp_tool_permissions");const availableRateLimitModels = useMemo(() => {- const selected = selectedModelsInForm ?? teamData?.team_info?.models ?? [];+ const selected = watchedModels ?? teamData?.team_info?.models ?? [];if (selected.includes("all-proxy-models") || selected.includes("all-team-models")) {return userModels;}return unfurlWildcardModelsInList(selected, userModels);- }, [selectedModelsInForm, teamData, userModels]);+ }, [watchedModels, teamData, userModels]);const isTeamAdminFromTeamData = useMemo(() =>@@ -254,6 +476,37 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({const visibleTabs = useMemo(() => getTeamInfoVisibleTabs(canEditTeam), [canEditTeam]);const defaultTabKey = useMemo(() => getTeamInfoDefaultTab(editTeam, canEditTeam), [editTeam, canEditTeam]);+ const teamFormValues = (): TeamUpdateFormValues => {+ const info = teamData?.team_info;+ return info+ ? toTeamFormValues(info, computeEffectiveGuardrails(info, globalGuardrailNames))+ : EMPTY_TEAM_UPDATE_VALUES;+ };++ const startEditing = () => {+ form.reset(teamFormValues());+ setTeamMemberSettingsOpen(false);+ setSearchToolSettingsOpen(false);+ setIsEditing(true);+ };++ const applyKillSwitchToGuardrails = (checked: boolean) => {+ const current = form.getValues("guardrails") ?? [];+ const nonGlobals = current.filter((name) => !globalGuardrailNames.has(name));+ form.setValue("guardrails", checked ? nonGlobals : [...Array.from(globalGuardrailNames), ...nonGlobals]);+ };++ const mountedUpdateValues = (values: TeamUpdateFormValues): Record<string, unknown> => {+ const unmounted = new Set<string>([+ ...(teamMemberSettingsOpen ? [] : TEAM_MEMBER_SETTINGS_FIELDS),+ ...(canViewPolicies ? [] : ["policies"]),+ ...(searchToolSettingsOpen ? [] : SEARCH_TOOL_SETTINGS_FIELDS),+ ]);+ return Object.fromEntries(Object.entries(values).filter(([key]) => !unmounted.has(key)));+ };++ const onTeamUpdateSubmit = (values: TeamUpdateFormValues) => handleTeamUpdate(mountedUpdateValues(values));+const fetchTeamInfo = async () => {try {setLoading(true);@@ -354,7 +607,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({toast.success("Team member added successfully");setIsAddMemberModalVisible(false);- form.resetFields();+ form.reset(teamFormValues());// Fetch updated team infoconst updatedTeamData = await teamInfoCall(accessToken, teamId);@@ -678,47 +931,11 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({const { team_info: info } = teamData;const initialKillSwitchOn = info.metadata?.disable_global_guardrails === true;- const optedOutGlobals = new Set<string>(- Array.isArray(info.metadata?.opted_out_global_guardrails) ? info.metadata.opted_out_global_guardrails : [],- );- const nonGlobalOptIns: string[] = (Array.isArray(info.metadata?.guardrails) ? info.metadata.guardrails : []).filter(- (n: string) => !globalGuardrailNames.has(n),- );- const effectiveGuardrails: string[] = initialKillSwitchOn- ? nonGlobalOptIns- : [...Array.from(globalGuardrailNames).filter((n) => !optedOutGlobals.has(n)), ...nonGlobalOptIns];const allGuardrails: GuardrailListItem[] = guardrailsData?.guardrails ?? [];const globalGuardrails = allGuardrails.filter((g) => g.litellm_params?.default_on);const otherGuardrails = allGuardrails.filter((g) => !g.litellm_params?.default_on);- const renderGuardrailOption = (g: GuardrailListItem, disabled: boolean) => (- <Select.Option key={g.guardrail_name} value={g.guardrail_name} label={g.guardrail_name} disabled={disabled}>- {g.guardrail_name}- </Select.Option>- );-- const preventTagMouseDown = (e: React.MouseEvent) => {- e.preventDefault();- e.stopPropagation();- };-- const renderGuardrailTag = ({ label, value, closable, onClose }: any) => {- const isGlobal = globalGuardrailNames.has(value);- return (- <Tag- color="blue"- closable={closable}- onClose={onClose}- onMouseDown={preventTagMouseDown}- style={{ marginInlineEnd: 4 }}- >- {isGlobal && <GlobalOutlined style={{ marginInlineEnd: 4 }} aria-label="Global guardrail" />}- {label}- </Tag>- );- };-const copyToClipboard = async (text: string, key: string) => {const success = await utilCopyToClipboard(text);if (success) {@@ -935,7 +1152,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({icon={<EditOutlined className="h-4 w-4" />}onClick={() => {setTeamModelAliases(info.litellm_model_table?.model_aliases ?? {});- setIsEditing(true);+ startEditing();}}>Edit Settings@@ -946,600 +1163,608 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({{isEditing && isGuardrailsLoading ? (<div className="p-4">Loading...</div>) : isEditing ? (- <Form- form={form}- onFinish={handleTeamUpdate}- onValuesChange={(changedValues) => {- if ("disable_global_guardrails" in changedValues) {- const checked = changedValues.disable_global_guardrails === true;- const current = (form.getFieldValue("guardrails") || []) as string[];- const nonGlobals = current.filter((n) => !globalGuardrailNames.has(n));- form.setFieldValue(- "guardrails",- checked ? nonGlobals : [...Array.from(globalGuardrailNames), ...nonGlobals],- );- }- }}- initialValues={{- ...info,- team_alias: info.team_alias,- models: info.models,- tpm_limit: info.tpm_limit,- rpm_limit: info.rpm_limit,- object_permission_search_tools: info.object_permission?.search_tools || [],- modelLimits: Array.from(- new Set([- ...Object.keys(info.metadata?.model_tpm_limit ?? {}),- ...Object.keys(info.metadata?.model_rpm_limit ?? {}),- ]),- ).map((model) => ({- model,- tpm: info.metadata?.model_tpm_limit?.[model],- rpm: info.metadata?.model_rpm_limit?.[model],- })),- max_budget: info.max_budget,- soft_budget: info.soft_budget,- budget_duration: info.budget_duration,- team_member_tpm_limit: info.team_member_budget_table?.tpm_limit,- team_member_rpm_limit: info.team_member_budget_table?.rpm_limit,- team_member_budget: info.team_member_budget_table?.max_budget,- team_member_budget_duration: info.team_member_budget_table?.budget_duration,- guardrails: effectiveGuardrails,- policies: info.policies || [],- disable_global_guardrails: info.metadata?.disable_global_guardrails || false,- soft_budget_alerting_emails: Array.isArray(info.metadata?.soft_budget_alerting_emails)- ? info.metadata.soft_budget_alerting_emails.join(", ")- : "",- default_estimated_output_tokens: info.metadata?.default_estimated_output_tokens,- default_estimated_output_tokens_per_model: info.metadata- ?.default_estimated_output_tokens_per_model- ? JSON.stringify(info.metadata.default_estimated_output_tokens_per_model)- : "",- metadata: metadataObjectToPairs(info.metadata, UI_MANAGED_METADATA_KEYS),- logging_settings: info.metadata?.logging || [],- secret_manager_settings: info.metadata?.secret_manager_settings- ? JSON.stringify(info.metadata.secret_manager_settings, null, 2)- : "",- organization_id: info.organization_id,- vector_stores: info.object_permission?.vector_stores || [],- mcp_servers: info.object_permission?.mcp_servers || [],- mcp_access_groups: info.object_permission?.mcp_access_groups || [],- mcp_servers_and_groups: {- servers: info.object_permission?.mcp_servers || [],- accessGroups: info.object_permission?.mcp_access_groups || [],- toolsets: info.object_permission?.mcp_toolsets || [],- },- mcp_tool_permissions: info.object_permission?.mcp_tool_permissions || {},- agents_and_groups: {- agents: info.object_permission?.agents || [],- accessGroups: info.object_permission?.agent_access_groups || [],- },- access_group_ids: info.access_group_ids || [],- default_team_member_models: info.default_team_member_models || [],- allowed_passthrough_routes: info.metadata?.allowed_passthrough_routes || [],- }}- layout="vertical"- >- <Form.Item- label="Team Name"- name="team_alias"- rules={[{ required: true, message: "Please input a team name" }]}- >- <Input type="" />- </Form.Item>+ <TooltipProvider>+ <form onSubmit={(event) => void form.handleSubmit(onTeamUpdateSubmit)(event)}>+ <FieldGroup>+ <FormField control={form.control} name="team_alias" label="Team Name">+ {({ ref, value, ...field }) => <UIInput {...field} ref={ref} value={value ?? ""} />}+ </FormField>++ <FormField+ control={form.control}+ name="models"+ label="Models"+ description="Leave empty to grant no models directly. The team keeps any models granted through its access groups"+ >+ {({ id, value, onChange }) => (+ <ModelSelect+ id={id}+ value={value ?? []}+ onChange={onChange}+ teamID={teamId}+ organizationID={teamData?.team_info?.organization_id || undefined}+ options={{+ includeSpecialOptions: true,+ includeUserModels: !teamData?.team_info?.organization_id,+ showAllProxyModelsOverride:+ isProxyAdminRole(userRole) && !teamData?.team_info?.organization_id,+ }}+ context="team"+ dataTestId="models-select"+ />+ )}+ </FormField>- <Form.Item- label="Models"- name="models"- extra="Leave empty to grant no models directly. The team keeps any models granted through its access groups"- >- <ModelSelect- value={form.getFieldValue("models") || []}- onChange={(values) => form.setFieldValue("models", values)}- teamID={teamId}- organizationID={teamData?.team_info?.organization_id || undefined}- options={{- includeSpecialOptions: true,- includeUserModels: !teamData?.team_info?.organization_id,- showAllProxyModelsOverride:- isProxyAdminRole(userRole) && !teamData?.team_info?.organization_id,- }}- context="team"- dataTestId="models-select"- />- </Form.Item>-- <Form.Item- label={- <span>- Model Aliases{" "}- <Tooltip title="Map a custom alias to an underlying model. Team members can call the alias in API requests instead of the real model name.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- >- <ModelAliasManager- accessToken={accessToken || ""}- initialModelAliases={teamModelAliases}- onAliasUpdate={setTeamModelAliases}- showExampleConfig={false}- />- </Form.Item>-- <Form.Item label="Max Budget (USD)" name="max_budget">- <NumericalInput step={0.01} precision={2} style={{ width: "100%" }} />- </Form.Item>-- <Form.Item label="Soft Budget (USD)" name="soft_budget">- <NumericalInput step={0.01} precision={2} style={{ width: "100%" }} />- </Form.Item>-- <Form.Item- label="Soft Budget Alerting Emails"- name="soft_budget_alerting_emails"- tooltip="Comma-separated email addresses to receive alerts when the soft budget is reached"- >- <Input placeholder="[email protected], [email protected]" />- </Form.Item>-- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Team Member Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <p className="text-xs text-gray-500 mb-4">- Optional defaults applied when members join this team. All fields can be overridden per- member.- </p>- <Form.Item- label={- <span>- Default Model Access{" "}- <Tooltip title="Optional. If set, new members can only access these models by default. Must be a subset of the team's models above. Leave empty to give all members access to all team models.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="default_team_member_models"+ <Field>+ <FieldLabel>+ {labelWithHint(+ "Model Aliases",+ "Map a custom alias to an underlying model. Team members can call the alias in API requests instead of the real model name.",+ )}+ </FieldLabel>+ <ModelAliasManager+ accessToken={accessToken || ""}+ initialModelAliases={teamModelAliases}+ onAliasUpdate={setTeamModelAliases}+ showExampleConfig={false}+ />+ </Field>++ <FormField control={form.control} name="max_budget" label="Max Budget (USD)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={0.01} precision={2} />+ )}+ </FormField>++ <FormField control={form.control} name="soft_budget" label="Soft Budget (USD)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={0.01} precision={2} />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="soft_budget_alerting_emails"+ label={labelWithHint(+ "Soft Budget Alerting Emails",+ "Comma-separated email addresses to receive alerts when the soft budget is reached",+ )}>- <Form.Item noStyle shouldUpdate={(prev, cur) => prev.models !== cur.models}>- {({ getFieldValue }) => {- const teamModels = getFieldValue("models") || info.models || [];- return (- <Select- mode="multiple"- placeholder="Leave empty — all team models accessible to every member"- value={form.getFieldValue("default_team_member_models") || []}- onChange={(values) => form.setFieldValue("default_team_member_models", values)}- options={teamModels.map((m: string) => ({ label: m, value: m }))}- />- );- }}- </Form.Item>- </Form.Item>- <Form.Item- label="Default Budget (USD)"- name="team_member_budget"- tooltip="Default spend budget for each member in this team."+ {({ ref, value, ...field }) => (+ <UIInput+ {...field}+ ref={ref}+ value={typeof value === "string" ? value : ""}+ placeholder="[email protected], [email protected]"+ />+ )}+ </FormField>++ <Collapsible+ open={teamMemberSettingsOpen}+ onOpenChange={setTeamMemberSettingsOpen}+ className="mt-4 mb-4 overflow-hidden rounded-lg border">- <NumericalInput step={0.01} precision={2} style={{ width: "100%" }} />- </Form.Item>- <Form.Item label="Default Budget Duration" name="team_member_budget_duration">- <DurationSelect- onChange={(value) => form.setFieldValue("team_member_budget_duration", value)}- value={form.getFieldValue("team_member_budget_duration")}+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Team Member Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <p className="mb-4 text-xs text-gray-500">+ Optional defaults applied when members join this team. All fields can be overridden per+ member.+ </p>+ <FieldGroup>+ <FormField+ control={form.control}+ name="default_team_member_models"+ label={labelWithHint(+ "Default Model Access",+ "Optional. If set, new members can only access these models by default. Must be a subset of the team's models above. Leave empty to give all members access to all team models.",+ )}+ >+ {({ id, value, onChange }) => (+ <MultiSelect+ id={id}+ value={value ?? []}+ onValueChange={onChange}+ options={(watchedModels ?? info.models ?? []).map((model) => ({+ label: model,+ value: model,+ }))}+ placeholder="Leave empty — all team models accessible to every member"+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_budget"+ label={labelWithHint(+ "Default Budget (USD)",+ "Default spend budget for each member in this team.",+ )}+ >+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={0.01} precision={2} />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_budget_duration"+ label="Default Budget Duration"+ >+ {({ value, onChange }) => (+ <DurationSelect value={value ?? undefined} onChange={onChange} />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_key_duration"+ label={labelWithHint(+ "Default Key Duration (eg: 1d, 1mo)",+ "Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",+ )}+ >+ {({ ref, value, ...field }) => (+ <UIInput {...field} ref={ref} value={value ?? ""} placeholder="e.g., 30d" />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_tpm_limit"+ label={labelWithHint(+ "Default TPM Limit",+ "Default tokens per minute limit for each member. Can be overridden per member.",+ )}+ >+ {({ ref, value, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ step={1}+ placeholder="e.g., 1000"+ />+ )}+ </FormField>+ <FormField+ control={form.control}+ name="team_member_rpm_limit"+ label={labelWithHint(+ "Default RPM Limit",+ "Default requests per minute limit for each member. Can be overridden per member.",+ )}+ >+ {({ ref, value, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ step={1}+ placeholder="e.g., 100"+ />+ )}+ </FormField>+ </FieldGroup>+ </CollapsibleContent>+ </Collapsible>++ <FormField control={form.control} name="budget_duration" label="Reset Budget">+ {({ id, value, onChange }) => (+ <BudgetDurationDropdown+ id={id}+ placeholder="Never resets"+ value={value}+ onChange={(next) => onChange(next ?? null)}+ />+ )}+ </FormField>++ <FormField control={form.control} name="tpm_limit" label="Tokens per minute Limit (TPM)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} />+ )}+ </FormField>++ <FormField control={form.control} name="rpm_limit" label="Requests per minute Limit (RPM)">+ {({ ref, value, ...field }) => (+ <NumericalInput {...field} ref={ref} value={value ?? ""} step={1} />+ )}+ </FormField>++ <Field>+ <FieldLabel>Metadata</FieldLabel>+ <MetadataKeyValueFields+ control={form.control}+ getValues={form.getValues}+ name="metadata"+ schemaFields={teamMetadataSchemaFields}+ schemaLoading={isTeamMetadataSchemaLoading}/>- </Form.Item>- <Form.Item- label="Default Key Duration (eg: 1d, 1mo)"- name="team_member_key_duration"- tooltip="Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)"+ <FieldDescription>+ Values are saved as text. Enter JSON for typed values, e.g. 3, true, or {'{"region": "us"}'}+ .+ </FieldDescription>+ </Field>++ <Field>+ <FieldLabel>+ {labelWithHint(+ "Model-Specific Rate Limits",+ "Set per-model TPM/RPM limits that apply across the whole team.",+ )}+ </FieldLabel>+ {modelLimitRows.map((row, index) => (+ <div key={row.id} className="mb-2 flex items-start gap-2">+ <FormField+ control={form.control}+ name={`modelLimits.${index}.model`}+ className="min-w-60"+ >+ {({ id, value, onChange }) => (+ <SearchSelect+ inputId={id}+ value={value ?? ""}+ onValueChange={onChange}+ options={availableRateLimitModels.map((model) => ({+ label: model,+ value: model,+ }))}+ placeholder="Select model"+ />+ )}+ </FormField>+ <FormField control={form.control} name={`modelLimits.${index}.tpm`}>+ {({ ref, value, onChange, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ onChange(event.target.value === "" ? null : Number(event.target.value))+ }+ placeholder="TPM Limit"+ min={0}+ step={1}+ />+ )}+ </FormField>+ <FormField control={form.control} name={`modelLimits.${index}.rpm`}>+ {({ ref, value, onChange, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) =>+ onChange(event.target.value === "" ? null : Number(event.target.value))+ }+ placeholder="RPM Limit"+ min={0}+ step={1}+ />+ )}+ </FormField>+ <UIButton+ type="button"+ variant="ghost"+ size="icon"+ aria-label="Remove model limit"+ className="mt-1 text-destructive"+ onClick={() => removeModelLimit(index)}+ >+ <CircleMinus className="size-4" />+ </UIButton>+ </div>+ ))}+ <UIButton+ type="button"+ variant="outline"+ className="w-full border-dashed"+ onClick={() => appendModelLimit({ model: "", tpm: null, rpm: null })}+ >+ <Plus className="size-4" />+ Add Model Limit+ </UIButton>+ </Field>++ <FormField+ control={form.control}+ name="default_estimated_output_tokens"+ label={labelWithHint("Estimated Output Tokens", teamEstimateTooltip.estimate)}>- <UIInput placeholder="e.g., 30d" />- </Form.Item>- <Form.Item- label="Default TPM Limit"- name="team_member_tpm_limit"- tooltip="Default tokens per minute limit for each member. Can be overridden per member."+ {({ ref, value, ...field }) => (+ <NumericalInput+ {...field}+ ref={ref}+ value={value ?? ""}+ min={1}+ step={1}+ disabled={!canEditTeamEstimates}+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="default_estimated_output_tokens_per_model"+ label={labelWithHint("Estimated Output Tokens Per Model", teamEstimateTooltip.perModel)}>- <NumericalInput step={1} style={{ width: "100%" }} placeholder="e.g., 1000" />- </Form.Item>- <Form.Item- label="Default RPM Limit"- name="team_member_rpm_limit"- tooltip="Default requests per minute limit for each member. Can be overridden per member."+ {({ ref, value, ...field }) => (+ <Textarea+ {...field}+ ref={ref}+ value={value ?? ""}+ rows={4}+ placeholder='{"gpt-4": 4096}'+ disabled={!canEditTeamEstimates}+ />+ )}+ </FormField>++ <Field>+ <FieldLabel>Router Settings</FieldLabel>+ <RouterSettingsAccordion+ ref={routerSettingsRef}+ accessToken={accessToken || ""}+ teamId={teamId}+ value={info.router_settings ? { router_settings: info.router_settings } : undefined}+ />+ </Field>++ <FormField+ control={form.control}+ name="guardrails"+ label={labelWithDocsHint(+ "Guardrails",+ "Select which guardrails apply to this team. Global guardrails are enabled by default, uncheck to opt out. Other guardrails are opt-in.",+ "https://docs.litellm.ai/docs/proxy/guardrails/quick_start",+ )}>- <NumericalInput step={1} style={{ width: "100%" }} placeholder="e.g., 100" />- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Form.Item label="Reset Budget" name="budget_duration">- <BudgetDurationDropdown placeholder="Never resets" />- </Form.Item>-- <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">- <NumericalInput step={1} style={{ width: "100%" }} />- </Form.Item>-- <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">- <NumericalInput step={1} style={{ width: "100%" }} />- </Form.Item>-- <Form.Item- label="Metadata"- help='Values are saved as text. Enter JSON for typed values, e.g. 3, true, or {"region": "us"}.'- >- <MetadataKeyValueFields- form={form}- schemaFields={teamMetadataSchemaFields}- schemaLoading={isTeamMetadataSchemaLoading}- />- </Form.Item>-- <Form.Item- label="Model-Specific Rate Limits"- tooltip="Set per-model TPM/RPM limits that apply across the whole team."- >- <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();- },- },- ]}- style={{ minWidth: 240 }}- >- <Select- showSearch- placeholder="Select model"- allowClear- options={availableRateLimitModels.map((m) => ({- value: m,- label: m,- }))}- />- </Form.Item>- <Form.Item- {...restField}- name={[name, "tpm"]}- rules={[- {- validator: async (_, value) => {- const row = (form.getFieldValue("modelLimits") ?? [])[name] ?? {};- if (row.model && value == null && row.rpm == null) {- return Promise.reject(new Error("Set at least one of TPM or RPM"));- }- return Promise.resolve();- },- },- ]}- >- <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>- </Form.Item>-- <Form.Item- label="Estimated Output Tokens"- name="default_estimated_output_tokens"- tooltip={teamEstimateTooltip.estimate}- rules={[estimateRules.positive]}- >- <NumericalInput min={1} step={1} style={{ width: "100%" }} disabled={!canEditTeamEstimates} />- </Form.Item>-- <Form.Item- label="Estimated Output Tokens Per Model"- name="default_estimated_output_tokens_per_model"- tooltip={teamEstimateTooltip.perModel}- rules={[estimateRules.perModel]}- >- <Input.TextArea rows={4} placeholder='{"gpt-4": 4096}' disabled={!canEditTeamEstimates} />- </Form.Item>-- <Form.Item label="Router Settings">- <RouterSettingsAccordion- ref={routerSettingsRef}- accessToken={accessToken || ""}- teamId={teamId}- value={info.router_settings ? { router_settings: info.router_settings } : undefined}- />- </Form.Item>-- <Form.Item- label={- <span>- Guardrails{" "}- <Tooltip title="Select which guardrails apply to this team. Global guardrails are enabled by default — uncheck to opt out. Other guardrails are opt-in.">- <a- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"- target="_blank"- rel="noopener noreferrer"- onClick={(e) => e.stopPropagation()}- >- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </a>- </Tooltip>- </span>- }- name="guardrails"- >- <Select- mode="multiple"- placeholder="Select guardrails"- optionLabelProp="label"- tagRender={renderGuardrailTag}- >- {globalGuardrails.length > 0 && otherGuardrails.length > 0 ? (- <>- <Select.OptGroup- label={- <>- <GlobalOutlined style={{ marginInlineEnd: 4 }} />- Global- </>- }- >- {globalGuardrails.map((g) => renderGuardrailOption(g, Boolean(killSwitchOn)))}- </Select.OptGroup>- <Select.OptGroup label="Other">- {otherGuardrails.map((g) => renderGuardrailOption(g, false))}- </Select.OptGroup>- </>- ) : (- [- ...globalGuardrails.map((g) => renderGuardrailOption(g, Boolean(killSwitchOn))),- ...otherGuardrails.map((g) => renderGuardrailOption(g, false)),- ]+ {({ id, value, onChange }) => (+ <GuardrailsSelect+ id={id}+ value={value ?? []}+ onValueChange={onChange}+ globalGuardrails={globalGuardrails.map((g) => ({+ name: g.guardrail_name,+ disabled: Boolean(killSwitchOn),+ }))}+ otherGuardrails={otherGuardrails.map((g) => ({+ name: g.guardrail_name,+ disabled: false,+ }))}+ globalGuardrailNames={globalGuardrailNames}+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="disable_global_guardrails"+ label={labelWithHint(+ "Disable all global guardrails",+ "Kill switch: bypass every global guardrail for this team, including any added in the future. For per-guardrail opt-out instead, use the Guardrails dropdown above.",+ )}+ >+ {({ id, value, onChange }) => (+ <Switch+ id={id}+ checked={value === true}+ onCheckedChange={(checked) => {+ onChange(checked);+ applyKillSwitchToGuardrails(checked);+ }}+ />+ )}+ </FormField>++ {canViewPolicies && (+ <FormField+ control={form.control}+ name="policies"+ label={labelWithDocsHint(+ "Policies",+ "Apply policies to this team to control guardrails and other settings",+ "https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",+ )}+ >+ {({ id, value, onChange }) => (+ <TagsInput+ id={id}+ value={value ?? []}+ onValueChange={onChange}+ options={policiesList.map((name) => ({ value: name, label: name }))}+ placeholder="Select or enter policies"+ />+ )}+ </FormField>)}- </Select>- </Form.Item>-- <Form.Item- label={- <span>- Disable all global guardrails{" "}- <Tooltip title="Kill switch: bypass every global guardrail for this team, including any added in the future. For per-guardrail opt-out instead, use the Guardrails dropdown above.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="disable_global_guardrails"- valuePropName="checked"- >- <Switch checkedChildren="Yes" unCheckedChildren="No" />- </Form.Item>- {canViewPolicies && (- <Form.Item- label={- <span>- Policies{" "}- <Tooltip title="Apply policies to this team to control guardrails and other settings">- <a- href="https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies"- target="_blank"- rel="noopener noreferrer"- onClick={(e) => e.stopPropagation()}- >- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </a>- </Tooltip>- </span>- }- name="policies"- >- <Select- mode="tags"- placeholder="Select or enter policies"- options={policiesList.map((name) => ({ value: name, label: name }))}- />- </Form.Item>- )}+ <FormField+ control={form.control}+ name="access_group_ids"+ label={labelWithHint(+ "Access Groups",+ "Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use",+ )}+ >+ {({ value, onChange }) => (+ <AccessGroupSelector+ value={value}+ onChange={onChange}+ placeholder="Select access groups (optional)"+ />+ )}+ </FormField>++ <FormField control={form.control} name="vector_stores" label="Vector Stores">+ {({ value, onChange }) => (+ <VectorStoreSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select vector stores"+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="allowed_passthrough_routes"+ label={+ !premiumUser+ ? labelWithHint(+ "Allowed Pass Through Routes",+ "Premium feature - Upgrade to set allowed pass through routes",+ )+ : !is_proxy_admin+ ? labelWithHint(+ "Allowed Pass Through Routes",+ "Only proxy admins can set allowed pass through routes",+ )+ : "Allowed Pass Through Routes"+ }+ >+ {({ value, onChange }) => (+ <PassThroughRoutesSelector+ value={value}+ onChange={onChange}+ accessToken={accessToken || ""}+ placeholder="Select pass through routes"+ disabled={!premiumUser || !is_proxy_admin}+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="mcp_servers_and_groups"+ label="MCP Servers / Access Groups"+ >+ {({ value, onChange }) => (+ <MCPServerSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select MCP servers or access groups (optional)"+ allowAllProxyMcpServers={is_proxy_admin}+ />+ )}+ </FormField>- <Form.Item- label={- <span>- Access Groups{" "}- <Tooltip title="Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="access_group_ids"- >- <AccessGroupSelector placeholder="Select access groups (optional)" />- </Form.Item>-- <Form.Item label="Vector Stores" name="vector_stores" aria-label="Vector Stores">- <VectorStoreSelector- onChange={(values: string[]) => form.setFieldValue("vector_stores", values)}- value={form.getFieldValue("vector_stores")}- accessToken={accessToken || ""}- placeholder="Select vector stores"- />- </Form.Item>-- <Form.Item- label="Allowed Pass Through Routes"- name="allowed_passthrough_routes"- tooltip={- !premiumUser- ? "Premium feature - Upgrade to set allowed pass through routes"- : !is_proxy_admin- ? "Only proxy admins can set allowed pass through routes"- : undefined- }- >- <PassThroughRoutesSelector- accessToken={accessToken || ""}- placeholder="Select pass through routes"- disabled={!premiumUser || !is_proxy_admin}- />- </Form.Item>-- <Form.Item label="MCP Servers / Access Groups" name="mcp_servers_and_groups">- <MCPServerSelector- onChange={(val) => form.setFieldValue("mcp_servers_and_groups", val)}- value={form.getFieldValue("mcp_servers_and_groups")}- accessToken={accessToken || ""}- placeholder="Select MCP servers or access groups (optional)"- allowAllProxyMcpServers={is_proxy_admin}- />- </Form.Item>-- {/* Hidden field to register mcp_tool_permissions with the form */}- <Form.Item name="mcp_tool_permissions" initialValue={{}} hidden>- <Input type="hidden" />- </Form.Item>-- <Form.Item- noStyle- shouldUpdate={(prevValues, currentValues) =>- prevValues.mcp_servers_and_groups !== currentValues.mcp_servers_and_groups ||- prevValues.mcp_tool_permissions !== currentValues.mcp_tool_permissions- }- >- {() => (<div className="mb-6"><MCPToolPermissionsaccessToken={accessToken || ""}- selectedServers={form.getFieldValue("mcp_servers_and_groups")?.servers || []}- toolPermissions={form.getFieldValue("mcp_tool_permissions") || {}}- onChange={(toolPerms) => form.setFieldsValue({ mcp_tool_permissions: toolPerms })}+ selectedServers={watchedMcpSelection?.servers || []}+ toolPermissions={watchedToolPermissions || {}}+ onChange={(toolPerms) => form.setValue("mcp_tool_permissions", toolPerms)}/></div>- )}- </Form.Item>-- <Form.Item label="Agents / Access Groups" name="agents_and_groups">- <AgentSelector- onChange={(val) => form.setFieldValue("agents_and_groups", val)}- value={form.getFieldValue("agents_and_groups")}- accessToken={accessToken || ""}- placeholder="Select agents or access groups (optional)"- />- </Form.Item>-- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">- <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">- <b>Search Tool Settings</b>- <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />- </CollapsibleTrigger>- <CollapsibleContent className="px-4 pb-3">- <Form.Item- label="Allowed Search Tools"- name="object_permission_search_tools"- tooltip="Select which search tools this team can access. Leave empty to allow all search tools."++ <FormField control={form.control} name="agents_and_groups" label="Agents / Access Groups">+ {({ value, onChange }) => (+ <AgentSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select agents or access groups (optional)"+ />+ )}+ </FormField>++ <Collapsible+ open={searchToolSettingsOpen}+ onOpenChange={setSearchToolSettingsOpen}+ className="mt-4 mb-4 overflow-hidden rounded-lg border">- <SearchToolSelector- onChange={(vals: string[]) => form.setFieldValue("object_permission_search_tools", vals)}- value={form.getFieldValue("object_permission_search_tools")}- accessToken={accessToken || ""}- placeholder="Select search tools (optional, empty = all allowed)"- />- </Form.Item>- </CollapsibleContent>- </Collapsible>-- <Form.Item label="Organization" name="organization_id">- <Select- allowClear- placeholder="Select an organization"- showSearch- optionFilterProp="label"- options={userOrganizations.map((org) => ({- value: org.organization_id,- label: org.organization_alias || org.organization_id,- }))}- />- </Form.Item>-- <Form.Item label="Logging Settings" name="logging_settings">- <EditLoggingSettings- value={form.getFieldValue("logging_settings")}- onChange={(values) => form.setFieldValue("logging_settings", values)}- />- </Form.Item>-- <Form.Item- label="Secret Manager Settings"- name="secret_manager_settings"- help={- premiumUser- ? "Enter secret manager configuration as a JSON object."- : "Premium feature - Upgrade to manage secret manager settings."- }- rules={[- {- validator: async (_, value) => {- if (!value) {- return Promise.resolve();- }- try {- JSON.parse(value);- return Promise.resolve();- } catch (error) {- return Promise.reject(new Error("Please enter valid JSON"));- }- },- },- ]}- >- <Input.TextArea- rows={6}- placeholder='{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}'- disabled={!premiumUser}- />- </Form.Item>-- <div className="sticky z-10 bg-white p-4 pr-0 border-t border-gray-200 -bottom-6 -inset-x-6">- <div className="flex justify-end items-center gap-2">- <Button onClick={() => setIsEditing(false)} disabled={isTeamSaving}>- Cancel- </Button>- <Button- icon={<SaveOutlined className="h-4 w-4" />}- type="primary"- htmlType="submit"- loading={isTeamSaving}+ <CollapsibleTrigger className="group/section flex w-full items-center justify-between px-4 py-3 text-left">+ <b>Search Tool Settings</b>+ <ChevronDown className="size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180" />+ </CollapsibleTrigger>+ <CollapsibleContent className="px-4 pb-3">+ <FormField+ control={form.control}+ name="object_permission_search_tools"+ label={labelWithHint(+ "Allowed Search Tools",+ "Select which search tools this team can access. Leave empty to allow all search tools.",+ )}+ >+ {({ value, onChange }) => (+ <SearchToolSelector+ onChange={onChange}+ value={value}+ accessToken={accessToken || ""}+ placeholder="Select search tools (optional, empty = all allowed)"+ />+ )}+ </FormField>+ </CollapsibleContent>+ </Collapsible>++ <FormField control={form.control} name="organization_id" label="Organization">+ {({ id, value, onChange }) => (+ <SearchSelect+ inputId={id}+ value={value ?? ""}+ onValueChange={(next) => onChange(next === "" ? null : next)}+ options={userOrganizations.map((org) => ({+ value: org.organization_id ?? "",+ label: org.organization_alias || org.organization_id || "",+ }))}+ placeholder="Select an organization"+ emptyText="No matching organizations"+ />+ )}+ </FormField>++ <FormField control={form.control} name="logging_settings" label="Logging Settings">+ {({ value, onChange }) => (+ <EditLoggingSettings value={(value as unknown[]) ?? []} onChange={onChange} />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="secret_manager_settings"+ label="Secret Manager Settings"+ description={+ premiumUser+ ? "Enter secret manager configuration as a JSON object."+ : "Premium feature - Upgrade to manage secret manager settings."+ }>- Save Changes- </Button>+ {({ ref, value, ...field }) => (+ <Textarea+ {...field}+ ref={ref}+ value={value ?? ""}+ rows={6}+ placeholder='{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}'+ disabled={!premiumUser}+ />+ )}+ </FormField>+ </FieldGroup>++ <div className="sticky z-10 -inset-x-6 -bottom-6 border-t border-gray-200 bg-white p-4 pr-0">+ <div className="flex items-center justify-end gap-2">+ <UIButton+ type="button"+ variant="outline"+ onClick={() => setIsEditing(false)}+ disabled={isTeamSaving}+ >+ Cancel+ </UIButton>+ <UIButton type="submit" disabled={isTeamSaving}>+ {isTeamSaving ? <UiLoadingSpinner className="size-4" /> : <Save className="size-4" />}+ Save Changes+ </UIButton>+ </div></div>- </div>- </Form>+ </form>+ </TooltipProvider>) : (<div className="space-y-4"><div>