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): let access groups be a team's only model source, with hover provenance (#36234)
ryan-crabbe-berri2a9aac700452
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex c8765eb0bd0..32b8eb3d4d0 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -99,19 +99,19 @@"limit": 0},"reportUnknownArgumentType": {- "limit": 45110+ "limit": 45098},"reportUnknownLambdaType": {"limit": 113},"reportUnknownMemberType": {- "limit": 39838+ "limit": 39826},"reportUnknownParameterType": {"limit": 20237},"reportUnknownVariableType": {- "limit": 31383+ "limit": 31371},"reportUnnecessaryCast": {"limit": 122diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 5b7dc3a7c73..1fc05ac4653 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -3894,12 +3894,19 @@ class OrganizationMemberUpdateResponse(MemberUpdateResponse):##########################################+class TeamAccessGroupModelGrant(LiteLLMPydanticObjectBase):+ access_group_id: str+ access_group_name: str+ models: tuple[str, ...]++class TeamInfoResponseObjectTeamTable(LiteLLM_TeamTable):team_member_budget_table: LiteLLM_BudgetTableFull | None = None# Resources inherited from access groups (separate from direct assignments)access_group_models: list[str] | None = Noneaccess_group_mcp_server_ids: list[str] | None = Noneaccess_group_agent_ids: list[str] | None = None+ access_group_details: tuple[TeamAccessGroupModelGrant, ...] | None = Noneclass TeamInfoResponseObject(TypedDict):diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex fe5a0e06d2e..0b99879f9fe 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -57,6 +57,7 @@ from litellm.proxy._types import (SpecialManagementEndpointEnums,SpecialModelNames,SpecialProxyStrings,+ TeamAccessGroupModelGrant,TeamAddMemberResponse,TeamInfoResponseObject,TeamInfoResponseObjectTeamTable,@@ -3829,7 +3830,7 @@ async def _add_team_member_budget_table() -> TeamInfoResponseObjectTeamTable:try:team_budget: Final = await _budget_db(prisma_client).find_unique(where={"budget_id": team_member_budget_id})- team_info_response_object.team_member_budget_table = team_budget+ return team_info_response_object.model_copy(update={"team_member_budget_table": team_budget})except Exception:verbose_proxy_logger.info("Team member budget table not found, passed team_member_budget_id=%s", team_member_budget_id@@ -3838,21 +3839,34 @@ async def _add_team_member_budget_table(return team_info_response_object-async def _resolve_team_access_group_resources(_team_info: TeamInfoResponseObjectTeamTable) -> None:- """Populate access_group_models / mcp_server_ids / agent_ids on the team- info response by resolving inherited resources from its access groups."""+async def _resolve_team_access_group_resources(+ _team_info: TeamInfoResponseObjectTeamTable,+) -> TeamInfoResponseObjectTeamTable:+ """Return a copy of the team info with access_group_models / mcp_server_ids /+ agent_ids / details resolved from its access groups."""if not _team_info.access_group_ids:- return+ return _team_infoag_lookup: Final = await _batch_resolve_access_group_resources(_team_info.access_group_ids)- models, mcp_ids, agent_ids = set(), set(), set()- for ag_id in _team_info.access_group_ids:- if ag_id in ag_lookup:- models.update(ag_lookup[ag_id]["models"])- mcp_ids.update(ag_lookup[ag_id]["mcp_server_ids"])- agent_ids.update(ag_lookup[ag_id]["agent_ids"])- _team_info.access_group_models = list(models)- _team_info.access_group_mcp_server_ids = list(mcp_ids)- _team_info.access_group_agent_ids = list(agent_ids)+ resolved_groups: Final = tuple(+ ag_lookup[ag_id] for ag_id in dict.fromkeys(_team_info.access_group_ids) if ag_id in ag_lookup+ )+ return _team_info.model_copy(+ update={+ "access_group_models": list({m for group in resolved_groups for m in (group.access_model_names or [])}),+ "access_group_mcp_server_ids": list(+ {s for group in resolved_groups for s in (group.access_mcp_server_ids or [])}+ ),+ "access_group_agent_ids": list({a for group in resolved_groups for a in (group.access_agent_ids or [])}),+ "access_group_details": tuple(+ TeamAccessGroupModelGrant(+ access_group_id=group.access_group_id,+ access_group_name=group.access_group_name,+ models=tuple(group.access_model_names or ()),+ )+ for group in resolved_groups+ ),+ }+ )@router.get("/team/info", tags=["team management"], dependencies=[Depends(user_api_key_auth)])@@ -3958,11 +3972,11 @@ async def team_info()# Resolve resources inherited from access groups- await _resolve_team_access_group_resources(_team_info)+ resolved_team_info: Final = await _resolve_team_access_group_resources(_team_info)response_object: Final = TeamInfoResponseObject(team_id=team_id,- team_info=_team_info,+ team_info=resolved_team_info,keys=keys,team_memberships=returned_tm,)@@ -4391,32 +4405,21 @@ async def _build_team_list_where_conditions(async def _batch_resolve_access_group_resources(all_access_group_ids: list[str],-) -> dict[str, dict[str, list[str]]]:+) -> dict[str, LiteLLM_AccessGroupTable]:"""- Batch-fetch access groups in a single DB query and return a per-group- resource map.-- Returns {ag_id: {"models": [...], "mcp_server_ids": [...], "agent_ids": [...]}}.- Missing/invalid groups are silently omitted.+ Batch-fetch access groups in a single DB query and return them keyed by+ access_group_id. Missing/invalid groups are silently omitted."""from litellm.proxy.proxy_server import prisma_client as _prisma_clientif not all_access_group_ids or _prisma_client is None:return {}- unique_ids: Final = list(set(all_access_group_ids))+ unique_ids: Final = tuple(frozenset(all_access_group_ids))rows: Final = await _access_group_db(_prisma_client).find_many(where={"access_group_id": {"in": unique_ids}},)-- result: Final[dict[str, dict[str, list[str]]]] = {}- for row in rows:- result[row.access_group_id] = {- "models": list(row.access_model_names or []),- "mcp_server_ids": list(row.access_mcp_server_ids or []),- "agent_ids": list(row.access_agent_ids or []),- }- return result+ return {row.access_group_id: row for row in rows}def _convert_teams_to_response_models(@@ -4710,15 +4713,18 @@ async def list_team_v2(all_ag_ids: Final = [ag_id for t in team_items_with_ag for ag_id in (t.access_group_ids or [])]ag_lookup: Final = await _batch_resolve_access_group_resources(all_ag_ids)for team_item in team_items_with_ag:- models, mcp_ids, agent_ids = set(), set(), set()- for ag_id in team_item.access_group_ids or []:- if ag_id in ag_lookup:- models.update(ag_lookup[ag_id]["models"])- mcp_ids.update(ag_lookup[ag_id]["mcp_server_ids"])- agent_ids.update(ag_lookup[ag_id]["agent_ids"])- team_item.access_group_models = list(models)- team_item.access_group_mcp_server_ids = list(mcp_ids)- team_item.access_group_agent_ids = list(agent_ids)+ team_groups = tuple(+ ag_lookup[ag_id] for ag_id in (team_item.access_group_ids or []) if ag_id in ag_lookup+ )+ team_item.access_group_models = list(+ {m for group in team_groups for m in (group.access_model_names or [])}+ )+ team_item.access_group_mcp_server_ids = list(+ {s for group in team_groups for s in (group.access_mcp_server_ids or [])}+ )+ team_item.access_group_agent_ids = list(+ {a for group in team_groups for a in (group.access_agent_ids or [])}+ )return {"teams": team_list,diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.pyindex eedffa1ea5f..a1cbc77b7a5 100644--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py@@ -8637,9 +8637,9 @@ class TestBatchResolveAccessGroupResources:with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):result = await _batch_resolve_access_group_resources(["ag-1"])- assert sorted(result["ag-1"]["models"]) == ["claude-3", "gpt-4"]- assert result["ag-1"]["mcp_server_ids"] == ["mcp-1"]- assert sorted(result["ag-1"]["agent_ids"]) == ["agent-1", "agent-2"]+ assert sorted(result["ag-1"].access_model_names) == ["claude-3", "gpt-4"]+ assert result["ag-1"].access_mcp_server_ids == ["mcp-1"]+ assert sorted(result["ag-1"].access_agent_ids) == ["agent-1", "agent-2"]@pytest.mark.asyncioasync def test_multiple_access_groups(self):@@ -8668,8 +8668,8 @@ class TestBatchResolveAccessGroupResources:with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):result = await _batch_resolve_access_group_resources(["ag-1", "ag-2"])- assert result["ag-1"]["models"] == ["gpt-4"]- assert result["ag-2"]["models"] == ["gemini"]+ assert result["ag-1"].access_model_names == ["gpt-4"]+ assert result["ag-2"].access_model_names == ["gemini"]@pytest.mark.asyncioasync def test_missing_access_group_omitted(self):@@ -8735,6 +8735,75 @@ class TestBatchResolveAccessGroupResources:assert "ag-1" in result+class TestResolveTeamAccessGroupResources:+ """Tests for the per-team access group resolution on /team/info."""++ @pytest.mark.asyncio+ async def test_populates_flat_lists_and_per_group_details(self):+ """access_group_details must attribute each model to the group granting it,+ so the UI can show provenance on hover; flat lists stay for back-compat.+ Duplicated ids must collapse to one entry (response amplification), and the+ input object must stay untouched (resolution returns a copy)."""+ from litellm.proxy._types import TeamInfoResponseObjectTeamTable+ from litellm.proxy.management_endpoints.team_endpoints import (+ _resolve_team_access_group_resources,+ )++ row1 = MagicMock()+ row1.access_group_id = "ag-1"+ row1.access_group_name = "shared-models"+ row1.access_model_names = ["gpt-4", "claude-3"]+ row1.access_mcp_server_ids = ["mcp-1"]+ row1.access_agent_ids = []++ row2 = MagicMock()+ row2.access_group_id = "ag-2"+ row2.access_group_name = "extra-models"+ row2.access_model_names = ["claude-3", "gemini"]+ row2.access_mcp_server_ids = []+ row2.access_agent_ids = ["agent-1"]++ fake_prisma = MagicMock()+ fake_prisma.db.litellm_accessgrouptable.find_many = AsyncMock(+ return_value=[row1, row2]+ )++ team_info = TeamInfoResponseObjectTeamTable(+ team_id="team-1", access_group_ids=["ag-1", "ag-2", "ag-1", "ag-missing"]+ )+ with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):+ resolved = await _resolve_team_access_group_resources(team_info)++ assert team_info.access_group_details is None+ assert sorted(resolved.access_group_models or []) == [+ "claude-3",+ "gemini",+ "gpt-4",+ ]+ assert resolved.access_group_mcp_server_ids == ["mcp-1"]+ assert resolved.access_group_agent_ids == ["agent-1"]+ assert [+ (d.access_group_id, d.access_group_name, d.models)+ for d in (resolved.access_group_details or [])+ ] == [+ ("ag-1", "shared-models", ("gpt-4", "claude-3")),+ ("ag-2", "extra-models", ("claude-3", "gemini")),+ ]++ @pytest.mark.asyncio+ async def test_no_access_groups_leaves_details_unset(self):+ from litellm.proxy._types import TeamInfoResponseObjectTeamTable+ from litellm.proxy.management_endpoints.team_endpoints import (+ _resolve_team_access_group_resources,+ )++ team_info = TeamInfoResponseObjectTeamTable(team_id="team-1", access_group_ids=[])+ resolved = await _resolve_team_access_group_resources(team_info)++ assert resolved.access_group_details is None+ assert resolved.access_group_models is None++@pytest.mark.asyncioasync def test_verify_team_access_denies_unauthorized_user():"""diff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex 991f8eaa934..0a0cfe9a617 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -1,9 +1,9 @@{"LIT001": {- "limit": 23245+ "limit": 23235},"LIT002": {- "limit": 27179+ "limit": 27176},"LIT003": {"limit": 269@@ -30,6 +30,6 @@"limit": 16769},"LIT011": {- "limit": 5602+ "limit": 5598}}diff --git a/ui/litellm-dashboard/src/components/Teams.test.tsx b/ui/litellm-dashboard/src/components/Teams.test.tsxindex 2bda0f72cec..e8331294972 100644--- a/ui/litellm-dashboard/src/components/Teams.test.tsx+++ b/ui/litellm-dashboard/src/components/Teams.test.tsx@@ -613,6 +613,34 @@ describe("Teams - access_group_ids in team create", () => {);});});++ it("creates a team with no models selected, sending the no-default-models sentinel instead of an empty list", async () => {+ renderWithQueryClient(<Teams accessToken="test-token" userID="user-123" userRole="Admin" />);++ const createButton = screen.getAllByRole("button", { name: /create team/i })[0];+ act(() => {+ fireEvent.click(createButton);+ });++ await waitFor(() => {+ expect(screen.getByLabelText(/team name/i)).toBeInTheDocument();+ });++ fireEvent.change(screen.getByLabelText(/team name/i), { target: { value: "Group Only Team" } });++ const createTeamSubmitButtons = screen.getAllByRole("button", { name: /create team/i });+ fireEvent.click(createTeamSubmitButtons[createTeamSubmitButtons.length - 1]);++ await waitFor(() => {+ expect(teamCreateCall).toHaveBeenCalledWith(+ "test-token",+ expect.objectContaining({+ team_alias: "Group Only Team",+ models: ["no-default-models"],+ }),+ );+ });+ });});describe("Teams - metadata key-value pairs in team create", () => {diff --git a/ui/litellm-dashboard/src/components/Teams.tsx b/ui/litellm-dashboard/src/components/Teams.tsxindex 95642b93019..42ff8bcc4c2 100644--- a/ui/litellm-dashboard/src/components/Teams.tsx+++ b/ui/litellm-dashboard/src/components/Teams.tsx@@ -42,6 +42,7 @@ interface TeamProps {import DeleteResourceModal from "./common_components/DeleteResourceModal";import { teamCreateCall } from "./networking";+import { normalizeTeamModelSelection } from "./team/teamModelAccess";import { ModelSelect } from "./ModelSelect/ModelSelect";const canCreateOrManageTeams = (@@ -351,7 +352,7 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUser}}- await teamCreateCall(accessToken, formValues);+ await teamCreateCall(accessToken, { ...formValues, models: normalizeTeamModelSelection(formValues.models) });NotificationsManager.success("Team created");await refreshTeams();form.resetFields();@@ -618,17 +619,11 @@ const Teams: React.FC<TeamProps> = ({ accessToken, userID, userRole, premiumUserlabel={<span>Models{" "}- <Tooltip title="These are the models that your selected team has access to">+ <Tooltip title="These are the models that your selected team has access to. Leave empty to grant no models directly, e.g. when the team gets its models from access groups"><InfoCircleOutlined style={{ marginLeft: "4px" }} /></Tooltip></span>}- rules={[- {- required: true,- message: "Please select at least one model",- },- ]}name="models"><ModelSelectdiff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.tsxindex b7bbbba3aed..e57bf59b2da 100644--- a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamInfo.tsx@@ -35,6 +35,12 @@ import { CheckIcon, CopyIcon } from "lucide-react";import React, { useEffect, useMemo, useState } from "react";import { copyToClipboard as utilCopyToClipboard } from "../../utils/dataUtils";import AccessGroupSelector from "../common_components/AccessGroupSelector";+import {+ computeTeamModelBadges,+ normalizeTeamModelSelection,+ TeamAccessGroupModelGrant,+ TeamModelBadgeKind,+} from "./teamModelAccess";import MetadataKeyValueFields, {metadataObjectToPairs,metadataPairsToObject,@@ -82,6 +88,13 @@ const UI_MANAGED_METADATA_KEYS: ReadonlySet<string> = new Set(["disable_global_guardrails",]);+const TEAM_MODEL_BADGE_COLORS: Record<TeamModelBadgeKind, "red" | "gray" | "blue" | "green"> = {+ "all-proxy": "red",+ "no-default": "gray",+ direct: "blue",+ "access-group": "green",+};+export interface TeamMembership {user_id: string;team_id: string;@@ -132,6 +145,7 @@ export interface TeamData {access_group_models?: string[];access_group_mcp_server_ids?: string[];access_group_agent_ids?: string[];+ access_group_details?: TeamAccessGroupModelGrant[];router_settings?: Record<string, any>;guardrails?: string[];policies?: string[];@@ -483,7 +497,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({const updateData: any = {team_id: teamId,team_alias: values.team_alias,- models: values.models,+ models: normalizeTeamModelSelection(values.models),tpm_limit: sanitizeNumeric(values.tpm_limit),rpm_limit: sanitizeNumeric(values.rpm_limit),model_tpm_limit: modelTpmLimit,@@ -764,21 +778,14 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({<Card><Text>Models</Text><div className="mt-2 flex flex-wrap gap-2">- {info.models.length === 0 || info.models.includes("all-proxy-models") ? (- <Badge color="red">All proxy models</Badge>- ) : (- <>- {info.models.map((model: string, index: number) => (- <Badge key={`direct-${index}`} color="blue">- {model}- </Badge>- ))}- {(info.access_group_models || []).map((model: string, index: number) => (- <Badge key={`ag-${index}`} color="green" title="From access group">- {model}- </Badge>- ))}- </>+ {computeTeamModelBadges(info.models, info.access_group_models || [], info.access_group_details).map(+ (badge, index) => (+ <Tooltip key={`${badge.kind}-${badge.label}-${index}`} title={badge.tooltip}>+ <span>+ <Badge color={TEAM_MODEL_BADGE_COLORS[badge.kind]}>{badge.label}</Badge>+ </span>+ </Tooltip>+ ),)}</div></Card>@@ -982,7 +989,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({<Form.Itemlabel="Models"name="models"- rules={[{ required: true, message: "Please select at least one model" }]}+ extra="Leave empty to grant no models directly. The team keeps any models granted through its access groups"><ModelSelectvalue={form.getFieldValue("models") || []}diff --git a/ui/litellm-dashboard/src/components/team/teamModelAccess.test.ts b/ui/litellm-dashboard/src/components/team/teamModelAccess.test.tsnew file mode 100644index 00000000000..3f0b4e20407--- /dev/null+++ b/ui/litellm-dashboard/src/components/team/teamModelAccess.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from "vitest";+import { computeTeamModelBadges, normalizeTeamModelSelection, TeamAccessGroupModelGrant } from "./teamModelAccess";++const GRANTS: TeamAccessGroupModelGrant[] = [+ { access_group_id: "ag-1", access_group_name: "shared", models: ["haiku", "gpt-4o-mini"] },+ { access_group_id: "ag-2", access_group_name: "extra", models: ["haiku", "sonnet"] },+];++describe("normalizeTeamModelSelection", () => {+ it("substitutes the no-default-models sentinel for an empty selection", () => {+ expect(normalizeTeamModelSelection([])).toEqual(["no-default-models"]);+ expect(normalizeTeamModelSelection(undefined)).toEqual(["no-default-models"]);+ });++ it("passes a non-empty selection through untouched", () => {+ expect(normalizeTeamModelSelection(["gpt-4o-mini"])).toEqual(["gpt-4o-mini"]);+ expect(normalizeTeamModelSelection(["all-proxy-models"])).toEqual(["all-proxy-models"]);+ });+});++describe("computeTeamModelBadges", () => {+ it("attributes group-only models to the groups granting them", () => {+ const badges = computeTeamModelBadges(["sonnet-direct"], [], GRANTS);+ expect(badges).toEqual([+ {+ label: "sonnet-direct",+ kind: "direct",+ tooltip: "Granted directly in the team's model list",+ },+ { label: "haiku", kind: "access-group", tooltip: "Granted via access groups shared, extra" },+ { label: "gpt-4o-mini", kind: "access-group", tooltip: "Granted via access group shared" },+ { label: "sonnet", kind: "access-group", tooltip: "Granted via access group extra" },+ ]);+ });++ it("marks a model both direct and group-granted on the direct badge, without a duplicate badge", () => {+ const badges = computeTeamModelBadges(["haiku"], [], GRANTS);+ expect(badges).toEqual([+ {+ label: "haiku",+ kind: "direct",+ tooltip: "Granted directly in the team's model list, and also via access groups shared, extra",+ },+ { label: "gpt-4o-mini", kind: "access-group", tooltip: "Granted via access group shared" },+ { label: "sonnet", kind: "access-group", tooltip: "Granted via access group extra" },+ ]);+ });++ it("shows the no-default-models sentinel as its own badge and keeps group badges visible", () => {+ const badges = computeTeamModelBadges(["no-default-models"], [], [GRANTS[0]]);+ expect(badges.map((b) => [b.label, b.kind])).toEqual([+ ["No default models", "no-default"],+ ["haiku", "access-group"],+ ["gpt-4o-mini", "access-group"],+ ]);+ });++ it("still shows group badges when the empty model list grants everything", () => {+ const badges = computeTeamModelBadges([], [], [GRANTS[0]]);+ expect(badges[0]).toEqual({+ label: "All proxy models",+ kind: "all-proxy",+ tooltip: "The team's model list is empty, so it can access every model on the proxy",+ });+ expect(badges.slice(1).map((b) => b.label)).toEqual(["haiku", "gpt-4o-mini"]);+ });++ it("distinguishes the all-proxy-models sentinel from an empty list in the tooltip", () => {+ const badges = computeTeamModelBadges(["all-proxy-models"], [], []);+ expect(badges).toEqual([+ {+ label: "All proxy models",+ kind: "all-proxy",+ tooltip: "Granted by the All Proxy Models entry in the team's model list",+ },+ ]);+ });++ it("falls back to the flat access_group_models list when per-group details are absent", () => {+ const badges = computeTeamModelBadges(["direct-model"], ["haiku"], undefined);+ expect(badges).toEqual([+ { label: "direct-model", kind: "direct", tooltip: "Granted directly in the team's model list" },+ { label: "haiku", kind: "access-group", tooltip: "Granted via an access group" },+ ]);+ });+});diff --git a/ui/litellm-dashboard/src/components/team/teamModelAccess.ts b/ui/litellm-dashboard/src/components/team/teamModelAccess.tsnew file mode 100644index 00000000000..91ddf0f4045--- /dev/null+++ b/ui/litellm-dashboard/src/components/team/teamModelAccess.ts@@ -0,0 +1,82 @@+export const ALL_PROXY_MODELS = "all-proxy-models";+export const NO_DEFAULT_MODELS = "no-default-models";++export interface TeamAccessGroupModelGrant {+ access_group_id: string;+ access_group_name: string;+ models: string[];+}++export type TeamModelBadgeKind = "all-proxy" | "no-default" | "direct" | "access-group";++export interface TeamModelBadge {+ label: string;+ kind: TeamModelBadgeKind;+ tooltip: string;+}++export function normalizeTeamModelSelection(models: string[] | undefined): string[] {+ return models && models.length > 0 ? models : [NO_DEFAULT_MODELS];+}++const describeGroups = (names: string[]): string =>+ names.length > 1 ? `access groups ${names.join(", ")}` : `access group ${names[0]}`;++export function computeTeamModelBadges(+ models: string[],+ accessGroupModels: string[],+ accessGroupDetails: TeamAccessGroupModelGrant[] | undefined,+): TeamModelBadge[] {+ const grants = accessGroupDetails ?? [];+ const groupNamesFor = (model: string): string[] =>+ grants.filter((g) => g.models.includes(model)).map((g) => g.access_group_name);+ const viaGroups = (model: string): string => {+ const names = groupNamesFor(model);+ return names.length > 0 ? describeGroups(names) : "an access group";+ };++ const allProxy = models.length === 0 || models.includes(ALL_PROXY_MODELS);+ const directModels = allProxy ? [] : models.filter((m) => m !== NO_DEFAULT_MODELS);+ const groupModels = [...new Set(grants.length > 0 ? grants.flatMap((g) => g.models) : accessGroupModels)].filter(+ (m) => !directModels.includes(m),+ );++ const allProxyBadge: TeamModelBadge = {+ label: "All proxy models",+ kind: "all-proxy",+ tooltip: models.includes(ALL_PROXY_MODELS)+ ? "Granted by the All Proxy Models entry in the team's model list"+ : "The team's model list is empty, so it can access every model on the proxy",+ };+ const noDefaultBadge: TeamModelBadge = {+ label: "No default models",+ kind: "no-default",+ tooltip: "No models are granted directly. Access comes only from access groups",+ };+ const headBadge = (): TeamModelBadge[] => {+ if (allProxy) return [allProxyBadge];+ if (models.includes(NO_DEFAULT_MODELS)) return [noDefaultBadge];+ return [];+ };++ return [+ ...headBadge(),+ ...directModels.map(+ (m): TeamModelBadge => ({+ label: m,+ kind: "direct",+ tooltip:+ groupNamesFor(m).length > 0+ ? `Granted directly in the team's model list, and also via ${viaGroups(m)}`+ : "Granted directly in the team's model list",+ }),+ ),+ ...groupModels.map(+ (m): TeamModelBadge => ({+ label: m,+ kind: "access-group",+ tooltip: `Granted via ${viaGroups(m)}`,+ }),+ ),+ ];+}