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 key edit form off Ant Design onto react-hook-form (#37398)
yuneng-jiang1bc1a5ed81d8
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 355835eb87c..3f32048cac1 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -2628,15 +2628,6 @@"src/components/templates/key_edit_view.tsx": {"local/filename-pascal-case": {"count": 1- },- "local/no-complex-jsx-arrow": {- "count": 2- },- "no-nested-ternary": {- "count": 2- },- "no-restricted-imports": {- "count": 1}},"src/components/templates/key_info_view.tsx": {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/TagsInput.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/TagsInput.tsxindex 0d799474399..6fb1508497e 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/TagsInput.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/content_filter/TagsInput.tsx@@ -28,6 +28,7 @@ interface TagsInputProps {emptyText?: string;tokenSeparators?: string[];loading?: boolean;+ disabled?: boolean;id?: string;}@@ -48,6 +49,7 @@ export const TagsInput = ({emptyText = "No matching options",tokenSeparators = [],loading = false,+ disabled = false,id,}: TagsInputProps) => {const anchor = useComboboxAnchor();@@ -103,6 +105,7 @@ export const TagsInput = ({itemToStringLabel={(option: TagsInputOption) => option.label}filter={matchesQuery}openOnInputClick+ disabled={disabled || loading}><ComboboxChips render={<div ref={anchor} />} className="min-h-8 py-1 text-sm"><ComboboxValue>diff --git a/ui/litellm-dashboard/src/components/shared/MultiSelect.test.tsx b/ui/litellm-dashboard/src/components/shared/MultiSelect.test.tsxindex 908c22b5d67..6fe2f0fe51c 100644--- a/ui/litellm-dashboard/src/components/shared/MultiSelect.test.tsx+++ b/ui/litellm-dashboard/src/components/shared/MultiSelect.test.tsx@@ -92,4 +92,18 @@ describe("MultiSelect", () => {expect(screen.queryByText('Create "vs-typed"')).not.toBeInTheDocument();expect(await screen.findByText("No options found")).toBeInTheDocument();});++ it("marks a disabled option as disabled and refuses to select it", async () => {+ const { onValueChange, input } = renderMultiSelect({+ options: [OPTIONS[0], { ...OPTIONS[1], disabled: true }],+ });++ await openPopup(input);+ const disabledOption = screen.getByRole("option", { name: /beta-kb/ });+ expect(disabledOption).toHaveAttribute("aria-disabled", "true");++ await userEvent.click(disabledOption);++ expect(onValueChange).not.toHaveBeenCalled();+ });});diff --git a/ui/litellm-dashboard/src/components/shared/MultiSelect.tsx b/ui/litellm-dashboard/src/components/shared/MultiSelect.tsxindex 49695b56d44..c60a019db06 100644--- a/ui/litellm-dashboard/src/components/shared/MultiSelect.tsx+++ b/ui/litellm-dashboard/src/components/shared/MultiSelect.tsx@@ -18,6 +18,7 @@ export interface MultiSelectOption {label: string;value: string;description?: string;+ disabled?: boolean;}interface MultiSelectProps {@@ -116,7 +117,7 @@ export function MultiSelect({<ComboboxEmpty>{emptyText}</ComboboxEmpty><ComboboxList>{(option: MultiSelectOption) => (- <ComboboxItem key={option.value} value={option}>+ <ComboboxItem key={option.value} value={option} disabled={option.disabled}><span className="min-w-0"><span className="block truncate">{option.label}</span>{option.description && (diff --git a/ui/litellm-dashboard/src/components/templates/KeyEditViewControls.tsx b/ui/litellm-dashboard/src/components/templates/KeyEditViewControls.tsxnew file mode 100644index 00000000000..1ab7b9be52c--- /dev/null+++ b/ui/litellm-dashboard/src/components/templates/KeyEditViewControls.tsx@@ -0,0 +1,50 @@+import React from "react";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { CircleHelp } from "lucide-react";++export const labelWithHint = (label: React.ReactNode, hint: string): React.ReactNode => (+ <>+ {label}+ <Tooltip>+ <TooltipTrigger render={<CircleHelp className="size-3.5 shrink-0 cursor-help text-muted-foreground" />} />+ <TooltipContent className="max-w-xs">{hint}</TooltipContent>+ </Tooltip>+ </>+);++const KEY_TYPE_OPTIONS = [+ { value: "default", label: "Full Access", hint: "Can call all routes (AI APIs, Management, and read-only)" },+ { value: "llm_api", label: "AI APIs", hint: "Can call only AI API routes (chat/completions, embeddings, etc.)" },+ { value: "management", label: "Management", hint: "Can call only management routes (user/team/key management)" },+];++export const KeyTypeSelect = ({+ id,+ value,+ onChange,+}: {+ id: string;+ value: string;+ onChange: (value: string) => void;+}) => (+ <Select+ items={Object.fromEntries(KEY_TYPE_OPTIONS.map((option) => [option.value, option.label]))}+ value={value}+ onValueChange={(next: string | null) => next != null && onChange(next)}+ >+ <SelectTrigger id={id} className="w-full">+ <SelectValue placeholder="Select key type" />+ </SelectTrigger>+ <SelectContent>+ {KEY_TYPE_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <div className="py-1">+ <div className="font-medium">{option.label}</div>+ <div className="mt-0.5 text-[11px] text-muted-foreground">{option.hint}</div>+ </div>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+);diff --git a/ui/litellm-dashboard/src/components/templates/estimatedOutputTokens.ts b/ui/litellm-dashboard/src/components/templates/estimatedOutputTokens.tsindex 842d7d2bb68..0982bbcc750 100644--- a/ui/litellm-dashboard/src/components/templates/estimatedOutputTokens.ts+++ b/ui/litellm-dashboard/src/components/templates/estimatedOutputTokens.ts@@ -44,25 +44,28 @@ export const estimateTooltips = (canEdit: boolean, entity: "key" | "team" = "key: ADMIN_ONLY_TOOLTIP,});-export const estimateRules = {+export const estimateChecks = {perModel: {- validator: (_: unknown, value: unknown) => {- if (typeof value !== "string" || value.trim() === "") return Promise.resolve();- return parsePerModelEstimates(value) === null- ? Promise.reject(new Error(INVALID_PER_MODEL_MESSAGE))- : Promise.resolve();- },+ isValid: (value: unknown): boolean =>+ typeof value !== "string" || value.trim() === "" ? true : parsePerModelEstimates(value) !== null,+ message: INVALID_PER_MODEL_MESSAGE,},positive: {- validator: (_: unknown, value: unknown) => {- if (value === "" || value === null || value === undefined) return Promise.resolve();- return isPositiveInteger(Number(value))- ? Promise.resolve()- : Promise.reject(new Error("Enter a positive integer"));- },+ isValid: (value: unknown): boolean =>+ value === "" || value === null || value === undefined ? true : isPositiveInteger(Number(value)),+ message: "Enter a positive integer",},};+const asAntdRule = ({ isValid, message }: { isValid: (value: unknown) => boolean; message: string }) => ({+ validator: (_: unknown, value: unknown) => (isValid(value) ? Promise.resolve() : Promise.reject(new Error(message))),+});++export const estimateRules = {+ perModel: asAntdRule(estimateChecks.perModel),+ positive: asAntdRule(estimateChecks.positive),+};+export const withNormalizedEstimates = <T extends FormValues>(values: T): FormValues => {const { [ESTIMATE_FIELD]: estimate, [PER_MODEL_FIELD]: perModel, ...rest } = values;diff --git a/ui/litellm-dashboard/src/components/templates/keyEditFieldNormalizers.ts b/ui/litellm-dashboard/src/components/templates/keyEditFieldNormalizers.tsindex ee8d9ebf685..c8b8a689dae 100644--- a/ui/litellm-dashboard/src/components/templates/keyEditFieldNormalizers.ts+++ b/ui/litellm-dashboard/src/components/templates/keyEditFieldNormalizers.ts@@ -17,3 +17,29 @@ export const keyTypeFromRoutes = (allowedRoutes: string[] | null | undefined): sif (allowedRoutes.includes("info_routes")) return "read_only";return "default";};++export const parseAllowedRoutes = (value: unknown): string[] =>+ typeof value === "string" && value.trim() !== ""+ ? value+ .split(",")+ .map((route) => route.trim())+ .filter((route) => route.length > 0)+ : [];++export const modelSentinelOptions = (+ keyTeamId: string | null | undefined,+ teamLoaded: boolean,+): { value: string; label: string }[] => {+ if (keyTeamId == null) return [{ value: "all-proxy-models", label: "All Proxy Models" }];+ return teamLoaded ? [{ value: "all-team-models", label: "All Team Models" }] : [];+};++export const currentValuePlaceholder = (+ premiumUser: boolean,+ current: unknown,+ premiumHint: string,+ emptyHint: string,+): string => {+ if (!premiumUser) return premiumHint;+ return Array.isArray(current) && current.length > 0 ? `Current: ${current.join(", ")}` : emptyHint;+};diff --git a/ui/litellm-dashboard/src/components/templates/keyEditFormValues.test.ts b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.test.tsnew file mode 100644index 00000000000..948ed659cd5--- /dev/null+++ b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { keyEditFormSchema } from "./keyEditFormValues";++const parse = (values: Record<string, unknown>) => keyEditFormSchema.safeParse(values);++describe("keyEditFormSchema", () => {+ it("accepts an empty form", () => {+ expect(parse({}).success).toBe(true);+ });++ it("rejects a fractional estimated output tokens value", () => {+ expect(parse({ default_estimated_output_tokens: "12.5" }).success).toBe(false);+ });++ it("rejects a zero or negative estimated output tokens value", () => {+ expect(parse({ default_estimated_output_tokens: "-5" }).success).toBe(false);+ expect(parse({ default_estimated_output_tokens: 0 }).success).toBe(false);+ });++ it("accepts a blank or absent estimated output tokens value", () => {+ expect(parse({ default_estimated_output_tokens: "" }).success).toBe(true);+ expect(parse({ default_estimated_output_tokens: null }).success).toBe(true);+ });++ it("rejects a per-model estimate that is not a JSON object of positive integers", () => {+ expect(parse({ default_estimated_output_tokens_per_model: "not json" }).success).toBe(false);+ expect(parse({ default_estimated_output_tokens_per_model: '{"gpt-4": 0}' }).success).toBe(false);+ });++ it("accepts a per-model estimate that is a JSON object of positive integers", () => {+ expect(parse({ default_estimated_output_tokens_per_model: '{"gpt-4": 4096}' }).success).toBe(true);+ });+});diff --git a/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.tsnew file mode 100644index 00000000000..ad90610b732--- /dev/null+++ b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts@@ -0,0 +1,203 @@+import { z } from "zod/v4";++import { KeyResponse } from "../key_team_helpers/key_list";+import { extractLoggingSettings, formatMetadataForDisplay, stripTagsFromMetadata } from "../key_info_utils";+import { mapInternalToDisplayNames } from "../callback_info_helpers";+import { estimateChecks, estimateFields } from "./estimatedOutputTokens";+import { canonicalBudgetDuration } from "./keyEditFieldNormalizers";++export interface McpServersAndGroups {+ servers: string[];+ accessGroups: string[];+ toolsets: string[];+}++export interface AgentsAndGroups {+ agents: string[];+ accessGroups: string[];+}++export interface KeyEditFormValues {+ key_alias?: string;+ models?: string[];+ allowed_routes?: string;+ max_budget?: number | string | null;+ budget_duration?: string | null;+ tpm_limit?: number | string | null;+ tpm_limit_type?: string | null;+ rpm_limit?: number | string | null;+ rpm_limit_type?: string | null;+ throttle_on_budget_exceeded?: boolean;+ enable_prompt_caching?: boolean;+ max_parallel_requests?: number | string | null;+ model_tpm_limit?: string;+ model_rpm_limit?: string;+ default_estimated_output_tokens?: number | string | null;+ default_estimated_output_tokens_per_model?: string;+ guardrails?: string[];+ disable_global_guardrails?: boolean;+ policies?: string[];+ tags?: string[];+ prompts?: string[];+ access_group_ids?: string[];+ allowed_passthrough_routes?: string[];+ vector_stores?: string[];+ mcp_servers_and_groups?: McpServersAndGroups;+ mcp_tool_permissions?: Record<string, string[]>;+ agents_and_groups?: AgentsAndGroups;+ organization_id?: string | null;+ team_id?: string | null;+ logging_settings?: unknown[];+ metadata?: string;+ duration?: string | null;+ token?: string;+ disabled_callbacks?: string[];+ auto_rotate?: boolean;+ rotation_interval?: string;+}++const readMetadata = (keyData: KeyResponse, key: string): unknown =>+ keyData.metadata != null && typeof keyData.metadata === "object"+ ? (keyData.metadata as Record<string, unknown>)[key]+ : undefined;++export const toKeyEditFormValues = (keyData: KeyResponse): KeyEditFormValues => ({+ key_alias: keyData.key_alias,+ models: keyData.models,+ allowed_routes:+ Array.isArray(keyData.allowed_routes) && keyData.allowed_routes.length > 0 ? keyData.allowed_routes.join(", ") : "",+ max_budget: keyData.max_budget,+ budget_duration: canonicalBudgetDuration(keyData.budget_duration),+ tpm_limit: keyData.tpm_limit,+ tpm_limit_type: (keyData as { tpm_limit_type?: string | null }).tpm_limit_type ?? null,+ rpm_limit: keyData.rpm_limit,+ rpm_limit_type: (keyData as { rpm_limit_type?: string | null }).rpm_limit_type ?? null,+ throttle_on_budget_exceeded: Boolean(readMetadata(keyData, "throttle_on_budget_exceeded")),+ enable_prompt_caching: Boolean(readMetadata(keyData, "enable_prompt_caching")),+ max_parallel_requests: keyData.max_parallel_requests,+ model_tpm_limit: (keyData as { model_tpm_limit?: string }).model_tpm_limit,+ model_rpm_limit: (keyData as { model_rpm_limit?: string }).model_rpm_limit,+ ...(estimateFields(keyData.metadata as Record<string, unknown> | null | undefined) as {+ default_estimated_output_tokens?: number | string | null;+ default_estimated_output_tokens_per_model?: string;+ }),+ guardrails: readMetadata(keyData, "guardrails") as string[] | undefined,+ disable_global_guardrails: Boolean(readMetadata(keyData, "disable_global_guardrails")),+ policies: (keyData as { policies?: string[] }).policies,+ tags: readMetadata(keyData, "tags") as string[] | undefined,+ prompts: readMetadata(keyData, "prompts") as string[] | undefined,+ access_group_ids: keyData.access_group_ids || [],+ allowed_passthrough_routes: (keyData as { allowed_passthrough_routes?: string[] }).allowed_passthrough_routes,+ vector_stores: keyData.object_permission?.vector_stores || [],+ mcp_servers_and_groups: {+ servers: keyData.object_permission?.mcp_servers || [],+ accessGroups: keyData.object_permission?.mcp_access_groups || [],+ toolsets: keyData.object_permission?.mcp_toolsets || [],+ },+ mcp_tool_permissions: keyData.object_permission?.mcp_tool_permissions || {},+ agents_and_groups: {+ agents: keyData.object_permission?.agents || [],+ accessGroups: keyData.object_permission?.agent_access_groups || [],+ },+ organization_id: keyData.organization_id,+ team_id: keyData.team_id,+ logging_settings: extractLoggingSettings(keyData.metadata),+ metadata: formatMetadataForDisplay(stripTagsFromMetadata(keyData.metadata)),+ duration: (keyData as { duration?: string }).duration ?? "",+ token: keyData.token || keyData.token_id,+ disabled_callbacks: Array.isArray(readMetadata(keyData, "litellm_disabled_callbacks"))+ ? mapInternalToDisplayNames(readMetadata(keyData, "litellm_disabled_callbacks") as string[])+ : [],+ auto_rotate: keyData.auto_rotate || false,+ rotation_interval: keyData.rotation_interval,+});++export const keyEditFormSchema = z.object({+ key_alias: z.custom<string | undefined>(),+ models: z.custom<string[] | undefined>(),+ allowed_routes: z.custom<string | undefined>(),+ max_budget: z.custom<number | string | null | undefined>(),+ budget_duration: z.custom<string | null | undefined>(),+ tpm_limit: z.custom<number | string | null | undefined>(),+ tpm_limit_type: z.custom<string | null | undefined>(),+ rpm_limit: z.custom<number | string | null | undefined>(),+ rpm_limit_type: z.custom<string | null | undefined>(),+ throttle_on_budget_exceeded: z.custom<boolean | undefined>(),+ enable_prompt_caching: z.custom<boolean | undefined>(),+ max_parallel_requests: z.custom<number | string | null | undefined>(),+ model_tpm_limit: z.custom<string | undefined>(),+ model_rpm_limit: z.custom<string | undefined>(),+ default_estimated_output_tokens: z+ .custom<number | string | null | undefined>()+ .refine(estimateChecks.positive.isValid, estimateChecks.positive.message),+ default_estimated_output_tokens_per_model: z+ .custom<string | undefined>()+ .refine(estimateChecks.perModel.isValid, estimateChecks.perModel.message),+ guardrails: z.custom<string[] | undefined>(),+ disable_global_guardrails: z.custom<boolean | undefined>(),+ policies: z.custom<string[] | undefined>(),+ tags: z.custom<string[] | undefined>(),+ prompts: z.custom<string[] | undefined>(),+ access_group_ids: z.custom<string[] | undefined>(),+ allowed_passthrough_routes: z.custom<string[] | undefined>(),+ vector_stores: z.custom<string[] | undefined>(),+ mcp_servers_and_groups: z.custom<McpServersAndGroups | undefined>(),+ mcp_tool_permissions: z.custom<Record<string, string[]> | undefined>(),+ agents_and_groups: z.custom<AgentsAndGroups | undefined>(),+ organization_id: z.custom<string | null | undefined>(),+ team_id: z.custom<string | null | undefined>(),+ logging_settings: z.custom<unknown[] | undefined>(),+ metadata: z.custom<string | undefined>(),+ duration: z.custom<string | null | undefined>(),+ token: z.custom<string | undefined>(),+ disabled_callbacks: z.custom<string[] | undefined>(),+ auto_rotate: z.custom<boolean | undefined>(),+ rotation_interval: z.custom<string | undefined>(),+});++export interface MountedFieldGates {+ canViewPolicies: boolean;+ canViewPrompts: boolean;+}++export const toSubmittedValues = (+ values: KeyEditFormValues,+ { canViewPolicies, canViewPrompts }: MountedFieldGates,+): Record<string, unknown> => ({+ key_alias: values.key_alias,+ models: values.models,+ allowed_routes: values.allowed_routes,+ max_budget: values.max_budget,+ budget_duration: values.budget_duration,+ tpm_limit: values.tpm_limit,+ tpm_limit_type: values.tpm_limit_type,+ rpm_limit: values.rpm_limit,+ rpm_limit_type: values.rpm_limit_type,+ throttle_on_budget_exceeded: values.throttle_on_budget_exceeded,+ enable_prompt_caching: values.enable_prompt_caching,+ max_parallel_requests: values.max_parallel_requests,+ model_tpm_limit: values.model_tpm_limit,+ model_rpm_limit: values.model_rpm_limit,+ default_estimated_output_tokens: values.default_estimated_output_tokens,+ default_estimated_output_tokens_per_model: values.default_estimated_output_tokens_per_model,+ guardrails: values.guardrails,+ disable_global_guardrails: values.disable_global_guardrails,+ ...(canViewPolicies ? { policies: values.policies } : {}),+ tags: values.tags,+ ...(canViewPrompts ? { prompts: values.prompts } : {}),+ access_group_ids: values.access_group_ids,+ allowed_passthrough_routes: values.allowed_passthrough_routes,+ vector_stores: values.vector_stores,+ mcp_servers_and_groups: values.mcp_servers_and_groups,+ mcp_tool_permissions: values.mcp_tool_permissions,+ agents_and_groups: values.agents_and_groups,+ organization_id: values.organization_id,+ team_id: values.team_id,+ logging_settings: values.logging_settings,+ metadata: values.metadata,+ duration: values.duration,+ token: values.token,+ disabled_callbacks: values.disabled_callbacks,+ auto_rotate: values.auto_rotate,+ rotation_interval: values.rotation_interval,+});diff --git a/ui/litellm-dashboard/src/components/templates/key_edit_view.test.tsx b/ui/litellm-dashboard/src/components/templates/key_edit_view.test.tsxindex 4a3fd50b379..1f4d3cf9128 100644--- a/ui/litellm-dashboard/src/components/templates/key_edit_view.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_edit_view.test.tsx@@ -3,7 +3,13 @@ import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { renderWithProviders } from "../../../tests/test-utils";import { KeyResponse } from "../key_team_helpers/key_list";-import { getPoliciesList, getPromptsList, modelAvailableCall } from "../networking";+import {+ getPassThroughEndpointsCall,+ getPoliciesList,+ getPromptsList,+ modelAvailableCall,+ vectorStoreListCall,+} from "../networking";import { KeyEditView } from "./key_edit_view";const can = vi.fn();@@ -98,6 +104,36 @@ vi.mock("@/app/(dashboard)/hooks/accessGroups/useAccessGroups", () => ({}),}));+vi.mock("../mcp_server_management/MCPServerSelector", () => ({+ default: ({+ value,+ onChange,+ }: {+ value?: { servers?: string[]; accessGroups?: string[]; toolsets?: string[] };+ onChange?: (v: { servers: string[]; accessGroups: string[]; toolsets: string[] }) => void;+ }) => (+ <button+ type="button"+ data-testid="mcp-server-selector"+ onClick={() => onChange?.({ servers: ["mcp-1"], accessGroups: [], toolsets: value?.toolsets ?? [] })}+ >+ pick mcp server+ </button>+ ),+}));++vi.mock("../agent_management/AgentSelector", () => ({+ default: ({ onChange }: { onChange?: (v: { agents: string[]; accessGroups: string[] }) => void }) => (+ <button+ type="button"+ data-testid="agent-selector"+ onClick={() => onChange?.({ agents: ["agent-1"], accessGroups: [] })}+ >+ pick agent+ </button>+ ),+}));+vi.mock("../common_components/AccessGroupSelector", () => ({default: ({ value = [], onChange }: { value?: string[]; onChange?: (v: string[]) => void }) => (<input@@ -108,24 +144,12 @@ vi.mock("../common_components/AccessGroupSelector", () => ({),}));-/* eslint-disable local/no-antd-class-selectors -- the "Key Type" and "Models" Form.Items wrap a noStyle nested item, so antd renders a label with no associated control and there is no accessible query for these selects */-const antdSelectorFor = (label: HTMLElement): Element =>- label.closest(".ant-form-item")!.querySelector(".ant-select-selector")!;-/* eslint-enable local/no-antd-class-selectors */--const visibleOptions = (): HTMLElement[] =>- // eslint-disable-next-line local/no-antd-class-selectors -- antd puts role="option" only on a hidden mirror list; the visible, clickable options carry no role or accessible name- Array.from(document.querySelectorAll<HTMLElement>(".ant-select-item-option"));+const visibleOptions = (): HTMLElement[] => screen.queryAllByRole("option");-const isOptionDisabled = (option: HTMLElement): boolean =>- // eslint-disable-next-line local/no-antd-class-selectors -- antd signals option disabled state only through this class; the rendered options carry no aria-disabled- option.classList.contains("ant-select-item-option-disabled");+const isOptionDisabled = (option: HTMLElement): boolean => option.getAttribute("aria-disabled") === "true";const optionByContent = (label: string): HTMLElement | undefined =>- visibleOptions().find(- // eslint-disable-next-line local/no-antd-class-selectors -- the option's own label text lives in this child node, with no accessible equivalent- (el) => el.querySelector(".ant-select-item-option-content")?.textContent === label,- );+ visibleOptions().find((el) => el.textContent === label);describe("KeyEditView", () => {const MOCK_KEY_DATA: KeyResponse = {@@ -348,6 +372,48 @@ describe("KeyEditView", () => {/>,);+ it("locks the prompts control for a non-premium admin so an unsavable value cannot be entered", async () => {+ renderWithProviders(+ <KeyEditView+ keyData={MOCK_KEY_DATA}+ onCancel={() => {}}+ onSubmit={async () => {}}+ accessToken={"test-token"}+ userID={"test-user"}+ userRole={"Admin"}+ premiumUser={false}+ />,+ );++ const prompts = await screen.findByLabelText(/Prompts/);+ expect(prompts).toBeDisabled();++ await userEvent.type(prompts, "sneaky-prompt{Enter}");++ expect(screen.queryByLabelText("sneaky-prompt")).not.toBeInTheDocument();+ });++ it("leaves the prompts control usable for a premium admin", async () => {+ renderWithProviders(+ <KeyEditView+ keyData={MOCK_KEY_DATA}+ onCancel={() => {}}+ onSubmit={async () => {}}+ accessToken={"test-token"}+ userID={"test-user"}+ userRole={"Admin"}+ premiumUser={true}+ />,+ );++ const prompts = await screen.findByLabelText(/Prompts/);+ expect(prompts).toBeEnabled();++ await userEvent.type(prompts, "allowed-prompt{Enter}");++ expect(await screen.findByLabelText("allowed-prompt")).toBeInTheDocument();+ });+it("should render both fields and load prompts for an admin", async () => {renderAs("Admin");@@ -1162,7 +1228,7 @@ describe("KeyEditView", () => {});// The selected key type label should show "AI APIs" (not "LLM API")- await userEvent.click(antdSelectorFor(screen.getByText("Key Type")));+ await userEvent.click(screen.getByLabelText("Key Type"));await waitFor(() => {// Verify "AI APIs" appears as an option label@@ -1310,8 +1376,8 @@ describe("KeyEditView", () => {});describe("models dropdown team gating", () => {- const openModelsDropdown = () => {- fireEvent.mouseDown(antdSelectorFor(screen.getByText("Models", { selector: "label" })));+ const openModelsDropdown = async () => {+ await userEvent.click(screen.getByLabelText("Models"));};it("should offer all-proxy-models but not all-team-models for a teamless key", async () => {@@ -1331,7 +1397,7 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();await waitFor(() => {expect(screen.getAllByText("gpt-4").length).toBeGreaterThan(0);@@ -1362,7 +1428,7 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();await waitFor(() => {expect(screen.getAllByText("team-model-1").length).toBeGreaterThan(0);@@ -1393,7 +1459,7 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();expect(screen.queryAllByText("All Team Models")).toHaveLength(0);expect(screen.queryAllByText("All Proxy Models")).toHaveLength(0);@@ -1420,10 +1486,9 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();- const proxyOptionLabels = () =>- Array.from(document.querySelectorAll('[role="option"]')).map((option) => option.getAttribute("aria-label"));+ const proxyOptionLabels = () => visibleOptions().map((option) => option.textContent);await waitFor(() => {expect(proxyOptionLabels()).toContain("gpt-4");@@ -1453,7 +1518,7 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();const clickOption = async (label: string) => {const option = await waitFor(() => {@@ -1466,6 +1531,7 @@ describe("KeyEditView", () => {await clickOption("gpt-4");await clickOption("All Proxy Models");+ await userEvent.keyboard("{Escape}");await userEvent.click(screen.getByRole("button", { name: /save changes/i }));@@ -1492,7 +1558,7 @@ describe("KeyEditView", () => {expect(screen.getByText("Models", { selector: "label" })).toBeInTheDocument();});- openModelsDropdown();+ await openModelsDropdown();const findOption = (label: string) => optionByContent(label);@@ -1535,6 +1601,47 @@ describe("KeyEditView", () => {/>,);+ it("refuses to save an invalid per-model estimate, and saves once it is corrected", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderEditView(MOCK_KEY_DATA, onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });+ const perModel = screen.getByLabelText("Estimated Output Tokens Per Model");++ fireEvent.change(perModel, { target: { value: "not json" } });+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ expect(await screen.findByText(/JSON object of positive integers/)).toBeInTheDocument();+ expect(onSubmitMock).not.toHaveBeenCalled();++ fireEvent.change(perModel, { target: { value: '{"gpt-4": 4096}' } });+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ });++ it("refuses to save a fractional estimate, and saves once it is corrected", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderEditView(MOCK_KEY_DATA, onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });+ const estimate = screen.getByLabelText("Estimated Output Tokens");++ fireEvent.change(estimate, { target: { value: "12.5" } });+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).not.toHaveBeenCalled();+ });++ fireEvent.change(estimate, { target: { value: "2048" } });+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ });+it("loads the estimates from key metadata and resubmits them unchanged", async () => {const onSubmitMock = vi.fn().mockResolvedValue(undefined);renderEditView(@@ -1777,5 +1884,297 @@ describe("KeyEditView", () => {});expect(onSubmitMock.mock.calls[0][0]).toHaveProperty("duration", null);});++ it("carries a typed value from every free-text and numeric control into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ const retype = async (label: RegExp | string, text: string) => {+ const control = screen.getByLabelText(label);+ await userEvent.clear(control);+ await userEvent.type(control, text);+ };++ await retype("Key Alias", "typed-alias");+ await retype("Max Budget (USD)", "12.5");+ await retype("TPM Limit", "111");+ await retype("RPM Limit", "222");+ await retype("Max Parallel Requests", "3");+ await retype("Model TPM Limit", '{{"gpt-4": 7}');+ await retype("Model RPM Limit", '{{"gpt-4": 8}');+ await retype("Metadata", '{{"typed": true}');++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0]).toMatchObject({+ key_alias: "typed-alias",+ max_budget: "12.5",+ tpm_limit: "111",+ rpm_limit: "222",+ max_parallel_requests: "3",+ model_tpm_limit: '{"gpt-4": 7}',+ model_rpm_limit: '{"gpt-4": 8}',+ metadata: '{"typed": true}',+ });+ });++ it("carries every toggle driven off its default into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("switch", { name: /throttle on budget exceeded/i }));+ await userEvent.click(screen.getByRole("switch", { name: /enable prompt caching/i }));+ await userEvent.click(screen.getByRole("switch", { name: /disable global guardrails/i }));++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0]).toMatchObject({+ throttle_on_budget_exceeded: true,+ enable_prompt_caching: true,+ disable_global_guardrails: true,+ });+ });++ it("carries a tag typed into the tags control into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.type(screen.getByLabelText("Tags"), "typed-tag{Enter}");++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].tags).toEqual(["test-tag", "typed-tag"]);+ });++ const pickFromCombobox = async (inputLabel: RegExp | string, optionName: RegExp | string) => {+ await userEvent.click(screen.getByLabelText(inputLabel));+ await userEvent.click(await screen.findByRole("option", { name: optionName }));+ await userEvent.keyboard("{Escape}");+ };++ it("carries a picked guardrail into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await pickFromCombobox("Select guardrails", "guardrail-1");+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].guardrails).toEqual(["guardrail-1"]);+ });++ it("carries a picked policy into the payload", async () => {+ vi.mocked(getPoliciesList).mockResolvedValueOnce({+ policies: [{ policy_name: "policy-1", version_number: 1, version_status: "production" }],+ });+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await pickFromCombobox(/Select policies/, /policy-1/);+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].policies).toEqual(["policy-1"]);+ });++ it("carries a typed prompt into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.type(screen.getByLabelText("Prompts"), "prompt-1{Enter}");+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].prompts).toEqual(["prompt-1"]);+ });++ it("carries the RPM rate limit type into its own payload key", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByLabelText(/RPM Rate Limit Type/));+ await userEvent.click(await screen.findByTitle("Guaranteed throughput"));++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ const payload = onSubmitMock.mock.calls[0][0];+ expect(payload.rpm_limit_type).toBe("guaranteed_throughput");+ expect(payload.tpm_limit_type).toBeNull();+ });++ it("carries a picked vector store into the payload", async () => {+ vi.mocked(vectorStoreListCall).mockResolvedValueOnce({+ data: [{ vector_store_id: "vs-1", vector_store_name: "VS One" }],+ });+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await pickFromCombobox("Select vector stores", /VS One/);+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].vector_stores).toEqual(["vs-1"]);+ });++ it("carries a picked pass through route into the payload", async () => {+ vi.mocked(getPassThroughEndpointsCall).mockResolvedValueOnce({+ endpoints: [{ path: "/bria", methods: ["POST"] }],+ });+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await pickFromCombobox(/allowed pass through routes/, /\/bria/);+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].allowed_passthrough_routes).toEqual(["/bria"]);+ });++ it("carries a picked team into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderWithProviders(+ <KeyEditView+ keyData={MOCK_KEY_DATA}+ teams={[{ team_id: "team-9", team_alias: "Team Nine" }]}+ onCancel={() => {}}+ onSubmit={onSubmitMock}+ accessToken={"test-token"}+ userID={"test-user"}+ userRole={"Admin"}+ premiumUser={true}+ />,+ );+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByLabelText("Team ID"));+ await userEvent.click(await screen.findByRole("option", { name: /Team Nine/ }));++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].team_id).toBe("team-9");+ });++ it("carries a picked MCP server into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: "pick mcp server" }));+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].mcp_servers_and_groups.servers).toEqual(["mcp-1"]);+ });++ it("carries a picked agent into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: "pick agent" }));+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].agents_and_groups.agents).toEqual(["agent-1"]);+ });++ it("carries an added logging integration into the payload", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: /add integration/i }));+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0].logging_settings).toEqual([+ { callback_name: "", callback_type: "success", callback_vars: {} },+ ]);+ });++ it("resends stored budget fallbacks on an untouched save", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock, {+ ...MOCK_KEY_DATA,+ budget_fallbacks: { "gpt-4": ["gpt-4o-mini"] },+ } as KeyResponse);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0]).toHaveProperty("budget_fallbacks", { "gpt-4": ["gpt-4o-mini"] });+ });++ it("omits budget fallbacks entirely for a key that has none", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0]).not.toHaveProperty("budget_fallbacks");+ });++ it("resends the stored per-tag rpm limits on an untouched save", async () => {+ const onSubmitMock = vi.fn().mockResolvedValue(undefined);+ renderForPayload(onSubmitMock, {+ ...MOCK_KEY_DATA,+ metadata: { ...MOCK_KEY_DATA.metadata, tag_rpm_limit: { "test-tag": 7 } },+ } as KeyResponse);+ await screen.findByRole("button", { name: /save changes/i });++ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));++ await waitFor(() => {+ expect(onSubmitMock).toHaveBeenCalled();+ });+ expect(onSubmitMock.mock.calls[0][0]).toHaveProperty("tag_rpm_limit", { "test-tag": 7 });+ });});});diff --git a/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx b/ui/litellm-dashboard/src/components/templates/key_edit_view.tsxindex 25e0992e5b6..de8689b46f6 100644--- a/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx@@ -3,12 +3,16 @@ import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganimport { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects";import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";import PolicySelector from "@/components/policies/PolicySelector";-import { InfoCircleOutlined } from "@ant-design/icons";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { TooltipProvider } from "@/components/ui/tooltip";import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";-import { Form, Input as AntdInput, Select, Switch, Tooltip } from "antd";-import { useEffect, useRef, useState } from "react";+import { Field, FieldGroup, FieldLabel } from "@/components/shared/form/field";+import { FormField } from "@/components/shared/form/FormField";+import React, { useEffect, useRef, useState } from "react";import { hasCapability } from "../../utils/capabilities";import { isProxyAdminRole, rolesWithWriteAccess } from "../../utils/roles";import AgentSelector from "../agent_management/AgentSelector";@@ -21,9 +25,22 @@ import RateLimitTypeFormItem from "../common_components/RateLimitTypeFormItem";import OrganizationDropdown from "../common_components/OrganizationDropdown";import RouterSettingsAccordion, { RouterSettingsAccordionRef } from "../common_components/RouterSettingsAccordion";import { routerSettingsEditorValue, routerSettingsUpdate } from "../common_components/routerSettingsPayload";-import { extractLoggingSettings, formatMetadataForDisplay, stripTagsFromMetadata } from "../key_info_utils";-import { estimateFields, estimateRules, estimateTooltips, withNormalizedEstimates } from "./estimatedOutputTokens";-import { canonicalBudgetDuration, keyTypeFromRoutes } from "./keyEditFieldNormalizers";+import { estimateTooltips, withNormalizedEstimates } from "./estimatedOutputTokens";+import {+ currentValuePlaceholder,+ keyTypeFromRoutes,+ modelSentinelOptions,+ parseAllowedRoutes,+} from "./keyEditFieldNormalizers";+import { KeyTypeSelect, labelWithHint } from "./KeyEditViewControls";+import {+ AgentsAndGroups,+ KeyEditFormValues,+ keyEditFormSchema,+ McpServersAndGroups,+ toKeyEditFormValues,+ toSubmittedValues,+} from "./keyEditFormValues";import { BudgetFallbacksEditor } from "../key_team_helpers/BudgetFallbacksEditor";import { BudgetWindowEntry, BudgetWindowsEditor } from "../key_team_helpers/BudgetWindowsEditor";import {@@ -41,8 +58,11 @@ import { toast } from "@/lib/toast";import { getPromptsList, modelAvailableCall, tagListCall } from "../networking";import { fetchTeamModels } from "../organisms/create_key_button";import NumericalInput from "../shared/numerical_input";+import { MultiSelect } from "../shared/MultiSelect";+import { TagsInput } from "@/app/(dashboard)/guardrails/_components/content_filter/TagsInput";import { Tag } from "../tag_management/types";import EditLoggingSettings from "../team/EditLoggingSettings";+import { useZodForm } from "@/lib/forms/useZodForm";import VectorStoreSelector from "../vector_store_management/VectorStoreSelector";interface KeyEditViewProps {@@ -71,7 +91,9 @@ export function KeyEditView({const canViewPrompts = hasCapability(userRole, "viewPrompts");const canEditEstimates = userRole != null && isProxyAdminRole(userRole);const estimateTooltip = estimateTooltips(canEditEstimates);- const [form] = Form.useForm();+ const form = useZodForm<KeyEditFormValues, KeyEditFormValues>(keyEditFormSchema, {+ defaultValues: toKeyEditFormValues(keyData),+ });const [promptsList, setPromptsList] = useState<string[]>([]);const [tagsList, setTagsList] = useState<Record<string, Tag>>({});const team = teams?.find((team) => team.team_id === keyData.team_id);@@ -96,6 +118,8 @@ export function KeyEditView({keyData.budget_fallbacks && typeof keyData.budget_fallbacks === "object" ? keyData.budget_fallbacks : {},);const routerSettingsRef = useRef<RouterSettingsAccordionRef>(null);+ const keyTypeFieldId = React.useId();+ const projectFieldId = React.useId();const { data: organizations, isLoading: isOrganizationsLoading } = useOrganizations();const { data: projects } = useProjects();const { data: uiSettingsData } = useUISettings();@@ -107,6 +131,13 @@ export function KeyEditView({return project?.project_alias ? `${project.project_alias} (${keyData.project_id})` : keyData.project_id;})();+ const allowedRoutesValue = form.watch("allowed_routes");+ const selectedModels = (form.watch("models") as string[] | undefined) ?? [];+ const allowedRoutes = parseAllowedRoutes(allowedRoutesValue);+ const isModelsDisabled = allowedRoutes.includes("management_routes") || allowedRoutes.includes("info_routes");+ const mcpServersAndGroups = form.watch("mcp_servers_and_groups");+ const mcpToolPermissions = form.watch("mcp_tool_permissions");+useEffect(() => {const fetchModels = async () => {if (!userID || !userRole || !accessToken) return;@@ -143,59 +174,21 @@ export function KeyEditView({// Sync disabled callbacks with form when component mountsuseEffect(() => {- form.setFieldValue("disabled_callbacks", disabledCallbacks);+ form.setValue("disabled_callbacks", disabledCallbacks);}, [form, disabledCallbacks]);- // Set initial form values- const initialValues = {- ...keyData,- token: keyData.token || keyData.token_id,- budget_duration: canonicalBudgetDuration(keyData.budget_duration),- metadata: formatMetadataForDisplay(stripTagsFromMetadata(keyData.metadata)),- guardrails: keyData.metadata?.guardrails,- disable_global_guardrails: keyData.metadata?.disable_global_guardrails || false,- throttle_on_budget_exceeded: keyData.metadata?.throttle_on_budget_exceeded || false,- enable_prompt_caching: keyData.metadata?.enable_prompt_caching || false,- ...estimateFields(keyData.metadata),- prompts: keyData.metadata?.prompts,- tags: keyData.metadata?.tags,- vector_stores: keyData.object_permission?.vector_stores || [],- mcp_servers_and_groups: {- servers: keyData.object_permission?.mcp_servers || [],- accessGroups: keyData.object_permission?.mcp_access_groups || [],- toolsets: keyData.object_permission?.mcp_toolsets || [],- },- mcp_tool_permissions: keyData.object_permission?.mcp_tool_permissions || {},- agents_and_groups: {- agents: keyData.object_permission?.agents || [],- accessGroups: keyData.object_permission?.agent_access_groups || [],- },- logging_settings: extractLoggingSettings(keyData.metadata),- disabled_callbacks: Array.isArray(keyData.metadata?.litellm_disabled_callbacks)- ? mapInternalToDisplayNames(keyData.metadata.litellm_disabled_callbacks)- : [],- access_group_ids: keyData.access_group_ids || [],- auto_rotate: keyData.auto_rotate || false,- ...(keyData.rotation_interval && { rotation_interval: keyData.rotation_interval }),- allowed_routes:- Array.isArray(keyData.allowed_routes) && keyData.allowed_routes.length > 0- ? keyData.allowed_routes.join(", ")- : "",- };-useEffect(() => {- form.setFieldsValue(initialValues);- // eslint-disable-next-line react-hooks/exhaustive-deps -- initialValues is rebuilt from keyData every render; depending on it would re-run each render+ form.reset(toKeyEditFormValues(keyData));}, [keyData, form]);// Sync auto-rotation state with form valuesuseEffect(() => {- form.setFieldValue("auto_rotate", autoRotationEnabled);+ form.setValue("auto_rotate", autoRotationEnabled);}, [autoRotationEnabled, form]);useEffect(() => {if (rotationInterval) {- form.setFieldValue("rotation_interval", rotationInterval);+ form.setValue("rotation_interval", rotationInterval);}}, [rotationInterval, form]);@@ -305,588 +298,577 @@ export function KeyEditView({}};+ const handleOrganizationChange = (setField: (value: string | undefined) => void, orgId: string | undefined) => {+ setField(orgId);+ setSelectedOrganizationId(orgId || null);+ form.setValue("team_id", undefined);+ };++ const handleTeamChange = (setField: (value: string | null) => void, teamId: string | null) => {+ setField(teamId);+ const selectedTeam = teams?.find((t) => t.team_id === teamId) || null;+ if (selectedTeam?.organization_id) {+ setSelectedOrganizationId(selectedTeam.organization_id);+ form.setValue("organization_id", selectedTeam.organization_id);+ } else if (!teamId) {+ setSelectedOrganizationId(null);+ form.setValue("organization_id", undefined);+ }+ };++ const handleDisabledCallbacksChange = (internalValues: string[]) => {+ setDisabledCallbacks(mapInternalToDisplayNames(internalValues));+ form.setValue("disabled_callbacks", internalValues);+ };++ const modelOptions = [+ ...modelSentinelOptions(keyData.team_id, team != null),+ ...availableModels.map((model) => ({+ value: model,+ label: model,+ disabled: hasAllModelsSentinel(selectedModels),+ })),+ ];++ const visibleTeams = selectedOrganizationId+ ? teams?.filter((t) => t.organization_id === selectedOrganizationId)+ : teams;+return (- <Form form={form} onFinish={handleSubmit} initialValues={initialValues} layout="vertical">- <Form.Item label="Key Alias" name="key_alias">- <Input />- </Form.Item>-- <Form.Item label="Models" name="models">- <Form.Item- noStyle- shouldUpdate={(prevValues, currentValues) =>- prevValues.allowed_routes !== currentValues.allowed_routes || prevValues.models !== currentValues.models- }- >- {({ getFieldValue, setFieldValue }) => {- const allowedRoutesValue = getFieldValue("allowed_routes") || "";- // Convert string to array for checking- const allowedRoutes =- typeof allowedRoutesValue === "string" && allowedRoutesValue.trim() !== ""- ? allowedRoutesValue- .split(",")- .map((r: string) => r.trim())- .filter((r: string) => r.length > 0)- : [];- const isDisabled = allowedRoutes.includes("management_routes") || allowedRoutes.includes("info_routes");- const models = getFieldValue("models") || [];-- return (- <>- <Select- mode="multiple"- placeholder="Select models"- style={{ width: "100%" }}- disabled={isDisabled}- value={isDisabled ? [] : models}- onChange={(value) => {- if (value.includes("all-team-models")) {- setFieldValue("models", ["all-team-models"]);- } else if (value.includes("all-proxy-models")) {- setFieldValue("models", ["all-proxy-models"]);- } else {- setFieldValue("models", value);- }- }}- >- {keyData.team_id != null ? (- team != null && <Select.Option value="all-team-models">All Team Models</Select.Option>- ) : (- <Select.Option value="all-proxy-models">All Proxy Models</Select.Option>- )}- {availableModels.map((model) => (- <Select.Option key={model} value={model} disabled={hasAllModelsSentinel(models)}>- {model}- </Select.Option>- ))}- </Select>- {isDisabled && (- <div style={{ fontSize: "11px", color: "#6b7280", marginTop: "2px" }}>- Models field is disabled for this key type- </div>- )}- </>- );- }}- </Form.Item>- </Form.Item>-- <Form.Item label="Key Type">- <Form.Item- noStyle- shouldUpdate={(prevValues, currentValues) => prevValues.allowed_routes !== currentValues.allowed_routes}- >- {({ getFieldValue, setFieldValue }) => {- const allowedRoutesValue = getFieldValue("allowed_routes") || "";- // Convert string to array for keyTypeFromRoutes- const allowedRoutes =- typeof allowedRoutesValue === "string" && allowedRoutesValue.trim() !== ""- ? allowedRoutesValue- .split(",")- .map((r: string) => r.trim())- .filter((r: string) => r.length > 0)- : [];- const keyTypeValue = keyTypeFromRoutes(allowedRoutes);-- return (- <Select- placeholder="Select key type"- style={{ width: "100%" }}- optionLabelProp="label"- value={keyTypeValue}- onChange={(value) => {- switch (value) {- case "default":- setFieldValue("allowed_routes", "");- break;- case "llm_api":- setFieldValue("allowed_routes", "llm_api_routes");- break;- case "management":- setFieldValue("allowed_routes", "management_routes");- setFieldValue("models", []);- break;- }- }}- >- <Select.Option value="default" label="Full Access">- <div style={{ padding: "4px 0" }}>- <div style={{ fontWeight: 500 }}>Full Access</div>- <div style={{ fontSize: "11px", color: "#6b7280", marginTop: "2px" }}>- Can call all routes (AI APIs, Management, and read-only)- </div>- </div>- </Select.Option>- <Select.Option value="llm_api" label="AI APIs">- <div style={{ padding: "4px 0" }}>- <div style={{ fontWeight: 500 }}>AI APIs</div>- <div style={{ fontSize: "11px", color: "#6b7280", marginTop: "2px" }}>- Can call only AI API routes (chat/completions, embeddings, etc.)- </div>- </div>- </Select.Option>- <Select.Option value="management" label="Management">- <div style={{ padding: "4px 0" }}>- <div style={{ fontWeight: 500 }}>Management</div>- <div style={{ fontSize: "11px", color: "#6b7280", marginTop: "2px" }}>- Can call only management routes (user/team/key management)- </div>- </div>- </Select.Option>- </Select>- );- }}- </Form.Item>- </Form.Item>-- <Form.Item- label={- <span>- Allowed Routes{" "}- <Tooltip title="List of allowed routes for the key (comma-separated). Can be specific routes (e.g., '/chat/completions') or route patterns (e.g., 'llm_api_routes', 'management_routes', '/keys/*'). Leave empty to allow all routes.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="allowed_routes"- >- <AntdInput placeholder="Enter allowed routes (comma-separated). Special values: llm_api_routes, management_routes. Examples: llm_api_routes, /chat/completions, /keys/*. Leave empty to allow all routes" />- </Form.Item>-- <Form.Item label="Max Budget (USD)" name="max_budget">- <NumericalInput step={0.01} style={{ width: "100%" }} placeholder="Enter a numerical value" />- </Form.Item>-- <Form.Item label="Reset Budget" name="budget_duration">- <BudgetDurationDropdown placeholder="Never resets" />- </Form.Item>-- <Form.Item- label={- <span>- Budget Windows{" "}- <Tooltip title="Set multiple independent budget windows (e.g., hourly $10 AND monthly $200). Each window tracks spend separately and resets on its own schedule.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- >- <BudgetWindowsEditor value={budgetLimits} onChange={setBudgetLimits} />- </Form.Item>-- <Form.Item- label={- <span>- Budget Fallbacks{" "}- <Tooltip title="When a model exceeds its per-model budget, requests automatically reroute to fallback models instead of failing">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- >- <BudgetFallbacksEditor- value={budgetFallbacks}- onChange={setBudgetFallbacks}- availableModels={availableModels}- />- </Form.Item>-- <Form.Item label="TPM Limit" name="tpm_limit">- <NumericalInput min={0} />- </Form.Item>-- <Form.Item name="tpm_limit_type" initialValue={null} noStyle>- <RateLimitTypeFormItem type="tpm" name="tpm_limit_type" showDetailedDescriptions={false} />- </Form.Item>-- <Form.Item label="RPM Limit" name="rpm_limit">- <NumericalInput min={0} />- </Form.Item>-- <Form.Item name="rpm_limit_type" initialValue={null} noStyle>- <RateLimitTypeFormItem type="rpm" name="rpm_limit_type" showDetailedDescriptions={false} />- </Form.Item>-- <Form.Item- label={- <span>- Throttle on budget exceeded{" "}- <Tooltip title="When this key exceeds its max budget, throttle its TPM/RPM to the globally configured percentage instead of blocking access entirely. Requires budget_exceeded_throttle_percentage in litellm_settings and a TPM/RPM limit on the key.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="throttle_on_budget_exceeded"- valuePropName="checked"- >- <Switch checkedChildren="Yes" unCheckedChildren="No" />- </Form.Item>-- <Form.Item- label={- <span>- Enable Prompt Caching{" "}- <Tooltip title="Automatically add prompt caching breakpoints (cache_control markers) to requests made with this key, cutting input cost on repeated prompts. Applies to Anthropic and Bedrock Claude models; requests that already set their own cache_control markers are left untouched.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="enable_prompt_caching"- valuePropName="checked"- >- <Switch checkedChildren="Yes" unCheckedChildren="No" />- </Form.Item>-- <Form.Item label="Max Parallel Requests" name="max_parallel_requests">- <NumericalInput min={0} />- </Form.Item>-- <Form.Item label="Model TPM Limit" name="model_tpm_limit">- <AntdInput.TextArea rows={4} placeholder='{"gpt-4": 100, "claude-v1": 200}' />- </Form.Item>-- <Form.Item label="Model RPM Limit" name="model_rpm_limit">- <AntdInput.TextArea rows={4} placeholder='{"gpt-4": 100, "claude-v1": 200}' />- </Form.Item>-- <Form.Item- label="Estimated Output Tokens"- name="default_estimated_output_tokens"- tooltip={estimateTooltip.estimate}- rules={[estimateRules.positive]}- >- <NumericalInput min={1} step={1} disabled={!canEditEstimates} />- </Form.Item>-- <Form.Item- label="Estimated Output Tokens Per Model"- name="default_estimated_output_tokens_per_model"- tooltip={estimateTooltip.perModel}- rules={[estimateRules.perModel]}- >- <AntdInput.TextArea rows={4} placeholder='{"gpt-4": 4096}' disabled={!canEditEstimates} />- </Form.Item>-- <Form.Item- label={- <span>- Per-Tag Rate Limits{" "}- <Tooltip title="Scope rate limits to a request tag so each tag (e.g. a cell or group) gets its own RPM counter. Requests without a matching tag fall back to the key-level limit.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- >- <TagRateLimitEditor value={tagRateLimits} onChange={setTagRateLimits} />- </Form.Item>-- <Form.Item label="Guardrails" name="guardrails">- {accessToken && (- <GuardrailSelector- onChange={(v) => {- form.setFieldValue("guardrails", v);- }}- accessToken={accessToken}- disabled={!canEditGuardrails}- />+ <TooltipProvider>+ <form+ onSubmit={form.handleSubmit((values) =>+ handleSubmit(toSubmittedValues(values, { canViewPolicies, canViewPrompts })),)}- </Form.Item>-- <Form.Item- label={- <span>- Disable Global Guardrails{" "}- <Tooltip title="When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="disable_global_guardrails"- valuePropName="checked">- <Switch disabled={!canEditGuardrails} checkedChildren="Yes" unCheckedChildren="No" />- </Form.Item>-- {canViewPolicies && (- <Form.Item- label={- <span>- Policies{" "}- <Tooltip title="Apply policies to this key to control guardrails and other settings">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="policies"- >- {accessToken && (- <PolicySelector- onChange={(v) => {- form.setFieldValue("policies", v);+ <FieldGroup>+ <FormField control={form.control} name="key_alias" label="Key Alias">+ {(field) => <Input {...field} value={(field.value as string | undefined) ?? ""} />}+ </FormField>++ <FormField+ control={form.control}+ name="models"+ label="Models"+ description={isModelsDisabled ? "Models field is disabled for this key type" : undefined}+ >+ {({ value, onChange, id }) => (+ <MultiSelect+ id={id}+ options={modelOptions}+ value={isModelsDisabled ? [] : (value as string[] | undefined) ?? []}+ onValueChange={(next) => {+ if (next.includes("all-team-models")) {+ onChange(["all-team-models"]);+ } else if (next.includes("all-proxy-models")) {+ onChange(["all-proxy-models"]);+ } else {+ onChange(next);+ }+ }}+ disabled={isModelsDisabled}+ placeholder="Select models"+ />+ )}+ </FormField>++ <Field>+ <FieldLabel htmlFor={keyTypeFieldId}>Key Type</FieldLabel>+ <KeyTypeSelect+ id={keyTypeFieldId}+ value={keyTypeFromRoutes(allowedRoutes)}+ onChange={(value) => {+ switch (value) {+ case "default":+ form.setValue("allowed_routes", "");+ break;+ case "llm_api":+ form.setValue("allowed_routes", "llm_api_routes");+ break;+ case "management":+ form.setValue("allowed_routes", "management_routes");+ form.setValue("models", []);+ break;+ }}}- accessToken={accessToken}- disabled={!premiumUser}/>- )}- </Form.Item>- )}-- <Form.Item label="Tags" name="tags">- <Select- mode="tags"- style={{ width: "100%" }}- placeholder="Select or enter tags"- options={Object.values(tagsList).map((tag) => ({- value: tag.name,- label: tag.name,- title: tag.description || tag.name,- }))}- />- </Form.Item>-- {canViewPrompts && (- <Form.Item label="Prompts" name="prompts">- <Tooltip title={!premiumUser ? "Setting prompts by key is a premium feature" : ""} placement="top">- <Select- mode="tags"- style={{ width: "100%" }}- disabled={!premiumUser}- placeholder={- !premiumUser- ? "Premium feature - Upgrade to set prompts by key"- : Array.isArray(keyData.metadata?.prompts) && keyData.metadata.prompts.length > 0- ? `Current: ${keyData.metadata.prompts.join(", ")}`- : "Select or enter prompts"- }- options={promptsList.map((name) => ({ value: name, label: name }))}+ </Field>++ <FormField+ control={form.control}+ name="allowed_routes"+ label={labelWithHint(+ "Allowed Routes",+ "List of allowed routes for the key (comma-separated). Can be specific routes (e.g., '/chat/completions') or route patterns (e.g., 'llm_api_routes', 'management_routes', '/keys/*'). Leave empty to allow all routes.",+ )}+ >+ {(field) => (+ <Input+ {...field}+ value={(field.value as string | undefined) ?? ""}+ placeholder="Enter allowed routes (comma-separated). Special values: llm_api_routes, management_routes. Examples: llm_api_routes, /chat/completions, /keys/*. Leave empty to allow all routes"+ />+ )}+ </FormField>++ <FormField control={form.control} name="max_budget" label="Max Budget (USD)">+ {({ ref: _ref, ...field }) => (+ <NumericalInput+ {...field}+ value={field.value ?? ""}+ step={0.01}+ style={{ width: "100%" }}+ placeholder="Enter a numerical value"+ />+ )}+ </FormField>++ <FormField control={form.control} name="budget_duration" label="Reset Budget">+ {({ value, onChange, id }) => (+ <BudgetDurationDropdown+ id={id}+ value={value as string | null}+ onChange={(next) => onChange(next ?? null)}+ placeholder="Never resets"+ />+ )}+ </FormField>++ <Field>+ <FieldLabel>+ {labelWithHint(+ "Budget Windows",+ "Set multiple independent budget windows (e.g., hourly $10 AND monthly $200). Each window tracks spend separately and resets on its own schedule.",+ )}+ </FieldLabel>+ <BudgetWindowsEditor value={budgetLimits} onChange={setBudgetLimits} />+ </Field>++ <Field>+ <FieldLabel>+ {labelWithHint(+ "Budget Fallbacks",+ "When a model exceeds its per-model budget, requests automatically reroute to fallback models instead of failing",+ )}+ </FieldLabel>+ <BudgetFallbacksEditor+ value={budgetFallbacks}+ onChange={setBudgetFallbacks}+ availableModels={availableModels}/>- </Tooltip>- </Form.Item>- )}-- <Form.Item- label={- <span>- Access Groups{" "}- <Tooltip title="Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="access_group_ids"- >- <AccessGroupSelector placeholder="Select access groups (optional)" />- </Form.Item>+ </Field>++ <FormField control={form.control} name="tpm_limit" label="TPM Limit">+ {({ ref: _ref, ...field }) => <NumericalInput {...field} value={field.value ?? ""} min={0} />}+ </FormField>++ <FormField control={form.control} name="tpm_limit_type">+ {({ value, onChange, id }) => (+ <RateLimitTypeFormItem+ id={id}+ type="tpm"+ name="tpm_limit_type"+ showDetailedDescriptions={false}+ value={value as string | null}+ onChange={onChange}+ />+ )}+ </FormField>++ <FormField control={form.control} name="rpm_limit" label="RPM Limit">+ {({ ref: _ref, ...field }) => <NumericalInput {...field} value={field.value ?? ""} min={0} />}+ </FormField>++ <FormField control={form.control} name="rpm_limit_type">+ {({ value, onChange, id }) => (+ <RateLimitTypeFormItem+ id={id}+ type="rpm"+ name="rpm_limit_type"+ showDetailedDescriptions={false}+ value={value as string | null}+ onChange={onChange}+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="throttle_on_budget_exceeded"+ label={labelWithHint(+ "Throttle on budget exceeded",+ "When this key exceeds its max budget, throttle its TPM/RPM to the globally configured percentage instead of blocking access entirely. Requires budget_exceeded_throttle_percentage in litellm_settings and a TPM/RPM limit on the key.",+ )}+ >+ {({ value, onChange, ref: _ref, ...field }) => (+ <Switch {...field} checked={Boolean(value)} onCheckedChange={onChange} />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="enable_prompt_caching"+ label={labelWithHint(+ "Enable Prompt Caching",+ "Automatically add prompt caching breakpoints (cache_control markers) to requests made with this key, cutting input cost on repeated prompts. Applies to Anthropic and Bedrock Claude models; requests that already set their own cache_control markers are left untouched.",+ )}+ >+ {({ value, onChange, ref: _ref, ...field }) => (+ <Switch {...field} checked={Boolean(value)} onCheckedChange={onChange} />+ )}+ </FormField>++ <FormField control={form.control} name="max_parallel_requests" label="Max Parallel Requests">+ {({ ref: _ref, ...field }) => <NumericalInput {...field} value={field.value ?? ""} min={0} />}+ </FormField>++ <FormField control={form.control} name="model_tpm_limit" label="Model TPM Limit">+ {(field) => (+ <Textarea+ {...field}+ value={(field.value as string | undefined) ?? ""}+ rows={4}+ placeholder='{"gpt-4": 100, "claude-v1": 200}'+ />+ )}+ </FormField>++ <FormField control={form.control} name="model_rpm_limit" label="Model RPM Limit">+ {(field) => (+ <Textarea+ {...field}+ value={(field.value as string | undefined) ?? ""}+ rows={4}+ placeholder='{"gpt-4": 100, "claude-v1": 200}'+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="default_estimated_output_tokens"+ label={labelWithHint("Estimated Output Tokens", estimateTooltip.estimate)}+ >+ {({ ref: _ref, ...field }) => (+ <NumericalInput {...field} value={field.value ?? ""} min={1} step={1} disabled={!canEditEstimates} />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="default_estimated_output_tokens_per_model"+ label={labelWithHint("Estimated Output Tokens Per Model", estimateTooltip.perModel)}+ >+ {(field) => (+ <Textarea+ {...field}+ value={(field.value as string | undefined) ?? ""}+ rows={4}+ placeholder='{"gpt-4": 4096}'+ disabled={!canEditEstimates}+ />+ )}+ </FormField>++ <Field>+ <FieldLabel>+ {labelWithHint(+ "Per-Tag Rate Limits",+ "Scope rate limits to a request tag so each tag (e.g. a cell or group) gets its own RPM counter. Requests without a matching tag fall back to the key-level limit.",+ )}+ </FieldLabel>+ <TagRateLimitEditor value={tagRateLimits} onChange={setTagRateLimits} />+ </Field>++ <FormField control={form.control} name="guardrails" label="Guardrails">+ {({ value, onChange }) =>+ accessToken ? (+ <GuardrailSelector+ onChange={onChange}+ value={value as string[] | undefined}+ accessToken={accessToken}+ disabled={!canEditGuardrails}+ />+ ) : (+ <div />+ )+ }+ </FormField>++ <FormField+ control={form.control}+ name="disable_global_guardrails"+ label={labelWithHint(+ "Disable Global Guardrails",+ "When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",+ )}+ >+ {({ value, onChange, ref: _ref, ...field }) => (+ <Switch {...field} checked={Boolean(value)} onCheckedChange={onChange} disabled={!canEditGuardrails} />+ )}+ </FormField>++ {canViewPolicies && (+ <FormField+ control={form.control}+ name="policies"+ label={labelWithHint("Policies", "Apply policies to this key to control guardrails and other settings")}+ >+ {({ value, onChange }) =>+ accessToken ? (+ <PolicySelector+ onChange={onChange}+ value={value as string[] | undefined}+ accessToken={accessToken}+ disabled={!premiumUser}+ />+ ) : (+ <div />+ )+ }+ </FormField>+ )}++ <FormField control={form.control} name="tags" label="Tags">+ {({ value, onChange, id }) => (+ <TagsInput+ id={id}+ value={(value as string[] | undefined) ?? []}+ onValueChange={onChange}+ options={Object.values(tagsList).map((tag) => ({ value: tag.name, label: tag.name }))}+ placeholder="Select or enter tags"+ />+ )}+ </FormField>++ {canViewPrompts && (+ <FormField+ control={form.control}+ name="prompts"+ label={premiumUser ? "Prompts" : labelWithHint("Prompts", "Setting prompts by key is a premium feature")}+ >+ {({ value, onChange, id }) => (+ <TagsInput+ id={id}+ value={(value as string[] | undefined) ?? []}+ onValueChange={onChange}+ options={promptsList.map((name) => ({ value: name, label: name }))}+ disabled={!premiumUser}+ placeholder={currentValuePlaceholder(+ premiumUser,+ keyData.metadata?.prompts,+ "Premium feature - Upgrade to set prompts by key",+ "Select or enter prompts",+ )}+ />+ )}+ </FormField>+ )}++ <FormField+ control={form.control}+ name="access_group_ids"+ label={labelWithHint(+ "Access Groups",+ "Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",+ )}+ >+ {({ value, onChange }) => (+ <AccessGroupSelector+ value={value as string[] | undefined}+ onChange={onChange}+ placeholder="Select access groups (optional)"+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="allowed_passthrough_routes"+ label={+ premiumUser+ ? "Allowed Pass Through Routes"+ : labelWithHint(+ "Allowed Pass Through Routes",+ "Setting allowed pass through routes by key is a premium feature",+ )+ }+ >+ {({ value, onChange }) => (+ <PassThroughRoutesSelector+ value={value as string[] | undefined}+ onChange={onChange}+ accessToken={accessToken || ""}+ placeholder={currentValuePlaceholder(+ premiumUser,+ keyData.metadata?.allowed_passthrough_routes,+ "Premium feature - Upgrade to set allowed pass through routes by key",+ "Select or enter allowed pass through routes",+ )}+ disabled={!premiumUser}+ />+ )}+ </FormField>++ <FormField control={form.control} name="vector_stores" label="Vector Stores">+ {({ value, onChange }) => (+ <VectorStoreSelector+ onChange={onChange}+ value={value as string[] | undefined}+ accessToken={accessToken || ""}+ placeholder="Select vector stores"+ />+ )}+ </FormField>++ <FormField control={form.control} name="mcp_servers_and_groups" label="MCP Servers / Access Groups">+ {({ value, onChange }) => (+ <MCPServerSelector+ onChange={onChange}+ value={value as McpServersAndGroups | undefined}+ accessToken={accessToken || ""}+ placeholder="Select MCP servers or access groups (optional)"+ allowNoMcpServers+ />+ )}+ </FormField>- <Form.Item- label="Allowed Pass Through Routes"- name="allowed_passthrough_routes"- tooltip={!premiumUser ? "Setting allowed pass through routes by key is a premium feature" : undefined}- >- <PassThroughRoutesSelector- accessToken={accessToken || ""}- placeholder={- !premiumUser- ? "Premium feature - Upgrade to set allowed pass through routes by key"- : Array.isArray(keyData.metadata?.allowed_passthrough_routes) &&- keyData.metadata.allowed_passthrough_routes.length > 0- ? `Current: ${keyData.metadata.allowed_passthrough_routes.join(", ")}`- : "Select or enter allowed pass through routes"- }- disabled={!premiumUser}- />- </Form.Item>-- <Form.Item label="Vector Stores" name="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="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)"- allowNoMcpServers- />- </Form.Item>-- {/* Hidden field to register mcp_tool_permissions with the form */}- <Form.Item name="mcp_tool_permissions" initialValue={{}} hidden>- <AntdInput 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 || []).filter(+ selectedServers={((mcpServersAndGroups as { servers?: string[] } | undefined)?.servers || []).filter((s: string) => s !== NO_MCP_SERVERS_SENTINEL,)}- toolPermissions={form.getFieldValue("mcp_tool_permissions") || {}}- onChange={(toolPerms) => form.setFieldsValue({ mcp_tool_permissions: toolPerms })}+ toolPermissions={(mcpToolPermissions as Record<string, string[]> | undefined) || {}}+ 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>-- <Form.Item- label={- <span>- Organization{" "}- <Tooltip title="The organization this key belongs to. Selecting an organization filters the available teams.">- <InfoCircleOutlined style={{ marginLeft: "4px" }} />- </Tooltip>- </span>- }- name="organization_id"- >- <OrganizationDropdown- organizations={organizations}- loading={isOrganizationsLoading}- disabled={userRole !== "Admin"}- onChange={(orgId) => {- setSelectedOrganizationId(orgId || null);- form.setFieldValue("team_id", undefined);- }}- />- </Form.Item>-- <Form.Item- label="Team ID"- name="team_id"- help={enableProjectsUI && hasProject ? "Team is locked because this key belongs to a project" : undefined}- >- <Select- placeholder="Select team"- showSearch- disabled={enableProjectsUI && hasProject}- style={{ width: "100%" }}- onChange={(teamId) => {- const selectedTeam = teams?.find((t) => t.team_id === teamId) || null;- if (selectedTeam?.organization_id) {- setSelectedOrganizationId(selectedTeam.organization_id);- form.setFieldValue("organization_id", selectedTeam.organization_id);- } else if (!teamId) {- setSelectedOrganizationId(null);- form.setFieldValue("organization_id", undefined);++ <FormField control={form.control} name="agents_and_groups" label="Agents / Access Groups">+ {({ value, onChange }) => (+ <AgentSelector+ onChange={onChange}+ value={value as AgentsAndGroups | undefined}+ accessToken={accessToken || ""}+ placeholder="Select agents or access groups (optional)"+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="organization_id"+ label={labelWithHint(+ "Organization",+ "The organization this key belongs to. Selecting an organization filters the available teams.",+ )}+ >+ {({ value, onChange, id }) => (+ <OrganizationDropdown+ id={id}+ value={(value as string | undefined) ?? undefined}+ organizations={organizations}+ loading={isOrganizationsLoading}+ disabled={userRole !== "Admin"}+ onChange={(orgId) => handleOrganizationChange(onChange, orgId)}+ />+ )}+ </FormField>++ <FormField+ control={form.control}+ name="team_id"+ label="Team ID"+ description={+ enableProjectsUI && hasProject ? "Team is locked because this key belongs to a project" : undefined}- }}- filterOption={(input, option) => {- const filteredTeams = selectedOrganizationId- ? teams?.filter((t) => t.organization_id === selectedOrganizationId)- : teams;- const team = filteredTeams?.find((t) => t.team_id === option?.value);- if (!team) return false;- return team.team_alias?.toLowerCase().includes(input.toLowerCase()) ?? false;- }}- >- {(selectedOrganizationId ? teams?.filter((t) => t.organization_id === selectedOrganizationId) : teams)?.map(- (team) => (- <Select.Option key={team.team_id} value={team.team_id}>- {`${team.team_alias} (${team.team_id})`}- </Select.Option>- ),+ >+ {({ value, onChange, id }) => (+ <Select+ value={(value as string | null) ?? null}+ onValueChange={(teamId: string | null) => handleTeamChange(onChange, teamId)}+ disabled={enableProjectsUI && hasProject}+ items={Object.fromEntries(+ (visibleTeams ?? []).map((t) => [t.team_id, `${t.team_alias} (${t.team_id})`]),+ )}+ >+ <SelectTrigger id={id} className="w-full">+ <SelectValue placeholder="Select team" />+ </SelectTrigger>+ <SelectContent>+ {visibleTeams?.map((t) => (+ <SelectItem key={t.team_id} value={t.team_id}>+ {`${t.team_alias} (${t.team_id})`}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </FormField>++ {enableProjectsUI && hasProject && (+ <Field>+ <FieldLabel htmlFor={projectFieldId}>Project</FieldLabel>+ <Input id={projectFieldId} value={projectDisplay ?? ""} disabled readOnly />+ </Field>)}- </Select>- </Form.Item>- {enableProjectsUI && hasProject && (- <Form.Item label="Project">- <AntdInput value={projectDisplay ?? ""} disabled />- </Form.Item>- )}- <Form.Item label="Router Settings">- <RouterSettingsAccordion- ref={routerSettingsRef}- accessToken={accessToken || ""}- teamId={keyData.team_id}- value={routerSettingsEditorValue(keyData.router_settings)}- />- </Form.Item>-- <Form.Item label="Logging Settings" name="logging_settings">- <EditLoggingSettings- value={form.getFieldValue("logging_settings")}- onChange={(values) => form.setFieldValue("logging_settings", values)}- disabledCallbacks={disabledCallbacks}- onDisabledCallbacksChange={(internalValues) => {- // Convert internal values back to display names for UI state- const displayNames = mapInternalToDisplayNames(internalValues);- setDisabledCallbacks(displayNames);- // Store internal values in form for submission- form.setFieldValue("disabled_callbacks", internalValues);- }}- />- </Form.Item>-- <Form.Item label="Metadata" name="metadata">- <AntdInput.TextArea rows={10} />- </Form.Item>-- {/* Auto-Rotation Settings */}- <div className="mb-4">- <Form.Item name="duration" initialValue="" noStyle>- <KeyLifecycleSettings- autoRotationEnabled={autoRotationEnabled}- onAutoRotationChange={setAutoRotationEnabled}- rotationInterval={rotationInterval}- onRotationIntervalChange={setRotationInterval}- neverExpire={neverExpire}- onNeverExpireChange={setNeverExpire}- />- </Form.Item>- </div>-- {/* Hidden form field for token */}- <Form.Item name="token" hidden>- <AntdInput />- </Form.Item>-- {/* Hidden form field for disabled callbacks */}- <Form.Item name="disabled_callbacks" hidden>- <AntdInput />- </Form.Item>-- {/* Hidden form fields for auto-rotation */}- <Form.Item name="auto_rotate" hidden>- <AntdInput />- </Form.Item>- <Form.Item name="rotation_interval" hidden>- <AntdInput />- </Form.Item>-- <div className="sticky z-10 bg-white p-4 border-t border-gray-200 -bottom-6 -inset-x-6">- <div className="flex justify-end items-center gap-2">- <Button variant="secondary" onClick={onCancel} disabled={isKeySaving}>- Cancel- </Button>- <Button type="submit" disabled={isKeySaving} aria-busy={isKeySaving}>- {isKeySaving && <UiLoadingSpinner className="size-4" />}- Save Changes- </Button>++ <Field>+ <FieldLabel>Router Settings</FieldLabel>+ <RouterSettingsAccordion+ ref={routerSettingsRef}+ accessToken={accessToken || ""}+ teamId={keyData.team_id}+ value={routerSettingsEditorValue(keyData.router_settings)}+ />+ </Field>++ <FormField control={form.control} name="logging_settings" label="Logging Settings">+ {({ value, onChange }) => (+ <EditLoggingSettings+ value={(value as unknown[] | undefined) ?? []}+ onChange={onChange}+ disabledCallbacks={disabledCallbacks}+ onDisabledCallbacksChange={handleDisabledCallbacksChange}+ />+ )}+ </FormField>++ <FormField control={form.control} name="metadata" label="Metadata">+ {(field) => <Textarea {...field} value={(field.value as string | undefined) ?? ""} rows={10} />}+ </FormField>++ <div className="mb-4">+ <FormField control={form.control} name="duration">+ {({ value, onChange, id }) => (+ <KeyLifecycleSettings+ id={id}+ value={(value as string | null) ?? ""}+ onChange={onChange}+ autoRotationEnabled={autoRotationEnabled}+ onAutoRotationChange={setAutoRotationEnabled}+ rotationInterval={rotationInterval}+ onRotationIntervalChange={setRotationInterval}+ neverExpire={neverExpire}+ onNeverExpireChange={setNeverExpire}+ />+ )}+ </FormField>+ </div>+ </FieldGroup>++ <div className="sticky z-10 bg-background p-4 border-t border-border -bottom-6 -inset-x-6">+ <div className="flex justify-end items-center gap-2">+ <Button type="button" variant="secondary" onClick={onCancel} disabled={isKeySaving}>+ Cancel+ </Button>+ <Button type="submit" disabled={isKeySaving} aria-busy={isKeySaving}>+ {isKeySaving && <UiLoadingSpinner className="size-4" />}+ Save Changes+ </Button>+ </div></div>- </div>- </Form>+ </form>+ </TooltipProvider>);}