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
fix(ui): validate default team values in Default User Settings (#34815)
ryan-crabbe-berri0171170fc783
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex 89781b9d92c..a2c16e88839 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -260,10 +260,12 @@ async def _add_user_to_team())else:- verbose_proxy_logger.debug(- "litellm.proxy.management_endpoints.internal_user_endpoints.new_user(): Exception occured - {}".format(- str(e)- )+ verbose_proxy_logger.error(+ "litellm.proxy.management_endpoints.internal_user_endpoints._add_user_to_team(): "+ "failed to add user %s to team %s - %s",+ user_id,+ team_id,+ str(e),)except Exception as e:if "already exists" in str(e) or "doesn't exist" in str(e):@@ -279,6 +281,13 @@ async def _add_user_to_team())else:+ verbose_proxy_logger.error(+ "litellm.proxy.management_endpoints.internal_user_endpoints._add_user_to_team(): "+ "failed to add user %s to team %s - %s",+ user_id,+ team_id,+ str(e),+ )raise ediff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex 10c71c00110..8f3f8ad1bfc 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -2,6 +2,7 @@import asyncioimport jsonimport os+from collections import Counterfrom collections.abc import Mappingfrom typing import Any, Dict, List, Optional, Set, Tuple, Type, Unionfrom urllib.parse import urlparse@@ -25,6 +26,7 @@ from litellm.repositories.table_repositories import (SSOConfigRepository,UISettingsRepository,)+from litellm.repositories.team_repository import TeamRepositoryfrom litellm.types.proxy.management_endpoints.ui_sso import (DefaultTeamSSOParams,SSOConfig,@@ -598,6 +600,51 @@ async def get_default_team_settings():)+def _default_team_ids(teams: list[str] | list[NewUserRequestTeam]) -> tuple[str, ...]:+ return tuple(team if isinstance(team, str) else team.team_id for team in teams)+++async def _validate_default_teams_exist(teams: list[str] | list[NewUserRequestTeam]) -> None:+ """Reject default teams that cannot be assigned.++ New users are added to these teams long after the settings are saved, and that+ consume path swallows the resulting 404, so an unknown team id would silently+ drop every future user's team assignment unless it is caught here.+ """+ team_ids = _default_team_ids(teams)+ if not team_ids:+ return++ duplicate_ids = tuple(team_id for team_id, count in Counter(team_ids).items() if count > 1)+ if duplicate_ids:+ raise HTTPException(+ status_code=400,+ detail={+ "error": f"Duplicate default team id(s): {', '.join(duplicate_ids)}. List each default team only once."+ },+ )++ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": "Database not connected. Please connect a database."},+ )++ existing_teams = await TeamRepository(prisma_client).find_many(where={"team_id": {"in": list(team_ids)}})+ existing_team_ids = {team.team_id for team in existing_teams}+ missing_ids = tuple(team_id for team_id in team_ids if team_id not in existing_team_ids)+ if missing_ids:+ raise HTTPException(+ status_code=400,+ detail={+ "error": f"Team(s) not found: {', '.join(missing_ids)}. "+ "A team must exist before it can be set as a default team for new users."+ },+ )++async def update_default_team_member_budget(teams: List[NewUserRequestTeam], user_api_key_dict: UserAPIKeyAuth):"""1. Update the max member budget for the team@@ -706,6 +753,9 @@ async def update_internal_user_settings(Update the default internal user parameters for SSO users.These settings will be applied to new users who sign in via SSO."""+ if settings.teams is not None:+ await _validate_default_teams_exist(settings.teams)+if settings.teams is not None and all(isinstance(team, NewUserRequestTeam) for team in settings.teams):await update_default_team_member_budget(settings.teams,diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.pyindex be0267d69c5..5cbc3e72d83 100644--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py@@ -3605,3 +3605,65 @@ async def test_add_new_user_to_default_team_string_teams_have_no_member_budget(massert mock_add.call_args.kwargs["max_budget_in_team"] is Noneassert mock_add.call_args.kwargs["team_id"] == "string-team"+++async def test_add_user_to_team_logs_unknown_team_at_error(mocker, caplog):+ """A default team that no longer exists makes every membership write 404.++ The failure is swallowed so user creation still succeeds, so the log line is+ the only signal an operator gets; it must be ERROR and name the team.+ """+ import logging++ from fastapi import HTTPException++ from litellm.proxy.management_endpoints.internal_user_endpoints import (+ _add_user_to_team,+ )++ mocker.patch(+ "litellm.proxy.management_endpoints.team_endpoints.team_member_add",+ new_callable=mocker.AsyncMock,+ side_effect=HTTPException(status_code=404, detail={"error": "Team not found"}),+ )++ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):+ await _add_user_to_team(+ user_id="sso-user",+ team_id="deleted-team",+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),+ )++ errors = [r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR]+ assert len(errors) == 1, f"expected exactly one ERROR log, got {errors}"+ assert "deleted-team" in errors[0]+ assert "sso-user" in errors[0]+++async def test_add_user_to_team_keeps_already_a_member_quiet(mocker, caplog):+ """Re-adding an existing member is expected on every login and must not+ produce an ERROR, otherwise the real failures above are lost in the noise."""+ import logging++ from fastapi import HTTPException++ from litellm.proxy.management_endpoints.internal_user_endpoints import (+ _add_user_to_team,+ )++ mocker.patch(+ "litellm.proxy.management_endpoints.team_endpoints.team_member_add",+ new_callable=mocker.AsyncMock,+ side_effect=HTTPException(status_code=400, detail={"error": "User already exists in team"}),+ )++ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):+ await _add_user_to_team(+ user_id="sso-user",+ team_id="existing-team",+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),+ )++ assert [r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR] == []diff --git a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.pyindex 20451f5d0ac..d4fd5bc2dce 100644--- a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py+++ b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py@@ -2680,6 +2680,142 @@ def test_update_ui_settings_writes_audit_log(monkeypatch):app.dependency_overrides.pop(user_api_key_auth, None)+def mock_team_lookup(monkeypatch):+ """Back /update/internal_user_settings with a fake team table.++ Yields the set of team ids that exist; the test mutates it before the call.+ Also exposes the find_many mock so a test can assert the lookup was skipped.+ """+ from unittest.mock import AsyncMock, MagicMock++ import litellm+ import litellm.proxy.proxy_server as proxy_server_module++ existing_team_ids: set = set()++ async def _find_many(where):+ requested = where["team_id"]["in"]+ return [{"team_id": team_id} for team_id in requested if team_id in existing_team_ids]++ find_many = AsyncMock(side_effect=_find_many)+ fake_prisma = MagicMock()+ fake_prisma.db.litellm_teamtable.find_many = find_many++ member_budget_update = AsyncMock()++ monkeypatch.setattr(proxy_server_module, "prisma_client", fake_prisma)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr(litellm, "default_internal_user_params", {})+ monkeypatch.setattr(+ "litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints.update_default_team_member_budget",+ member_budget_update,+ )++ return {+ "existing_team_ids": existing_team_ids,+ "find_many": find_many,+ "member_budget_update": member_budget_update,+ }+++def test_update_internal_user_settings_rejects_unknown_team_object(mock_proxy_config, mock_auth, mock_team_lookup):+ """Regression: saving a default team that doesn't exist used to return 200,+ then silently fail for every SSO user because the membership write 404s."""+ mock_team_lookup["existing_team_ids"].add("real-team")++ resp = client.patch(+ "/update/internal_user_settings",+ json={+ "max_budget": 10.0,+ "teams": [+ {"team_id": "real-team", "max_budget_in_team": 5.0},+ {"team_id": "ghost-team"},+ ],+ },+ )++ assert resp.status_code == 400, resp.text+ assert "ghost-team" in resp.json()["detail"]["error"]+ assert "real-team" not in resp.json()["detail"]["error"]+ assert mock_proxy_config["save_call_count"]() == 0+ assert mock_team_lookup["member_budget_update"].await_count == 0, (+ "per-member budgets must not be written before the team ids are validated"+ )++ import litellm++ assert litellm.default_internal_user_params == {}+++def test_update_internal_user_settings_rejects_unknown_team_string(mock_proxy_config, mock_auth, mock_team_lookup):+ """The bare-string team shape must be validated too."""+ resp = client.patch(+ "/update/internal_user_settings",+ json={"teams": ["ghost-team"]},+ )++ assert resp.status_code == 400, resp.text+ assert "ghost-team" in resp.json()["detail"]["error"]+ assert mock_proxy_config["save_call_count"]() == 0+++def test_update_internal_user_settings_rejects_duplicate_team_ids(mock_proxy_config, mock_auth, mock_team_lookup):+ """Listing a team twice makes its per-member budget a race between the two+ entries, so the payload is rejected rather than silently resolved."""+ mock_team_lookup["existing_team_ids"].add("real-team")++ resp = client.patch(+ "/update/internal_user_settings",+ json={+ "teams": [+ {"team_id": "real-team", "max_budget_in_team": 5.0},+ {"team_id": "real-team", "max_budget_in_team": 50.0},+ ]+ },+ )++ assert resp.status_code == 400, resp.text+ assert "real-team" in resp.json()["detail"]["error"]+ assert mock_proxy_config["save_call_count"]() == 0+++def test_update_internal_user_settings_saves_when_all_teams_exist(mock_proxy_config, mock_auth, mock_team_lookup):+ """Valid team ids still save, and still reach the per-member budget update."""+ mock_team_lookup["existing_team_ids"].update({"team-a", "team-b"})++ resp = client.patch(+ "/update/internal_user_settings",+ json={+ "max_budget": 10.0,+ "teams": [+ {"team_id": "team-a", "max_budget_in_team": 5.0},+ {"team_id": "team-b"},+ ],+ },+ )++ assert resp.status_code == 200, resp.text+ assert [team["team_id"] for team in resp.json()["settings"]["teams"]] == [+ "team-a",+ "team-b",+ ]+ assert mock_proxy_config["save_call_count"]() == 1+ mock_team_lookup["member_budget_update"].assert_awaited_once()+++def test_update_internal_user_settings_without_teams_skips_team_lookup(mock_proxy_config, mock_auth, mock_team_lookup):+ """Settings changes that don't touch teams must not pay for a DB round trip."""+ resp = client.patch(+ "/update/internal_user_settings",+ json={"max_budget": 10.0},+ )++ assert resp.status_code == 200, resp.text+ mock_team_lookup["find_many"].assert_not_awaited()+ assert mock_proxy_config["save_call_count"]() == 1++def test_update_mcp_semantic_filter_settings_requires_proxy_admin(monkeypatch):"""Non-admin callers must not mutate global MCP semantic filter settings."""from litellm.proxy._types import UserAPIKeyAuthdiff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 998422a78d2..d79c755ebdd 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -1867,11 +1867,6 @@"count": 1}},- "src/app/(dashboard)/users/_components/DefaultUserSettings.tsx": {- "no-restricted-imports": {- "count": 2- }- },"src/app/(dashboard)/users/_components/edit_user.tsx": {"local/filename-pascal-case": {"count": 1@@ -3353,10 +3348,10 @@"count": 5},"no-restricted-syntax": {- "count": 154+ "count": 153},"prefer-const": {- "count": 33+ "count": 32}},"src/components/object_permissions_view.tsx": {@@ -4321,11 +4316,6 @@"count": 1}},- "src/lib/http/client.ts": {- "no-nested-ternary": {- "count": 1- }- },"src/utils/dataUtils.test.ts": {"max-nested-callbacks": {"count": 1diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.test.tsxdeleted file mode 100644index 06dafcfcffd..00000000000--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.test.tsx+++ /dev/null@@ -1,153 +0,0 @@-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import DefaultUserSettings from "./DefaultUserSettings";-import * as networking from "@/components/networking";--vi.mock("@/components/networking", () => ({- getInternalUserSettings: vi.fn(),- updateInternalUserSettings: vi.fn(),- modelAvailableCall: vi.fn(),-}));--vi.mock("@/components/common_components/budget_duration_dropdown", () => ({- default: ({ value, onChange }: { value: string | null; onChange: (value: string | null) => void }) => (- <select data-testid="budget-duration" value={value || ""} onChange={(e) => onChange(e.target.value || null)}>- <option value="">Select duration</option>- <option value="daily">Daily</option>- <option value="monthly">Monthly</option>- </select>- ),- getBudgetDurationLabel: (value: string) => value,-}));--vi.mock("@/components/key_team_helpers/fetch_available_models_team_key", () => ({- getModelDisplayName: (model: string) => model,-}));--describe("DefaultUserSettings", () => {- const mockGetInternalUserSettings = vi.mocked(networking.getInternalUserSettings);- const mockUpdateInternalUserSettings = vi.mocked(networking.updateInternalUserSettings);- const mockModelAvailableCall = vi.mocked(networking.modelAvailableCall);-- const defaultProps = {- accessToken: "test-token",- userID: "user-123",- userRole: "Admin",- possibleUIRoles: {- internal_user_admin: {- ui_label: "Admin",- description: "Full access",- },- internal_user_viewer: {- ui_label: "Viewer",- description: "Read-only access",- },- },- };-- const mockSettings = {- values: {- user_role: "internal_user_admin",- budget_duration: "monthly",- max_budget: 1000,- teams: [],- },- field_schema: {- description: "Default user settings",- properties: {- user_role: {- type: "string",- description: "User role",- },- budget_duration: {- type: "string",- description: "Budget duration",- },- max_budget: {- type: "number",- description: "Maximum budget",- },- teams: {- type: "array",- description: "Teams",- },- },- },- };-- beforeEach(() => {- mockGetInternalUserSettings.mockClear();- mockUpdateInternalUserSettings.mockClear();- mockModelAvailableCall.mockClear();- mockModelAvailableCall.mockResolvedValue({- data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],- });- });-- it("should render", async () => {- mockGetInternalUserSettings.mockResolvedValue(mockSettings);-- render(<DefaultUserSettings {...defaultProps} />);-- await waitFor(() => {- expect(mockGetInternalUserSettings).toHaveBeenCalled();- });-- expect(screen.getByText("Default User Settings")).toBeInTheDocument();- });-- it("should toggle edit mode when edit button is clicked", async () => {- mockGetInternalUserSettings.mockResolvedValue(mockSettings);-- render(<DefaultUserSettings {...defaultProps} />);-- await waitFor(() => {- expect(screen.getByText("Edit Settings")).toBeInTheDocument();- });-- const editButton = screen.getByText("Edit Settings");- act(() => {- fireEvent.click(editButton);- });-- expect(screen.getByText("Cancel")).toBeInTheDocument();- expect(screen.getByText("Save Changes")).toBeInTheDocument();- expect(screen.queryByText("Edit Settings")).not.toBeInTheDocument();- });-- it("should save settings when save button is clicked", async () => {- mockGetInternalUserSettings.mockResolvedValue(mockSettings);- mockUpdateInternalUserSettings.mockResolvedValue({- settings: {- ...mockSettings.values,- max_budget: 2000,- },- });-- render(<DefaultUserSettings {...defaultProps} />);-- await waitFor(() => {- expect(screen.getByText("Edit Settings")).toBeInTheDocument();- });-- const editButton = screen.getByText("Edit Settings");- act(() => {- fireEvent.click(editButton);- });-- await waitFor(() => {- expect(screen.getByText("Save Changes")).toBeInTheDocument();- });-- const saveButton = screen.getByText("Save Changes");- act(() => {- fireEvent.click(saveButton);- });-- await waitFor(() => {- expect(mockUpdateInternalUserSettings).toHaveBeenCalled();- });-- expect(screen.getByText("Edit Settings")).toBeInTheDocument();- });-});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.tsxdeleted file mode 100644index 7fee2e14b27..00000000000--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/DefaultUserSettings.tsx+++ /dev/null@@ -1,492 +0,0 @@-import React, { useState, useEffect } from "react";-import { Card, Title, Text, Divider, TextInput } from "@tremor/react";-import { Button, Typography, Spin, Switch, Select, InputNumber } from "antd";-import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";-import { getInternalUserSettings, updateInternalUserSettings, modelAvailableCall } from "@/components/networking";-import BudgetDurationDropdown, {- getBudgetDurationLabel,-} from "@/components/common_components/budget_duration_dropdown";-import { getModelDisplayName } from "@/components/key_team_helpers/fetch_available_models_team_key";-import { formatNumberWithCommas } from "@/utils/dataUtils";-import NotificationManager from "@/components/molecules/notifications_manager";--interface DefaultUserSettingsProps {- accessToken: string | null;- possibleUIRoles?: Record<string, Record<string, string>> | null;- userID: string;- userRole: string;-}--interface TeamEntry {- team_id: string;- max_budget_in_team?: number;- user_role: "user" | "admin";-}--const DefaultUserSettings: React.FC<DefaultUserSettingsProps> = ({- accessToken,- possibleUIRoles,- userID,- userRole,-}) => {- const [loading, setLoading] = useState<boolean>(true);- const [settings, setSettings] = useState<any>(null);- const [isEditing, setIsEditing] = useState<boolean>(false);- const [editedValues, setEditedValues] = useState<any>({});- const [saving, setSaving] = useState<boolean>(false);- const [availableModels, setAvailableModels] = useState<string[]>([]);- const { Paragraph } = Typography;- const { Option } = Select;-- useEffect(() => {- const fetchSSOSettings = async () => {- if (!accessToken) {- setLoading(false);- return;- }-- try {- const data = await getInternalUserSettings(accessToken);- setSettings(data);- setEditedValues(data.values || {});-- // Fetch available models- if (accessToken) {- try {- const modelResponse = await modelAvailableCall(accessToken, userID, userRole);- if (modelResponse && modelResponse.data) {- const modelNames = modelResponse.data.map((model: { id: string }) => model.id);- setAvailableModels(modelNames);- }- } catch (error) {- console.error("Error fetching available models:", error);- }- }- } catch (error) {- console.error("Error fetching SSO settings:", error);- NotificationManager.fromBackend("Failed to fetch SSO settings");- } finally {- setLoading(false);- }- };-- fetchSSOSettings();- }, [accessToken]);-- const handleSaveSettings = async () => {- if (!accessToken) return;-- setSaving(true);- try {- // Convert empty strings to null- const processedValues = Object.entries(editedValues).reduce(- (acc, [key, value]) => {- acc[key] = value === "" ? null : value;- return acc;- },- {} as Record<string, any>,- );-- const updatedSettings = await updateInternalUserSettings(accessToken, processedValues);- setSettings({ ...settings, values: updatedSettings.settings });- setIsEditing(false);- } catch (error) {- console.error("Error updating SSO settings:", error);- NotificationManager.fromBackend("Failed to update settings: " + error);- } finally {- setSaving(false);- }- };-- const handleTextInputChange = (key: string, value: any) => {- setEditedValues((prev: Record<string, any>) => ({- ...prev,- [key]: value,- }));- };-- // Helper function to normalize teams array to consistent format- const normalizeTeams = (teams: any[]): TeamEntry[] => {- if (!teams || !Array.isArray(teams)) return [];-- return teams.map((team) => {- if (typeof team === "string") {- return {- team_id: team,- user_role: "user" as const,- };- } else if (typeof team === "object" && team.team_id) {- return {- team_id: team.team_id,- max_budget_in_team: team.max_budget_in_team,- user_role: team.user_role || "user",- };- }- return {- team_id: "",- user_role: "user" as const,- };- });- };-- // Teams editor component- const renderTeamsEditor = (teams: any[]) => {- const normalizedTeams = normalizeTeams(teams);-- const updateTeam = (index: number, field: keyof TeamEntry, value: any) => {- const updatedTeams = [...normalizedTeams];- updatedTeams[index] = {- ...updatedTeams[index],- [field]: value,- };- handleTextInputChange("teams", updatedTeams);- };-- const addTeam = () => {- const newTeam: TeamEntry = {- team_id: "",- user_role: "user",- };- handleTextInputChange("teams", [...normalizedTeams, newTeam]);- };-- const removeTeam = (index: number) => {- const updatedTeams = normalizedTeams.filter((_, i) => i !== index);- handleTextInputChange("teams", updatedTeams);- };-- return (- <div className="space-y-3">- {normalizedTeams.map((team, index) => (- <div key={index} className="border rounded-lg p-4 bg-gray-50">- <div className="flex items-center justify-between mb-3">- <Text className="font-medium">Team {index + 1}</Text>- <Button size="small" danger icon={<DeleteOutlined />} onClick={() => removeTeam(index)}>- Remove- </Button>- </div>-- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">- <div>- <Text className="text-sm font-medium mb-1">Team ID</Text>- <TextInput- value={team.team_id}- onChange={(e) => updateTeam(index, "team_id", e.target.value)}- placeholder="Enter team ID"- />- </div>-- <div>- <Text className="text-sm font-medium mb-1">Max Budget in Team</Text>- <InputNumber- style={{ width: "100%" }}- value={team.max_budget_in_team}- onChange={(value) => updateTeam(index, "max_budget_in_team", value)}- placeholder="Optional"- min={0}- step={0.01}- precision={2}- />- </div>-- <div>- <Text className="text-sm font-medium mb-1">User Role</Text>- <Select- style={{ width: "100%" }}- value={team.user_role}- onChange={(value) => updateTeam(index, "user_role", value)}- >- <Option value="user">User</Option>- <Option value="admin">Admin</Option>- </Select>- </div>- </div>- </div>- ))}-- <Button icon={<PlusOutlined />} onClick={addTeam} className="w-full">- Add Team- </Button>- </div>- );- };-- const renderEditableField = (key: string, property: any, value: any) => {- const type = property.type;-- if (key === "teams") {- return <div className="mt-2">{renderTeamsEditor(editedValues[key] || [])}</div>;- } else if (key === "user_role" && possibleUIRoles) {- return (- <Select- style={{ width: "100%" }}- value={editedValues[key] || ""}- onChange={(value) => handleTextInputChange(key, value)}- className="mt-2"- >- {Object.entries(possibleUIRoles)- .filter(([role]) => role.includes("internal_user"))- .map(([role, { ui_label, description }]) => (- <Option key={role} value={role}>- <div className="flex items-center">- <span>{ui_label}</span>- <span className="ml-2 text-xs text-gray-500">{description}</span>- </div>- </Option>- ))}- </Select>- );- } else if (key === "budget_duration") {- return (- <BudgetDurationDropdown- value={editedValues[key] || null}- onChange={(value) => handleTextInputChange(key, value)}- className="mt-2"- />- );- } else if (type === "boolean") {- return (- <div className="mt-2">- <Switch checked={!!editedValues[key]} onChange={(checked) => handleTextInputChange(key, checked)} />- </div>- );- } else if (type === "array" && property.items?.enum) {- return (- <Select- mode="multiple"- style={{ width: "100%" }}- value={editedValues[key] || []}- onChange={(value) => handleTextInputChange(key, value)}- className="mt-2"- >- {property.items.enum.map((option: string) => (- <Option key={option} value={option}>- {option}- </Option>- ))}- </Select>- );- } else if (key === "models") {- return (- <Select- mode="multiple"- style={{ width: "100%" }}- value={editedValues[key] || []}- onChange={(value) => handleTextInputChange(key, value)}- className="mt-2"- >- <Option key="no-default-models" value="no-default-models">- No Default Models- </Option>- <Option key="all-proxy-models" value="all-proxy-models">- All Proxy Models- </Option>- {availableModels.map((model: string) => (- <Option key={model} value={model}>- {getModelDisplayName(model)}- </Option>- ))}- </Select>- );- } else if (type === "string" && property.enum) {- return (- <Select- style={{ width: "100%" }}- value={editedValues[key] || ""}- onChange={(value) => handleTextInputChange(key, value)}- className="mt-2"- >- {property.enum.map((option: string) => (- <Option key={option} value={option}>- {option}- </Option>- ))}- </Select>- );- } else {- return (- <TextInput- value={editedValues[key] !== undefined ? String(editedValues[key]) : ""}- onChange={(e) => handleTextInputChange(key, e.target.value)}- placeholder={property.description || ""}- className="mt-2"- />- );- }- };-- const renderValue = (key: string, value: any): JSX.Element => {- if (value === null || value === undefined) return <span className="text-gray-400">Not set</span>;-- if (key === "teams" && Array.isArray(value)) {- if (value.length === 0) return <span className="text-gray-400">No teams assigned</span>;-- const normalizedTeams = normalizeTeams(value);-- return (- <div className="space-y-2 mt-1">- {normalizedTeams.map((team, index) => (- <div key={index} className="border rounded-lg p-3 bg-white">- <div className="grid grid-cols-1 md:grid-cols-3 gap-2 text-sm">- <div>- <span className="font-medium text-gray-600">Team ID:</span>- <p className="text-gray-900">{team.team_id || "Not specified"}</p>- </div>- <div>- <span className="font-medium text-gray-600">Max Budget:</span>- <p className="text-gray-900">- {team.max_budget_in_team !== undefined- ? `$${formatNumberWithCommas(team.max_budget_in_team, 4)}`- : "No limit"}- </p>- </div>- <div>- <span className="font-medium text-gray-600">Role:</span>- <p className="text-gray-900 capitalize">{team.user_role}</p>- </div>- </div>- </div>- ))}- </div>- );- }-- if (key === "user_role" && possibleUIRoles && possibleUIRoles[value]) {- const { ui_label, description } = possibleUIRoles[value];- return (- <div>- <span className="font-medium">{ui_label}</span>- {description && <p className="text-xs text-gray-500 mt-1">{description}</p>}- </div>- );- }-- if (key === "budget_duration") {- return <span>{getBudgetDurationLabel(value)}</span>;- }-- if (typeof value === "boolean") {- return <span>{value ? "Enabled" : "Disabled"}</span>;- }-- if (key === "models" && Array.isArray(value)) {- if (value.length === 0) return <span className="text-gray-400">None</span>;-- return (- <div className="flex flex-wrap gap-2 mt-1">- {value.map((model, index) => (- <span key={index} className="px-2 py-1 bg-blue-100 rounded-sm text-xs">- {getModelDisplayName(model)}- </span>- ))}- </div>- );- }-- if (typeof value === "object") {- if (Array.isArray(value)) {- if (value.length === 0) return <span className="text-gray-400">None</span>;-- return (- <div className="flex flex-wrap gap-2 mt-1">- {value.map((item, index) => (- <span key={index} className="px-2 py-1 bg-blue-100 rounded-sm text-xs">- {typeof item === "object" ? JSON.stringify(item) : String(item)}- </span>- ))}- </div>- );- }-- return (- <pre className="bg-gray-100 p-2 rounded-sm text-xs overflow-auto mt-1">{JSON.stringify(value, null, 2)}</pre>- );- }-- return <span>{String(value)}</span>;- };-- if (loading) {- return (- <div className="flex justify-center items-center h-64">- <Spin size="large" />- </div>- );- }-- if (!settings) {- return (- <Card>- <Text>No settings available or you do not have permission to view them.</Text>- </Card>- );- }-- // Dynamically render settings based on the schema- const renderSettings = () => {- const { values, field_schema } = settings;-- if (!field_schema || !field_schema.properties) {- return <Text>No schema information available</Text>;- }-- return Object.entries(field_schema.properties).map(([key, property]: [string, any]) => {- const value = values[key];- const displayName = key.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());-- return (- <div key={key} className="mb-6 pb-6 border-b border-gray-200 last:border-0">- <Text className="font-medium text-lg">{displayName}</Text>- <Paragraph className="text-sm text-gray-500 mt-1">- {property.description || "No description available"}- </Paragraph>-- {isEditing ? (- <div className="mt-2">{renderEditableField(key, property, value)}</div>- ) : (- <div className="mt-1 p-2 bg-gray-50 rounded-sm">{renderValue(key, value)}</div>- )}- </div>- );- });- };-- return (- <Card>- <div className="flex justify-between items-center mb-4">- <Title>Default User Settings</Title>- {!loading &&- settings &&- (isEditing ? (- <div className="flex gap-2">- <Button- onClick={() => {- setIsEditing(false);- setEditedValues(settings.values || {});- }}- disabled={saving}- >- Cancel- </Button>- <Button type="primary" onClick={handleSaveSettings} loading={saving}>- Save Changes- </Button>- </div>- ) : (- <Button type="primary" onClick={() => setIsEditing(true)}>- Edit Settings- </Button>- ))}- </div>-- {settings?.field_schema?.description && (- <Paragraph className="mb-4">{settings.field_schema.description}</Paragraph>- )}- <Divider />-- <div className="mt-4 space-y-4">{renderSettings()}</div>- </Card>- );-};--export default DefaultUserSettings;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.test.tsxnew file mode 100644index 00000000000..bfdcc70fb0c--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.test.tsx@@ -0,0 +1,296 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import React from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({+ useInfiniteTeams: () => ({+ data: {+ pages: [+ {+ teams: [+ { team_id: "team-alpha", team_alias: "Alpha" },+ { team_id: "team-beta", team_alias: "Beta" },+ ],+ },+ ],+ },+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ }),+}));++vi.mock("@/components/ModelSelect/ModelSelect", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/components/ModelSelect/ModelSelect")>();+ return {+ MODEL_SENTINEL_OPTIONS: actual.MODEL_SENTINEL_OPTIONS,+ ModelSelect: ({ onChange }: { onChange: (values: string[]) => void }) => (+ <button type="button" onClick={() => onChange(["all-proxy-models"])}>+ set-models+ </button>+ ),+ };+});++import NotificationsManager from "@/components/molecules/notifications_manager";++import { DefaultUserSettingsForm } from "./DefaultUserSettingsForm";+import type { InternalUserSettings } from "./mapper";++const POSSIBLE_UI_ROLES = {+ internal_user: { ui_label: "Internal User", description: "create and view own keys" },+ internal_user_viewer: { ui_label: "Internal Viewer", description: "view own keys" },+ proxy_admin: { ui_label: "Admin", description: "all permissions" },+};++const SETTINGS: InternalUserSettings = {+ values: {+ user_role: "internal_user",+ max_budget: 100,+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-alpha", max_budget_in_team: 25, user_role: "user" }],+ },+ field_schema: {},+};++const SAVED_BODY = {+ user_role: "internal_user",+ max_budget: 100,+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-alpha", max_budget_in_team: 25, user_role: "user" }],+};++const renderForm = (overrides?: {+ fetchSettings?: ReturnType<typeof vi.fn>;+ updateSettings?: ReturnType<typeof vi.fn>;+}) => {+ const fetchSettings = overrides?.fetchSettings ?? vi.fn().mockResolvedValue(SETTINGS);+ const updateSettings = overrides?.updateSettings ?? vi.fn().mockResolvedValue(undefined);+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });++ render(+ <QueryClientProvider client={queryClient}>+ <DefaultUserSettingsForm+ possibleUIRoles={POSSIBLE_UI_ROLES}+ fetchSettings={fetchSettings}+ updateSettings={updateSettings}+ />+ </QueryClientProvider>,+ );++ return { fetchSettings, updateSettings };+};++const saveButton = async () => await screen.findByRole("button", { name: "Save Changes" });++const enterEditMode = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(await screen.findByRole("button", { name: "Edit Settings" }));+};++describe("DefaultUserSettingsForm", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("shows a read-only summary until Edit Settings is clicked", async () => {+ renderForm();++ expect(await screen.findByText("Internal User")).toBeInTheDocument();+ expect(screen.getByText("100")).toBeInTheDocument();+ expect(screen.getByText("monthly")).toBeInTheDocument();+ expect(screen.getByText("gpt-5.2")).toBeInTheDocument();+ expect(screen.getByText(/team-alpha/)).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save Changes" })).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Max Budget (USD)")).not.toBeInTheDocument();+ });++ it("labels model sentinels in the read-only summary", async () => {+ renderForm({+ fetchSettings: vi+ .fn()+ .mockResolvedValue({ ...SETTINGS, values: { ...SETTINGS.values, models: ["all-proxy-models"] } }),+ });++ expect(await screen.findByText("All Proxy Models")).toBeInTheDocument();+ });++ it("disables Save until the loaded settings are edited", async () => {+ const user = userEvent.setup();+ renderForm();++ await enterEditMode(user);++ expect(await saveButton()).toBeDisabled();+ });++ it("shows an error instead of the form when the settings cannot be loaded", async () => {+ renderForm({ fetchSettings: vi.fn().mockRejectedValue(new Error("nope")) });++ expect(await screen.findByRole("alert")).toHaveTextContent("Could not load the default user settings.");+ expect(screen.queryByRole("button", { name: "Edit Settings" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save Changes" })).not.toBeInTheDocument();+ });++ it("sends every field on save, not only the edited one", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.clear(await screen.findByLabelText("Max Budget (USD)"));+ await user.type(screen.getByLabelText("Max Budget (USD)"), "250");+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({ ...SAVED_BODY, max_budget: 250 });+ });++ it("clears an emptied budget with null", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.clear(await screen.findByLabelText("Max Budget (USD)"));+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({ ...SAVED_BODY, max_budget: null });+ });++ it("sends the models selection through unchanged, sentinel values included", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.click(await screen.findByRole("button", { name: "set-models" }));+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({ ...SAVED_BODY, models: ["all-proxy-models"] });+ });++ it("saves a team that was picked from the searchable list", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.click(await screen.findByRole("button", { name: "Add Team" }));+ await user.click(screen.getAllByLabelText("Team")[1]);+ await user.click(await screen.findByText("Beta"));+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({+ ...SAVED_BODY,+ teams: [+ { team_id: "team-alpha", max_budget_in_team: 25, user_role: "user" },+ { team_id: "team-beta", max_budget_in_team: null, user_role: "user" },+ ],+ });+ });++ it("never turns a team id typed into the picker into a saved team", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.click(await screen.findByRole("button", { name: "Add Team" }));+ await user.type(screen.getAllByLabelText("Team")[1], "team-alhpa");+ await user.keyboard("{Escape}");+ await user.click(await saveButton());++ expect(await screen.findByText("Select a team")).toBeInTheDocument();+ expect(screen.getAllByLabelText("Team")[1]).toHaveValue("");+ expect(updateSettings).not.toHaveBeenCalled();+ });++ it("blocks saving the same default team twice", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.click(await screen.findByRole("button", { name: "Add Team" }));+ await user.click(screen.getAllByLabelText("Team")[1]);+ await user.click(await screen.findByText("Alpha"));+ await user.click(await saveButton());++ expect(await screen.findByText("This team is already listed")).toBeInTheDocument();+ expect(updateSettings).not.toHaveBeenCalled();+ });++ it("drops a removed team row from the saved settings", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.click(await screen.findByRole("button", { name: "Remove" }));+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({ ...SAVED_BODY, teams: null });+ });++ it("returns to the read-only view showing the new values after a successful save", async () => {+ const user = userEvent.setup();+ const updated = { ...SETTINGS, values: { ...SETTINGS.values, max_budget: 250 } };+ const { updateSettings } = renderForm({+ fetchSettings: vi.fn().mockResolvedValueOnce(SETTINGS).mockResolvedValue(updated),+ });++ await enterEditMode(user);+ await user.clear(await screen.findByLabelText("Max Budget (USD)"));+ await user.type(screen.getByLabelText("Max Budget (USD)"), "250");+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(await screen.findByRole("button", { name: "Edit Settings" })).toBeInTheDocument();+ expect(await screen.findByText("250")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save Changes" })).not.toBeInTheDocument();+ expect(NotificationsManager.success).toHaveBeenCalledWith("Default user settings updated successfully");++ await enterEditMode(user);+ expect(await saveButton()).toBeDisabled();+ });++ it("keeps the edit and surfaces the backend error when the save fails", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm({+ updateSettings: vi.fn().mockRejectedValue(new Error("Team(s) not found: team-alhpa.")),+ });++ await enterEditMode(user);+ await user.clear(await screen.findByLabelText("Max Budget (USD)"));+ await user.type(screen.getByLabelText("Max Budget (USD)"), "250");+ await user.click(await saveButton());++ await waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(NotificationsManager.fromBackend).toHaveBeenCalledWith("Team(s) not found: team-alhpa."),+ );+ expect(await saveButton()).toBeEnabled();+ expect(screen.getByLabelText("Max Budget (USD)")).toHaveValue(250);+ });++ it("discards edits and returns to the read-only view when Cancel is pressed", async () => {+ const user = userEvent.setup();+ const { updateSettings } = renderForm();++ await enterEditMode(user);+ await user.clear(await screen.findByLabelText("Max Budget (USD)"));+ await user.type(screen.getByLabelText("Max Budget (USD)"), "250");+ await user.click(screen.getByRole("button", { name: "Cancel" }));++ expect(await screen.findByRole("button", { name: "Edit Settings" })).toBeInTheDocument();+ expect(screen.getByText("100")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Save Changes" })).not.toBeInTheDocument();+ expect(updateSettings).not.toHaveBeenCalled();++ await enterEditMode(user);+ expect(screen.getByLabelText("Max Budget (USD)")).toHaveValue(100);+ expect(await saveButton()).toBeDisabled();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.tsxnew file mode 100644index 00000000000..b1474e7cd0c--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/DefaultUserSettingsForm.tsx@@ -0,0 +1,433 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import * as React from "react";+import { useFieldArray, type Control } from "react-hook-form";++import { useInfiniteTeams } from "@/app/(dashboard)/hooks/teams/useTeams";+import { ModelSelect, MODEL_SENTINEL_OPTIONS } from "@/components/ModelSelect/ModelSelect";+import NotificationsManager from "@/components/molecules/notifications_manager";+import { PaginatedSearchSelect } from "@/components/shared/PaginatedSearchSelect";+import { FieldGroup } from "@/components/shared/form/field";+import { FormField } from "@/components/shared/form/FormField";+import type { SearchSelectOption } from "@/components/shared/SearchSelect";+import { Button } from "@/components/ui/button";+import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { useZodForm } from "@/lib/forms/useZodForm";+import { fetchClient } from "@/lib/http/api";++import { buildBody, settingsToForm, type DefaultInternalUserParams, type InternalUserSettings } from "./mapper";+import { defaultUserSettingsSchema, EMPTY_TEAM_ROW, type DefaultUserSettingsFormValues } from "./schema";++const NO_RESET = "never";++const BUDGET_DURATION_OPTIONS = [+ { value: NO_RESET, label: "No reset" },+ { value: "1h", label: "hourly" },+ { value: "24h", label: "daily" },+ { value: "7d", label: "weekly" },+ { value: "30d", label: "monthly" },+] as const;++const TEAM_ROLE_OPTIONS = [+ { value: "user", label: "User" },+ { value: "admin", label: "Admin" },+] as const;++const MODEL_SENTINEL_LABELS: ReadonlyMap<string, string> = new Map(+ MODEL_SENTINEL_OPTIONS.map(({ value, label }) => [value, label]),+);++const TEAMS_PAGE_SIZE = 50;++const SETTINGS_QUERY_KEY = ["internalUserSettings"] as const;++const defaultFetchSettings = async (): Promise<InternalUserSettings> => {+ const { data } = await fetchClient.GET("/get/internal_user_settings");+ if (data === undefined) {+ throw new Error("Failed to load default user settings");+ }+ return data;+};++const defaultUpdateSettings = async (body: DefaultInternalUserParams): Promise<void> => {+ await fetchClient.PATCH("/update/internal_user_settings", { body });+};++interface RoleOption {+ value: string;+ label: string;+ description: string;+}++type SettingsControl = Control<DefaultUserSettingsFormValues, unknown, DefaultUserSettingsFormValues>;++const TeamPickerField = ({ control, index }: { control: SettingsControl; index: number }) => {+ const [search, setSearch] = React.useState("");+ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteTeams(+ TEAMS_PAGE_SIZE,+ search === "" ? undefined : search,+ );++ const options = React.useMemo<SearchSelectOption[]>(+ () =>+ (data?.pages ?? []).flatMap((page) =>+ page.teams.map((team) => ({+ label: team.team_alias || team.team_id,+ value: team.team_id,+ sublabel: team.team_id,+ })),+ ),+ [data],+ );++ return (+ <FormField control={control} name={`teams.${index}.team_id`} label="Team">+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (+ <PaginatedSearchSelect+ options={options}+ value={value}+ onValueChange={onChange}+ onSearchChange={setSearch}+ onLoadMore={() => void fetchNextPage()}+ hasNextPage={hasNextPage}+ isLoading={isLoading}+ isFetchingNextPage={isFetchingNextPage}+ placeholder="Search a team"+ emptyText="No teams found"+ inputId={id}+ aria-invalid={ariaInvalid}+ aria-describedby={ariaDescribedBy}+ />+ )}+ </FormField>+ );+};++const TeamsField = ({ control }: { control: SettingsControl }) => {+ const { fields, append, remove } = useFieldArray({ control, name: "teams" });++ return (+ <div className="flex w-full flex-col gap-3">+ <div>+ <p className="text-sm font-medium">Default Teams</p>+ <p className="text-sm text-muted-foreground">+ New users are added to these teams. Only teams that already exist can be selected.+ </p>+ </div>++ {fields.map((field, index) => (+ <div key={field.id} className="rounded-lg border border-border p-4">+ <div className="mb-3 flex items-center justify-between">+ <p className="text-sm font-medium">Team {index + 1}</p>+ <Button type="button" variant="destructive" size="sm" onClick={() => remove(index)}>+ Remove+ </Button>+ </div>++ <div className="grid grid-cols-1 gap-3 md:grid-cols-3">+ <TeamPickerField control={control} index={index} />++ <FormField control={control} name={`teams.${index}.max_budget_in_team`} label="Max Budget in Team (USD)">+ {({ ref, ...budgetField }) => (+ <Input {...budgetField} ref={ref} type="number" step={0.01} min={0} placeholder="Optional" />+ )}+ </FormField>++ <FormField control={control} name={`teams.${index}.user_role`} label="Team Role">+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (+ <Select+ items={TEAM_ROLE_OPTIONS}+ value={value}+ onValueChange={(selected) => onChange(selected ?? "user")}+ >+ <SelectTrigger+ id={id}+ className="w-full"+ aria-invalid={ariaInvalid}+ aria-describedby={ariaDescribedBy}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {TEAM_ROLE_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </FormField>+ </div>+ </div>+ ))}++ <Button type="button" variant="outline" onClick={() => append(EMPTY_TEAM_ROW)}>+ Add Team+ </Button>+ </div>+ );+};++const ViewRow = ({ label, children }: { label: string; children: React.ReactNode }) => (+ <div>+ <p className="text-sm font-medium">{label}</p>+ <p className="text-sm text-muted-foreground">{children}</p>+ </div>+);++interface SettingsViewProps {+ values: DefaultUserSettingsFormValues;+ roleOptions: readonly RoleOption[];+}++const SettingsView = ({ values, roleOptions }: SettingsViewProps) => {+ const roleLabel = roleOptions.find((option) => option.value === values.user_role)?.label ?? values.user_role;+ const durationValue = values.budget_duration === "" ? NO_RESET : values.budget_duration;+ const durationLabel =+ BUDGET_DURATION_OPTIONS.find((option) => option.value === durationValue)?.label ?? values.budget_duration;++ return (+ <div className="flex flex-col gap-4">+ <ViewRow label="Default Role">{roleLabel === "" ? "Not set" : roleLabel}</ViewRow>+ <ViewRow label="Max Budget (USD)">{values.max_budget === "" ? "Not set" : values.max_budget}</ViewRow>+ <ViewRow label="Reset Budget">{durationLabel}</ViewRow>+ <ViewRow label="Default Models">+ {values.models.length === 0+ ? "Not set"+ : values.models.map((model) => MODEL_SENTINEL_LABELS.get(model) ?? model).join(", ")}+ </ViewRow>+ <div>+ <p className="text-sm font-medium">Default Teams</p>+ {values.teams.length === 0 ? (+ <p className="text-sm text-muted-foreground">None</p>+ ) : (+ values.teams.map((team) => (+ <p key={team.team_id} className="text-sm text-muted-foreground">+ {team.team_id}+ {team.max_budget_in_team !== "" && <> · ${team.max_budget_in_team} max budget</>}+ <> · {team.user_role}</>+ </p>+ ))+ )}+ </div>+ </div>+ );+};++interface SettingsFormProps {+ initialValues: DefaultUserSettingsFormValues;+ roleOptions: readonly RoleOption[];+ updateSettings: (body: DefaultInternalUserParams) => Promise<void>;+ onCancel: () => void;+ onSaved: () => void;+}++const SettingsForm = ({ initialValues, roleOptions, updateSettings, onCancel, onSaved }: SettingsFormProps) => {+ const queryClient = useQueryClient();+ const form = useZodForm(defaultUserSettingsSchema, { defaultValues: initialValues });+ const { isDirty } = form.formState;++ const mutation = useMutation({+ mutationFn: (values: DefaultUserSettingsFormValues) => updateSettings(buildBody(values)),+ onSuccess: (_result, values) => {+ NotificationsManager.success("Default user settings updated successfully");+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEY });+ form.reset(values);+ onSaved();+ },+ onError: (error: unknown) =>+ NotificationsManager.fromBackend(+ error instanceof Error ? error.message : "Failed to update default user settings",+ ),+ });++ const onSubmit = form.handleSubmit((values) => mutation.mutate(values));++ return (+ <form onSubmit={onSubmit}>+ <FieldGroup>+ <FormField+ control={form.control}+ name="user_role"+ label="Default Role"+ description="Role assigned to new users"+ >+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (+ <Select+ items={roleOptions}+ value={value === "" ? null : value}+ onValueChange={(selected) => onChange(selected ?? "")}+ >+ <SelectTrigger id={id} className="w-full" aria-invalid={ariaInvalid} aria-describedby={ariaDescribedBy}>+ <SelectValue placeholder="Not set" />+ </SelectTrigger>+ <SelectContent>+ {roleOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <span>{option.label}</span>+ {option.description !== "" && (+ <span className="text-xs text-muted-foreground">{option.description}</span>+ )}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </FormField>++ <FormField+ control={form.control}+ name="max_budget"+ label="Max Budget (USD)"+ description="Default maximum budget for new users"+ >+ {({ ref, ...field }) => <Input {...field} ref={ref} type="number" step={0.01} min={0} />}+ </FormField>++ <FormField+ control={form.control}+ name="budget_duration"+ label="Reset Budget"+ description="How often the default budget resets"+ >+ {({ id, value, onChange, "aria-invalid": ariaInvalid, "aria-describedby": ariaDescribedBy }) => (+ <Select+ items={BUDGET_DURATION_OPTIONS}+ value={value === "" ? NO_RESET : value}+ onValueChange={(selected) => onChange(selected === null || selected === NO_RESET ? "" : selected)}+ >+ <SelectTrigger id={id} className="w-full" aria-invalid={ariaInvalid} aria-describedby={ariaDescribedBy}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {BUDGET_DURATION_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </FormField>++ <FormField+ control={form.control}+ name="models"+ label="Default Models"+ description="Models new users can access"+ >+ {(field) => (+ <ModelSelect+ value={field.value}+ onChange={field.onChange}+ context="global"+ options={{ includeSpecialOptions: true }}+ />+ )}+ </FormField>++ <TeamsField control={form.control} />+ </FieldGroup>++ <div className="mt-6 flex items-center justify-end gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => {+ form.reset(initialValues);+ onCancel();+ }}+ disabled={mutation.isPending}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={!isDirty || mutation.isPending}>+ {mutation.isPending ? "Saving..." : "Save Changes"}+ </Button>+ </div>+ </form>+ );+};++const SettingsCard = ({ action, children }: { action?: React.ReactNode; children: React.ReactNode }) => (+ <Card>+ <CardHeader>+ <CardTitle>Default User Settings</CardTitle>+ <CardDescription>+ Applied to every new internal user created through SSO or the user management APIs.+ </CardDescription>+ {action !== undefined && <CardAction>{action}</CardAction>}+ </CardHeader>+ <CardContent>{children}</CardContent>+ </Card>+);++export interface DefaultUserSettingsFormProps {+ possibleUIRoles?: Record<string, Record<string, string>> | null;+ fetchSettings?: () => Promise<InternalUserSettings>;+ updateSettings?: (body: DefaultInternalUserParams) => Promise<void>;+}++export const DefaultUserSettingsForm = ({+ possibleUIRoles,+ fetchSettings = defaultFetchSettings,+ updateSettings = defaultUpdateSettings,+}: DefaultUserSettingsFormProps) => {+ const [isEditing, setIsEditing] = React.useState(false);+ const { data, isPending, isError } = useQuery({ queryKey: SETTINGS_QUERY_KEY, queryFn: fetchSettings });++ const roleOptions = React.useMemo<RoleOption[]>(+ () =>+ Object.entries(possibleUIRoles ?? {})+ .filter(([role]) => role.includes("internal_user"))+ .map(([role, meta]) => ({ value: role, label: meta.ui_label || role, description: meta.description ?? "" })),+ [possibleUIRoles],+ );++ const initialValues = React.useMemo(() => (data === undefined ? undefined : settingsToForm(data.values)), [data]);++ if (isPending) {+ return (+ <SettingsCard>+ <Skeleton className="h-64 w-full" />+ </SettingsCard>+ );+ }++ if (isError || initialValues === undefined) {+ return (+ <SettingsCard>+ <p role="alert">Could not load the default user settings.</p>+ </SettingsCard>+ );+ }++ return (+ <SettingsCard+ action={+ isEditing ? undefined : (+ <Button type="button" onClick={() => setIsEditing(true)}>+ Edit Settings+ </Button>+ )+ }+ >+ {isEditing ? (+ <SettingsForm+ initialValues={initialValues}+ roleOptions={roleOptions}+ updateSettings={updateSettings}+ onCancel={() => setIsEditing(false)}+ onSaved={() => setIsEditing(false)}+ />+ ) : (+ <SettingsView values={initialValues} roleOptions={roleOptions} />+ )}+ </SettingsCard>+ );+};diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.test.tsnew file mode 100644index 00000000000..e8b350332c8--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";++import { buildBody, settingsToForm } from "./mapper";+import type { DefaultUserSettingsFormValues } from "./schema";++const CONFIGURED_SETTINGS = {+ user_role: "internal_user",+ max_budget: 100.5,+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-1", max_budget_in_team: 25, user_role: "admin" }],+};++const UNCONFIGURED_SETTINGS = {+ user_role: "internal_user_viewer",+ max_budget: null,+ budget_duration: null,+ models: null,+ teams: null,+};++const CONFIGURED_FORM = {+ user_role: "internal_user",+ max_budget: "100.5",+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-1", max_budget_in_team: "25", user_role: "admin" }],+};++const UNCONFIGURED_FORM = {+ user_role: "internal_user_viewer",+ max_budget: "",+ budget_duration: "",+ models: [],+ teams: [],+};++describe("settingsToForm", () => {+ it("maps a fully populated settings blob onto widget-space strings", () => {+ expect(settingsToForm(CONFIGURED_SETTINGS)).toStrictEqual(CONFIGURED_FORM);+ });++ it("maps an unconfigured settings blob onto empty widget state", () => {+ expect(settingsToForm(UNCONFIGURED_SETTINGS)).toStrictEqual(UNCONFIGURED_FORM);+ });++ it("hydrates the legacy list-of-team-ids shape as full team rows", () => {+ expect(settingsToForm({ teams: ["team-1", "team-2"] }).teams).toStrictEqual([+ { team_id: "team-1", max_budget_in_team: "", user_role: "user" },+ { team_id: "team-2", max_budget_in_team: "", user_role: "user" },+ ]);+ });++ it("defaults a team row's role to user and leaves an absent in-team budget blank", () => {+ expect(settingsToForm({ teams: [{ team_id: "team-1" }] }).teams).toStrictEqual([+ { team_id: "team-1", max_budget_in_team: "", user_role: "user" },+ ]);+ });++ it("degrades an unrecognisable team entry to a blank row instead of throwing", () => {+ expect(settingsToForm({ teams: [{ max_budget_in_team: 5 }, 7] }).teams).toStrictEqual([+ { team_id: "", max_budget_in_team: "", user_role: "user" },+ { team_id: "", max_budget_in_team: "", user_role: "user" },+ ]);+ });+});++const formValues = (overrides: Partial<DefaultUserSettingsFormValues> = {}): DefaultUserSettingsFormValues => ({+ user_role: "internal_user",+ max_budget: "100",+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-1", max_budget_in_team: "25", user_role: "admin" }],+ ...overrides,+});++const SAVED_BODY = {+ user_role: "internal_user",+ max_budget: 100,+ budget_duration: "30d",+ models: ["gpt-5.2"],+ teams: [{ team_id: "team-1", max_budget_in_team: 25, user_role: "admin" }],+};++const CLEARED_FORM = { user_role: "", max_budget: "", budget_duration: "", models: [], teams: [] };++const CLEARED_BODY = {+ user_role: null,+ max_budget: null,+ budget_duration: null,+ models: null,+ teams: null,+};++describe("buildBody", () => {+ it("sends every field, because the endpoint replaces the whole settings object", () => {+ expect(buildBody(formValues())).toStrictEqual(SAVED_BODY);+ });++ it("clears emptied fields with null so the backend drops them", () => {+ expect(buildBody(formValues(CLEARED_FORM))).toStrictEqual(CLEARED_BODY);+ });++ it("sends teams as objects and nulls an in-team budget that was left blank", () => {+ expect(+ buildBody(formValues({ teams: [{ team_id: "team-9", max_budget_in_team: "", user_role: "user" }] })),+ ).toStrictEqual({+ ...SAVED_BODY,+ teams: [{ team_id: "team-9", max_budget_in_team: null, user_role: "user" }],+ });+ });++ it("refuses to send a role the backend does not accept", () => {+ expect(buildBody(formValues({ user_role: "made_up_role" })).user_role).toBeNull();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.ts b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.tsnew file mode 100644index 00000000000..50365081afb--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/mapper.ts@@ -0,0 +1,75 @@+import { z } from "zod/v4";++import type { components } from "@/lib/http/schema";++import { EMPTY_TEAM_ROW, type DefaultTeamRowValues, type DefaultUserSettingsFormValues } from "./schema";++export type InternalUserSettings = components["schemas"]["InternalUserSettingsResponse"];+export type DefaultInternalUserParams = components["schemas"]["DefaultInternalUserParams"];+type DefaultTeamBody = components["schemas"]["NewUserRequestTeam"];++const teamRowFromServer = z+ .union([+ z.string().transform((teamId): DefaultTeamRowValues => ({ ...EMPTY_TEAM_ROW, team_id: teamId })),+ z+ .object({+ team_id: z.string(),+ max_budget_in_team: z.number().nullish(),+ user_role: z.enum(["user", "admin"]).catch("user"),+ })+ .transform(+ (team): DefaultTeamRowValues => ({+ team_id: team.team_id,+ max_budget_in_team: team.max_budget_in_team?.toString() ?? "",+ user_role: team.user_role,+ }),+ ),+ ])+ .catch(EMPTY_TEAM_ROW);++const serverValuesShape = {+ user_role: z.string().nullish().catch(null),+ max_budget: z.number().nullish().catch(null),+ budget_duration: z.string().nullish().catch(null),+ models: z.array(z.string()).nullish().catch(null),+ teams: z.array(teamRowFromServer).nullish().catch(null),+};++const serverValuesSchema = z.object(serverValuesShape);++export const settingsToForm = (values: InternalUserSettings["values"]): DefaultUserSettingsFormValues => {+ const parsed = serverValuesSchema.parse(values);++ return {+ user_role: parsed.user_role ?? "",+ max_budget: parsed.max_budget?.toString() ?? "",+ budget_duration: parsed.budget_duration ?? "",+ models: parsed.models ?? [],+ teams: parsed.teams ?? [],+ };+};++const DEFAULT_USER_ROLES = ["internal_user", "internal_user_viewer", "proxy_admin", "proxy_admin_viewer"] as const;++const asDefaultUserRole = (raw: string): DefaultInternalUserParams["user_role"] =>+ DEFAULT_USER_ROLES.find((role) => role === raw) ?? null;++const numberOrNull = (raw: string): number | null => (raw.trim() === "" ? null : Number(raw));++const textOrNull = (raw: string): string | null => (raw.trim() === "" ? null : raw);++const listOrNull = <T>(items: readonly T[]): T[] | null => (items.length === 0 ? null : [...items]);++const toTeamBody = (team: DefaultTeamRowValues): DefaultTeamBody => ({+ team_id: team.team_id,+ max_budget_in_team: numberOrNull(team.max_budget_in_team),+ user_role: team.user_role,+});++export const buildBody = (values: DefaultUserSettingsFormValues): DefaultInternalUserParams => ({+ user_role: asDefaultUserRole(values.user_role),+ max_budget: numberOrNull(values.max_budget),+ budget_duration: textOrNull(values.budget_duration),+ models: listOrNull(values.models),+ teams: listOrNull(values.teams.map(toTeamBody)),+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.test.tsnew file mode 100644index 00000000000..889f87f2203--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";++import { defaultUserSettingsSchema, type DefaultUserSettingsFormValues } from "./schema";++const values = (overrides: Partial<DefaultUserSettingsFormValues> = {}): DefaultUserSettingsFormValues => ({+ user_role: "internal_user",+ max_budget: "",+ budget_duration: "",+ models: [],+ teams: [],+ ...overrides,+});++const issuesFor = (input: DefaultUserSettingsFormValues) => {+ const result = defaultUserSettingsSchema.safeParse(input);+ return result.success ? [] : result.error.issues.map((issue) => ({ path: issue.path, message: issue.message }));+};++describe("defaultUserSettingsSchema", () => {+ it("accepts settings with no default teams", () => {+ expect(defaultUserSettingsSchema.safeParse(values()).success).toBe(true);+ });++ it("rejects a team row that has no team selected", () => {+ expect(issuesFor(values({ teams: [{ team_id: "", max_budget_in_team: "", user_role: "user" }] }))).toStrictEqual([+ { path: ["teams", 0, "team_id"], message: "Select a team" },+ ]);+ });++ it("rejects the same team appearing twice", () => {+ expect(+ issuesFor(+ values({+ teams: [+ { team_id: "team-1", max_budget_in_team: "", user_role: "user" },+ { team_id: "team-1", max_budget_in_team: "", user_role: "admin" },+ ],+ }),+ ),+ ).toStrictEqual([{ path: ["teams", 1, "team_id"], message: "This team is already listed" }]);+ });++ it("does not treat two blank rows as duplicates of each other", () => {+ const issues = issuesFor(+ values({+ teams: [+ { team_id: "", max_budget_in_team: "", user_role: "user" },+ { team_id: "", max_budget_in_team: "", user_role: "user" },+ ],+ }),+ );++ expect(issues.map((issue) => issue.message)).toStrictEqual(["Select a team", "Select a team"]);+ });++ it("rejects non-numeric budgets on the form and on a team row", () => {+ expect(issuesFor(values({ max_budget: "lots" }))).toStrictEqual([+ { path: ["max_budget"], message: "Must be a non-negative number" },+ ]);+ expect(+ issuesFor(values({ teams: [{ team_id: "team-1", max_budget_in_team: "-5", user_role: "user" }] })),+ ).toStrictEqual([{ path: ["teams", 0, "max_budget_in_team"], message: "Must be a non-negative number" }]);+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.ts b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.tsnew file mode 100644index 00000000000..7309e3745da--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/default-user-settings/schema.ts@@ -0,0 +1,44 @@+import { z } from "zod/v4";++const isBlank = (value: string): boolean => value.trim() === "";++const amountOrEmpty = z+ .string()+ .refine(+ (value) => isBlank(value) || (Number.isFinite(Number(value)) && Number(value) >= 0),+ "Must be a non-negative number",+ );++const defaultTeamRowSchema = z.object({+ team_id: z.string().min(1, "Select a team"),+ max_budget_in_team: amountOrEmpty,+ user_role: z.enum(["user", "admin"]),+});++export type DefaultTeamRowValues = z.output<typeof defaultTeamRowSchema>;++export const EMPTY_TEAM_ROW: DefaultTeamRowValues = { team_id: "", max_budget_in_team: "", user_role: "user" };++const defaultUserSettingsShape = {+ user_role: z.string(),+ max_budget: amountOrEmpty,+ budget_duration: z.string(),+ models: z.array(z.string()),+ teams: z.array(defaultTeamRowSchema),+};++export const defaultUserSettingsSchema = z.object(defaultUserSettingsShape).superRefine((values, ctx) => {+ const repeatedRows = values.teams.flatMap((team, index) =>+ team.team_id !== "" && values.teams.findIndex((other) => other.team_id === team.team_id) < index ? [index] : [],+ );++ repeatedRows.forEach((index) =>+ ctx.addIssue({+ code: "custom",+ message: "This team is already listed",+ path: ["teams", index, "team_id"],+ }),+ );+});++export type DefaultUserSettingsFormValues = z.output<typeof defaultUserSettingsSchema>;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.test.tsxindex 8dc11babd72..5fcc55c1e98 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.test.tsx@@ -27,7 +27,6 @@ vi.mock("@/components/networking", () => ({DEFAULT_TEAM_DISABLED: false,SSO_ENABLED: false,}),- getInternalUserSettings: vi.fn().mockResolvedValue({}),}));// The detail view has its own test; stub it so this file covers the parent's swap.diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.tsxindex ce912c09373..2c1d28d82f8 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users.tsx@@ -30,7 +30,7 @@ import {import DeleteResourceModal from "@/components/common_components/DeleteResourceModal";import NotificationsManager from "@/components/molecules/notifications_manager";import { modelAvailableCall, userDeleteCall } from "@/components/networking";-import DefaultUserSettings from "./DefaultUserSettings";+import { DefaultUserSettingsForm } from "./default-user-settings/DefaultUserSettingsForm";import { UsersTable } from "./view_users/UsersTable";import UserInfoView from "./view_users/user_info_view";import { UserInfo } from "@/components/networking";@@ -412,12 +412,7 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({<Skeleton active paragraph={{ rows: 4 }} /></div>) : (- <DefaultUserSettings- accessToken={accessToken}- possibleUIRoles={possibleUIRoles}- userID={userID}- userRole={userRole}- />+ <DefaultUserSettingsForm possibleUIRoles={possibleUIRoles} />)}</TabPanel></TabPanels>diff --git a/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx b/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsxindex 898374d2a61..0965683c241 100644--- a/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx+++ b/ui/litellm-dashboard/src/components/ModelSelect/ModelSelect.tsx@@ -16,7 +16,7 @@ const MODEL_SELECT_NO_DEFAULT_MODELS_SPECIAL_VALUE = {value: "no-default-models",} as const;-const MODEL_SELECT_SPECIAL_VALUES_ARRAY = [+export const MODEL_SENTINEL_OPTIONS = [MODEL_SELECT_ALL_PROXY_MODELS_SPECIAL_VALUE,MODEL_SELECT_NO_DEFAULT_MODELS_SPECIAL_VALUE,] as const;@@ -100,7 +100,7 @@ export const ModelSelect = (props: ModelSelectProps) => {const { data: organization, isLoading: isLoadingOrganization } = useOrganization(organizationID);const { data: currentUser, isLoading: isCurrentUserLoading } = useCurrentUser();- const isSpecialOption = (value: string) => MODEL_SELECT_SPECIAL_VALUES_ARRAY.some((sv) => sv.value === value);+ const isSpecialOption = (value: string) => MODEL_SENTINEL_OPTIONS.some((sv) => sv.value === value);const hasSpecialOptionSelected = value.some(isSpecialOption);const isLoading = isLoadingAllProxyModels || isLoadingTeam || isLoadingOrganization || isCurrentUserLoading;const organizationHasAllProxyModels =diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 576e16cbb37..22dc087e150 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -4749,45 +4749,6 @@ export const uiSpendLogDetailsCall = async (accessToken: string, logId: string,}};-export const getInternalUserSettings = async (accessToken: string) => {- try {- const data = await apiClient.get(`/get/internal_user_settings`, { accessToken });- return data;- } catch (error) {- console.error("Failed to fetch SSO settings:", error);- throw error;- }-};--export const updateInternalUserSettings = async (accessToken: string, settings: Record<string, any>) => {- try {- // Construct base URL- let url = proxyBaseUrl ? `${proxyBaseUrl}/update/internal_user_settings` : `/update/internal_user_settings`;-- const response = await fetch(url, {- method: "PATCH",- headers: {- [globalLitellmHeaderName]: `Bearer ${accessToken}`,- "Content-Type": "application/json",- },- body: JSON.stringify(settings),- });-- if (!response.ok) {- const errorData = await response.text();- handleError(errorData);- throw new Error(errorData);- }-- const data = await response.json();- NotificationsManager.success("Internal user settings updated successfully");- return data;- } catch (error) {- console.error("Failed to update internal user settings:", error);- throw error;- }-};-export const fetchOpenAPIRegistry = async (accessToken: string) => {try {const url = proxyBaseUrl ? `${proxyBaseUrl}/v1/mcp/openapi-registry` : `/v1/mcp/openapi-registry`;diff --git a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsxindex b59cd1263ea..fde29fd5362 100644--- a/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx+++ b/ui/litellm-dashboard/src/components/shared/PaginatedSearchSelect.tsx@@ -34,6 +34,9 @@ interface PaginatedSearchSelectProps {loadingText?: string;disabled?: boolean;className?: string;+ inputId?: string;+ "aria-invalid"?: true | undefined;+ "aria-describedby"?: string;}export function PaginatedSearchSelect({@@ -50,6 +53,9 @@ export function PaginatedSearchSelect({loadingText = "Loading…",disabled = false,className,+ inputId,+ "aria-invalid": ariaInvalid,+ "aria-describedby": ariaDescribedBy,}: PaginatedSearchSelectProps) {const selected = useMemo<SearchSelectOption | null>(() => {if (value === undefined || value === "") return null;@@ -90,6 +96,9 @@ export function PaginatedSearchSelect({disabled={disabled}><ComboboxInput+ id={inputId}+ aria-invalid={ariaInvalid}+ aria-describedby={ariaDescribedBy}placeholder={placeholder}showClear={value !== undefined && value !== ""}className={`w-full ${className ?? ""}`}diff --git a/ui/litellm-dashboard/src/lib/http/client.test.ts b/ui/litellm-dashboard/src/lib/http/client.test.tsindex e0b5a73d11a..ac1bc86f871 100644--- a/ui/litellm-dashboard/src/lib/http/client.test.ts+++ b/ui/litellm-dashboard/src/lib/http/client.test.ts@@ -119,4 +119,10 @@ describe("deriveErrorMessage", () => {it("falls back to a string detail field", () => {expect(deriveErrorMessage({ detail: "detail text" })).toBe("detail text");});++ it("unwraps the HTTPException detail.error shape management endpoints raise", () => {+ expect(deriveErrorMessage({ detail: { error: "Team(s) not found: ghost-team" } })).toBe(+ "Team(s) not found: ghost-team",+ );+ });});diff --git a/ui/litellm-dashboard/src/lib/http/client.ts b/ui/litellm-dashboard/src/lib/http/client.tsindex e2b47f7b354..1370d3e9273 100644--- a/ui/litellm-dashboard/src/lib/http/client.ts+++ b/ui/litellm-dashboard/src/lib/http/client.ts@@ -44,13 +44,15 @@ export class ApiError extends Error {* Lives here because error parsing is the client's job; networking.tsx re-exports* it so existing `@/components/networking` import paths keep working.*/+const deriveDetailMessage = (detail: any): string | undefined => {+ if (Array.isArray(detail)) return detail.map((d: any) => d?.msg || JSON.stringify(d)).join("; ");+ if (typeof detail === "string") return detail;+ if (typeof detail?.error === "string") return detail.error;+ return undefined;+};+export const deriveErrorMessage = (errorData: any): string => {- const detail = errorData?.detail;- const detailStr = Array.isArray(detail)- ? detail.map((d: any) => d?.msg || JSON.stringify(d)).join("; ")- : typeof detail === "string"- ? detail- : undefined;+ const detailStr = deriveDetailMessage(errorData?.detail);return ((errorData?.error &&(errorData.error.message || (typeof errorData.error === "string" ? errorData.error : undefined))) ||