Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,19 @@
})();
Object.defineProperty(window, "localStorage", { value: localStorageMock });

const { mockPush, mockReplace, navState } = vi.hoisted(() => ({
mockPush: vi.fn(),
mockReplace: vi.fn(),
navState: { pathname: "/models-and-endpoints" },
}));
vi.mock("next/navigation", () => ({
usePathname: () => navState.pathname,
useRouter: () => ({ push: mockPush, replace: mockReplace }),
}));

// Minimal stubs to avoid Next.js router and network usage during render
vi.mock("@/components/networking", () => ({
serverRootPath: "",
credentialListCall: vi.fn().mockResolvedValue({ credentials: [] }),
modelInfoCall: vi.fn().mockResolvedValue({ data: [] }),
modelCostMap: vi.fn().mockResolvedValue({}),
Expand Down Expand Up @@ -89,6 +100,9 @@

describe("ModelsAndEndpointsView", () => {
beforeEach(() => {
navState.pathname = "/models-and-endpoints";
mockPush.mockClear();
mockReplace.mockClear();
mockUseModelsInfo.mockReturnValue({
data: { data: [] },
isLoading: false,
Expand All @@ -102,7 +116,7 @@
isLoading: false,
error: null,
});
mockUseAuthorized.mockReturnValue({

Check warning on line 119 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.test.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Object literal with 4 properties passed inline as an argument; assign it to a named variable first
accessToken: "123",
token: "123",
userRole: "Admin",
Expand Down Expand Up @@ -192,21 +206,55 @@
refetch: vi.fn(),
});

navState.pathname = "/models-and-endpoints/health";
const queryClient = createQueryClient();
await act(async () => {
render(
<QueryClientProvider client={queryClient}>
<ModelsAndEndpointsView premiumUser={false} teams={[]} />
</QueryClientProvider>,
);
});

expect(mockHealthCheckComponent).toHaveBeenCalled();
const healthCheckProps = mockHealthCheckComponent.mock.calls[0][0];
expect(healthCheckProps.all_models_on_proxy).toEqual(["deployment-id-1", "deployment-id-2"]);
expect(healthCheckProps.all_models_on_proxy).not.toContain("gpt-4");
});

it("selecting a tab navigates to that tab's path instead of updating local state", async () => {
const queryClient = createQueryClient();
const { getByRole } = render(
<QueryClientProvider client={queryClient}>
<ModelsAndEndpointsView premiumUser={false} teams={[]} />
</QueryClientProvider>,
);

const healthStatusTab = getByRole("tab", { name: "Health Status" });
await act(async () => {
healthStatusTab.click();
getByRole("tab", { name: "Health Status" }).click();
});

expect(mockHealthCheckComponent).toHaveBeenCalled();
const healthCheckProps = mockHealthCheckComponent.mock.calls[0][0];
expect(healthCheckProps.all_models_on_proxy).toEqual(["deployment-id-1", "deployment-id-2"]);
expect(healthCheckProps.all_models_on_proxy).not.toContain("gpt-4");
expect(mockPush).toHaveBeenCalledWith(expect.stringMatching(/\/models-and-endpoints\/health\/$/));
});

it("redirects to the base models path when a tab path is not permitted for the role", async () => {
mockUseAuthorized.mockReturnValue({

Check warning on line 241 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.test.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Object literal with 4 properties passed inline as an argument; assign it to a named variable first
accessToken: "123",
token: "123",
userRole: "Internal User",
userId: "123",
});
navState.pathname = "/models-and-endpoints/llm-credentials";

const queryClient = createQueryClient();
await act(async () => {
render(
<QueryClientProvider client={queryClient}>
<ModelsAndEndpointsView premiumUser={false} teams={[]} />
</QueryClientProvider>,
);
});

expect(mockReplace).toHaveBeenCalledWith(expect.stringMatching(/\/models-and-endpoints\/$/));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import { getDisplayModelName } from "@/components/view_model/model_name_display";
import { transformModelData } from "./utils/modelDataTransformer";
import { all_admin_roles, internalUserRoles, isProxyAdminRole, isUserTeamAdminForAnyTeam } from "@/utils/roles";
import { modelTabHref, slugFromPathname } from "@/app/(dashboard)/models-and-endpoints/tabRoutes";
import { usePathname, useRouter } from "next/navigation";
import { RefreshIcon } from "@heroicons/react/outline";
import { useQueryClient } from "@tanstack/react-query";
import type { PaginationState } from "@tanstack/react-table";
Expand Down Expand Up @@ -53,8 +55,10 @@

const HEALTH_PAGE_SIZE = 50;

const ModelsAndEndpointsView: React.FC<ModelDashboardProps> = ({ premiumUser, teams }) => {

Check warning on line 58 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Arrow function has a complexity of 26. Maximum allowed is 20
const { accessToken, token, userRole, userId: userID } = useAuthorized();
const pathname = usePathname();
const router = useRouter();
const [addModelForm] = Form.useForm();
const [lastRefreshed, setLastRefreshed] = useState("");
const [providerModels, setProviderModels] = useState<Array<string>>([]);
Expand All @@ -69,7 +73,6 @@
const [showAdvancedSettings, setShowAdvancedSettings] = useState<boolean>(false);
const [selectedModelId, setSelectedModelId] = useState<string | null>(null);
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
const [healthPagination, setHealthPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: HEALTH_PAGE_SIZE,
Expand Down Expand Up @@ -112,13 +115,13 @@

const allModelsOnProxy = useMemo<string[]>(() => {
if (!modelDataResponse?.data) return [];
return modelDataResponse.data.map((model: any) => model.model_name);

Check warning on line 118 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
}, [modelDataResponse?.data]);

const healthModelIdsOnProxy = useMemo<string[]>(() => {
if (!healthModelDataResponse?.data) return [];
return healthModelDataResponse.data
.map((model: any) => model.model_info?.id)

Check warning on line 124 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
.filter((id: string | undefined): id is string => Boolean(id));
}, [healthModelDataResponse?.data]);

Expand All @@ -134,12 +137,12 @@
const processedModelData = useMemo(() => {
if (!modelDataResponse?.data) return { data: [] };
return transformModelData(modelDataResponse, getProviderFromModel);
}, [modelDataResponse?.data, getProviderFromModel]);

Check warning on line 140 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

React Hook useMemo has a missing dependency: 'modelDataResponse'. Either include it or remove the dependency array

const processedHealthModelData = useMemo(() => {
if (!healthModelDataResponse?.data) return { data: [] };
return transformModelData(healthModelDataResponse, getProviderFromModel);
}, [healthModelDataResponse?.data, getProviderFromModel]);

Check warning on line 145 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

React Hook useMemo has a missing dependency: 'healthModelDataResponse'. Either include it or remove the dependency array

const healthRowCount = healthModelDataResponse?.total_count ?? 0;

Expand All @@ -150,6 +153,27 @@
isInternalUser && uiSettings?.values?.disable_model_add_for_internal_users === true;
// Hide tab if user is NOT a proxy admin AND (internal user with setting enabled OR not a team admin)
const shouldHideAddModelTab = !isProxyAdmin && (addModelDisabledForInternalUsers || !isUserTeamAdmin);
const isAdmin = all_admin_roles.includes(userRole);

const visibleSlugs = useMemo<string[]>(
() => [
"",
...(shouldHideAddModelTab ? [] : ["add"]),
...(isAdmin
? ["llm-credentials", "pass-through", "health", "retry-settings", "model-group-alias", "price-data"]
: []),
],
[shouldHideAddModelTab, isAdmin],
);
Comment thread
ryan-crabbe-berri marked this conversation as resolved.
Resolved

const activeSlug = slugFromPathname(pathname);
const activeTabIndex = Math.max(0, visibleSlugs.indexOf(activeSlug));

useEffect(() => {
if (activeSlug !== "" && !visibleSlugs.includes(activeSlug)) {
router.replace(modelTabHref(""));
}
}, [activeSlug, visibleSlugs, router]);

const setProviderModelsFn = (provider: Providers) => {
const _providerModels = getProviderModels(provider, modelCostMapData);
Expand Down Expand Up @@ -236,7 +260,7 @@
};

useEffect(() => {
if (!accessToken || !token || !userRole || !userID || !modelDataResponse) {

Check warning on line 263 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Boolean expression combines 5 conditions; extract it into a named variable
return;
}
let active = true;
Expand All @@ -251,7 +275,7 @@
};
}, [accessToken, token, userRole, userID, modelDataResponse, fetchRouterSettings, applyRouterSettings]);

const isLoading = isLoadingModels || isLoadingModelCostMap || isLoadingCredentials || isLoadingUISettings;

Check warning on line 278 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Boolean expression combines 4 conditions; extract it into a named variable

// Admin Viewer can view all models read-only — page render proceeds; the
// individual write-action tabs (Add Model, LLM Credentials, etc.) are
Expand All @@ -261,7 +285,7 @@
try {
const values = await addModelForm.validateFields();
await handleAddModelSubmit(values, accessToken, addModelForm, handleRefreshClick);
} catch (error: any) {

Check warning on line 288 in ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
const errorMessages =
error.errorFields
?.map((field: any) => {
Expand Down Expand Up @@ -327,15 +351,8 @@
/>
) : (
(() => {
// Build a single source-of-truth list of {tab, panel} pairs.
// Conditionally-hidden tabs (e.g. "Add Model" for non-admin) get
// filtered out as a unit so tab indices and panel indices can
// never drift apart — Tremor's TabList and TabPanels filter
// falsy children inconsistently, which previously caused
// "click LLM Credentials, see nothing" for Admin Viewer.
const isAdmin = all_admin_roles.includes(userRole);
const visibleTabs: Array<{ tab: React.ReactElement; panel: React.ReactElement }> = [
{
const tabBySlug: Record<string, { tab: React.ReactElement; panel: React.ReactElement }> = {
"": {
tab: <Tab key="all-models">{isAdmin ? "All Models" : "Your Models"}</Tab>,
panel: (
<AllModelsTab
Expand All @@ -349,9 +366,7 @@
/>
),
},
];
if (!shouldHideAddModelTab) {
visibleTabs.push({
add: {
tab: <Tab key="add-model">Add Model</Tab>,
panel: (
<TabPanel key="add-model" className="h-full">
Expand All @@ -373,94 +388,90 @@
/>
</TabPanel>
),
});
}
if (isAdmin) {
visibleTabs.push(
{
tab: <Tab key="llm-credentials">LLM Credentials</Tab>,
panel: (
<TabPanel key="llm-credentials">
<CredentialsPanel uploadProps={uploadProps} />
</TabPanel>
),
},
{
tab: <Tab key="pass-through">Pass-Through Endpoints</Tab>,
panel: (
<TabPanel key="pass-through">
<PassThroughSettings
accessToken={accessToken}
userRole={userRole}
userID={userID}
premiumUser={premiumUser}
/>
</TabPanel>
),
},
{
tab: <Tab key="health-status">Health Status</Tab>,
panel: (
<TabPanel key="health-status">
<HealthCheckComponent
accessToken={accessToken}
modelData={processedHealthModelData}
all_models_on_proxy={healthModelIdsOnProxy}
getDisplayModelName={getDisplayModelName}
setSelectedModelId={setSelectedModelId}
teams={teams}
isLoading={isLoadingHealthModels}
pagination={healthPagination}
onPaginationChange={setHealthPagination}
rowCount={healthRowCount}
/>
</TabPanel>
),
},
{
tab: <Tab key="model-retry-settings">Model Retry Settings</Tab>,
panel: (
<ModelRetrySettingsTab
key="model-retry-settings"
selectedModelGroup={retryScope}
setSelectedModelGroup={setRetryScope}
availableModelGroups={availableModelGroups}
globalRetryPolicy={globalRetryPolicy}
setGlobalRetryPolicy={setGlobalRetryPolicy}
defaultRetry={defaultRetry}
modelGroupRetryPolicy={modelGroupRetryPolicy}
setModelGroupRetryPolicy={setModelGroupRetryPolicy}
handleSaveRetrySettings={handleSaveRetrySettings}
isSaving={updateRetryPolicy.isPending}
},
"llm-credentials": {
tab: <Tab key="llm-credentials">LLM Credentials</Tab>,
panel: (
<TabPanel key="llm-credentials">
<CredentialsPanel uploadProps={uploadProps} />
</TabPanel>
),
},
"pass-through": {
tab: <Tab key="pass-through">Pass-Through Endpoints</Tab>,
panel: (
<TabPanel key="pass-through">
<PassThroughSettings
accessToken={accessToken}
userRole={userRole}
userID={userID}
premiumUser={premiumUser}
/>
),
},
{
tab: <Tab key="model-group-alias">Model Group Alias</Tab>,
panel: (
<TabPanel key="model-group-alias">
<ModelGroupAliasSettings
accessToken={accessToken}
initialModelGroupAlias={modelGroupAlias}
onAliasUpdate={setModelGroupAlias}
/>
</TabPanel>
),
},
{
tab: <Tab key="price-data-reload">Price Data Reload</Tab>,
panel: <PriceDataManagementTab key="price-data-reload" />,
},
);
}
</TabPanel>
),
},
health: {
tab: <Tab key="health-status">Health Status</Tab>,
panel: (
<TabPanel key="health-status">
<HealthCheckComponent
accessToken={accessToken}
modelData={processedHealthModelData}
all_models_on_proxy={healthModelIdsOnProxy}
getDisplayModelName={getDisplayModelName}
setSelectedModelId={setSelectedModelId}
teams={teams}
isLoading={isLoadingHealthModels}
pagination={healthPagination}
onPaginationChange={setHealthPagination}
rowCount={healthRowCount}
/>
</TabPanel>
),
},
"retry-settings": {
tab: <Tab key="model-retry-settings">Model Retry Settings</Tab>,
panel: (
<ModelRetrySettingsTab
key="model-retry-settings"
selectedModelGroup={retryScope}
setSelectedModelGroup={setRetryScope}
availableModelGroups={availableModelGroups}
globalRetryPolicy={globalRetryPolicy}
setGlobalRetryPolicy={setGlobalRetryPolicy}
defaultRetry={defaultRetry}
modelGroupRetryPolicy={modelGroupRetryPolicy}
setModelGroupRetryPolicy={setModelGroupRetryPolicy}
handleSaveRetrySettings={handleSaveRetrySettings}
isSaving={updateRetryPolicy.isPending}
/>
),
},
"model-group-alias": {
tab: <Tab key="model-group-alias">Model Group Alias</Tab>,
panel: (
<TabPanel key="model-group-alias">
<ModelGroupAliasSettings
accessToken={accessToken}
initialModelGroupAlias={modelGroupAlias}
onAliasUpdate={setModelGroupAlias}
/>
</TabPanel>
),
},
"price-data": {
tab: <Tab key="price-data-reload">Price Data Reload</Tab>,
panel: <PriceDataManagementTab key="price-data-reload" />,
},
};
return (
<TabGroup
index={selectedTabIndex}
onIndexChange={setSelectedTabIndex}
index={activeTabIndex}
onIndexChange={(index) => router.push(modelTabHref(visibleSlugs[index] ?? ""))}
className="gap-2 h-[75vh] w-full "
>
<TabList className="flex justify-between mt-2 w-full items-center">
<div className="flex">{visibleTabs.map((t) => t.tab)}</div>
<div className="flex">{visibleSlugs.map((slug) => tabBySlug[slug].tab)}</div>

<div className="flex items-center space-x-2 self-center">
{lastRefreshed && <span className="text-xs text-gray-500">Last Refreshed: {lastRefreshed}</span>}
Expand All @@ -473,7 +484,7 @@
/>
</div>
</TabList>
<TabPanels>{visibleTabs.map((t) => t.panel)}</TabPanels>
<TabPanels>{visibleSlugs.map((slug) => tabBySlug[slug].panel)}</TabPanels>
</TabGroup>
);
})()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function TabRoutePlaceholder() {
return null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "../TabRoutePlaceholder";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "../TabRoutePlaceholder";
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use client";

import type { ReactNode } from "react";
import ModelsAndEndpointsView from "@/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";

export default function ModelsAndEndpointsLayout({ children }: { children: ReactNode }) {
const { premiumUser } = useAuthorized();
const { data: teams } = useTeams();
return (
<>
<ModelsAndEndpointsView premiumUser={premiumUser} teams={teams ?? null} />
{children}
</>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "../TabRoutePlaceholder";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "../TabRoutePlaceholder";
Original file line number Diff line number Diff line change
@@ -1,11 +1 @@
"use client";

import ModelsAndEndpointsView from "@/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";

export default function ModelsAndEndpointsPage() {
const { premiumUser } = useAuthorized();
const { data: teams } = useTeams();
return <ModelsAndEndpointsView premiumUser={premiumUser} teams={teams ?? null} />;
}
export { default } from "./TabRoutePlaceholder";
Loading
Loading