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): keep virtual-keys filters across delete and refresh (LIT-4080) (#31533)
ryan-crabbe-berri0e5aee183837
diff --git a/ui/litellm-dashboard/eslint-metrics.json b/ui/litellm-dashboard/eslint-metrics.jsonindex 01c5a241562..deef1136b43 100644--- a/ui/litellm-dashboard/eslint-metrics.json+++ b/ui/litellm-dashboard/eslint-metrics.json@@ -1,5 +1,5 @@{- "@typescript-eslint/no-explicit-any": 2026,- "complexity": 128,+ "@typescript-eslint/no-explicit-any": 2016,+ "complexity": 127,"max-depth": 61}diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 770c953d3f3..5d3a54f9e81 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -1133,20 +1133,6 @@"count": 1}},- "src/components/key_team_helpers/filter_logic.tsx": {- "react-hooks/purity": {- "count": 1- },- "react-hooks/refs": {- "count": 1- },- "react-hooks/set-state-in-effect": {- "count": 3- },- "react-hooks/use-memo": {- "count": 1- }- },"src/components/key_team_helpers/key_list.tsx": {"react-hooks/set-state-in-effect": {"count": 1diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsxindex 3a3251ea76a..13689afcb52 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsx@@ -42,10 +42,6 @@ vi.mock("@/app/(dashboard)/hooks/teams/useTeams", () => ({teamListCall: vi.fn(() => new Promise(() => {})),}));-vi.mock("@/components/organizations", () => ({- fetchOrganizations: vi.fn(),-}));-vi.mock("next/navigation", () => ({useSearchParams: () => new URLSearchParams(""),}));diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.tsxindex 54f4bf41a21..ae0c443910a 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.tsx@@ -3,9 +3,7 @@import { teamListCall as v2TeamListCall } from "@/app/(dashboard)/hooks/teams/useTeams";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";import { KeyResponse, Team } from "@/components/key_team_helpers/key_list";-import { Organization } from "@/components/networking";import { CreateKeyPrefillData } from "@/components/organisms/create_key_button";-import { fetchOrganizations } from "@/components/organizations";import UserDashboard from "@/components/user_dashboard";import { useAuth } from "@/contexts/AuthContext";import { useSearchParams } from "next/navigation";@@ -20,7 +18,6 @@ export default function ApiKeysDashboard() {const [teams, setTeams] = useState<Team[] | null>(null);const [keys, setKeys] = useState<KeyResponse[] | null>([]);- const [organizations, setOrganizations] = useState<Organization[]>([]);const [createClicked, setCreateClicked] = useState<boolean>(false);const autoOpenCreate = searchParams.get("create") === "true";@@ -77,9 +74,6 @@ export default function ApiKeysDashboard() {.then((response) => setTeams(response.teams ?? [])).catch(console.error);}- if (accessToken) {- fetchOrganizations(accessToken, setOrganizations);- }}, [accessToken, userID, userRole]);return (@@ -94,7 +88,6 @@ export default function ApiKeysDashboard() {setUserEmail={setUserEmail}setTeams={setTeams}setKeys={setKeys}- organizations={organizations}addKey={addKey}createClicked={createClicked}autoOpenCreate={autoOpenCreate}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.tsindex 164e393eb9b..8c9b33f2c3e 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts@@ -69,6 +69,7 @@ const mockKeys: KeyResponse[] = [organization_id: null,created_at: "2024-01-01T00:00:00Z",updated_at: "2024-01-01T00:00:00Z",+ last_active: null,team_spend: 0,team_alias: "",team_tpm_limit: 0,@@ -125,6 +126,7 @@ const mockKeys: KeyResponse[] = [organization_id: null,created_at: "2024-01-01T00:00:00Z",updated_at: "2024-01-01T00:00:00Z",+ last_active: null,team_spend: 0,team_alias: "test-team",team_tpm_limit: 1000,@@ -460,6 +462,31 @@ describe("useKeys", () => {expect(callUrl).not.toContain("project_id");});+ // LIT-4080 guard: filter options must be part of the query key, not just the+ // queryFn closure. If they were dropped from the key, changing a filter would+ // reuse the cached (unfiltered) result and never refetch — exactly the bug+ // where deleting a key wiped the active User ID filter.+ it("refetches with the new filter when a filter option changes (options are in the query key)", async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => mockKeysResponse,+ });++ const { result, rerender } = renderHook(({ userID }) => useKeys(1, 10, { userID }), {+ wrapper,+ initialProps: { userID: "user-1" },+ });++ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(mockFetch.mock.calls[0][0]).toContain("user_id=user-1");++ rerender({ userID: "user-2" });++ await waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(2));+ expect(mockFetch.mock.calls[1][0]).toContain("user_id=user-2");+ });+it("should pass agentID filter to the API", async () => {mockFetch.mockResolvedValueOnce({ok: true,diff --git a/ui/litellm-dashboard/src/app/(dashboard)/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/page.tsxindex c5d28fab8a0..cb4a4a0de03 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/page.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/page.tsx@@ -4,8 +4,7 @@ import ApiKeysDashboard from "@/app/(dashboard)/api-keys/ApiKeysDashboard";import { teamListCall as v2TeamListCall } from "@/app/(dashboard)/hooks/teams/useTeams";import LoadingScreen from "@/components/common_components/LoadingScreen";import { Team } from "@/components/key_team_helpers/key_list";-import { Organization, proxyBaseUrl } from "@/components/networking";-import { fetchOrganizations } from "@/components/organizations";+import { proxyBaseUrl } from "@/components/networking";import UserDashboard from "@/components/user_dashboard";import { useAuth } from "@/contexts/AuthContext";import {@@ -25,7 +24,6 @@ function CreateKeyPageContent() {const [teams, setTeams] = useState<Team[] | null>(null);const [keys, setKeys] = useState<null | any[]>([]);- const [organizations, setOrganizations] = useState<Organization[]>([]);const router = useRouter();const searchParams = useSearchParams()!;@@ -112,9 +110,6 @@ function CreateKeyPageContent() {.then((response) => setTeams(response.teams ?? [])).catch(console.error);}- if (accessToken) {- fetchOrganizations(accessToken, setOrganizations);- }}, [accessToken, userID, userRole]);if (authLoading || redirectToLogin || isLegacyRedirect) {@@ -135,7 +130,6 @@ function CreateKeyPageContent() {setUserEmail={setUserEmail}setTeams={setTeams}setKeys={setKeys}- organizations={organizations}addKey={addKey}createClicked={createClicked}/>diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsxindex 4002bbd245f..6389b82c9fd 100644--- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx+++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx@@ -1,63 +1,46 @@import { act, screen, waitFor, fireEvent } from "@testing-library/react";-import { vi, it, expect, beforeEach, MockedFunction } from "vitest";+import { vi, it, expect, beforeEach, describe, MockedFunction } from "vitest";import { renderWithProviders } from "../../../tests/test-utils";import { VirtualKeysTable } from "./VirtualKeysTable";import { KeyResponse, Team } from "../key_team_helpers/key_list";-import { Organization } from "../networking";import { KeysResponse, useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";-import { useFilterLogic } from "../key_team_helpers/filter_logic";import useTeams from "@/app/(dashboard)/hooks/useTeams";-// Mock network calls-vi.mock("./networking", async (importOriginal) => {- const actual = await importOriginal<typeof import("../networking")>();+// Resolve debounced values synchronously so an applied filter lands in the useKeys query within the test tick.+vi.mock("@tanstack/react-pacer/debouncer", async () => {+ const React = await vi.importActual<typeof import("react")>("react");return {- ...actual,- userListCall: vi.fn().mockResolvedValue({- users: [- {- user_id: "user-1",- user_email: "[email protected]",- user_role: "user",- },- ],- }),- teamListCall: vi.fn().mockResolvedValue([]),+ useDebouncedValue: (value: unknown) => [value, { cancel: vi.fn(), flush: vi.fn() }],+ useDebouncedState: (initial: unknown) => {+ const [value, setValue] = React.useState(initial);+ return [value, setValue, { cancel: vi.fn(), flush: vi.fn() }];+ },};});-// Mock filter helpers-vi.mock("./key_team_helpers/filter_helpers", () => ({- fetchAllTeams: vi.fn().mockResolvedValue([- {- team_id: "team-1",- team_alias: "Test Team",- },- ]),- fetchAllOrganizations: vi.fn().mockResolvedValue([- {- organization_id: "org-1",- organization_alias: "Test Organization",- },- ]),+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: vi.fn(() => ({+ accessToken: "test-token",+ userId: "test-user",+ userRole: "Admin",+ premiumUser: true,+ token: "test-token",+ })),}));-// Mock useKeys hook-vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({- useKeys: vi.fn(),+vi.mock("../key_team_helpers/filter_helpers", () => ({+ fetchAllTeams: vi.fn().mockResolvedValue([{ team_id: "team-1", team_alias: "Test Team" }]),}));-// Mock useFilterLogic hook-vi.mock("../key_team_helpers/filter_logic", () => ({- useFilterLogic: vi.fn(),+vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({+ useKeys: vi.fn(),+ keyKeys: { lists: () => ["keys", "list"] },}));-// Mock useTeams hook (used by KeyInfoView)vi.mock("@/app/(dashboard)/hooks/useTeams", () => ({default: vi.fn(),}));-// Mock useOrganizations hookvi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({useOrganizations: vi.fn().mockReturnValue({data: [@@ -69,15 +52,6 @@ vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({}),}));-// Mock fetchTeams to prevent network calls-vi.mock("@/app/(dashboard)/networking", async (importOriginal) => {- const actual = await importOriginal<typeof import("@/app/(dashboard)/networking")>();- return {- ...actual,- fetchTeams: vi.fn().mockResolvedValue([]),- };-});-const mockKey: KeyResponse = {token: "sk-1234567890abcdef",token_id: "key-1",@@ -91,6 +65,7 @@ const mockKey: KeyResponse = {config: {},user_id: "user-1",team_id: "team-1",+ project_id: null,max_parallel_requests: 10,metadata: {},tpm_limit: 1000,@@ -153,68 +128,33 @@ const mockTeam: Team = {created_at: "2024-10-01T10:00:00Z",keys: [],members_with_roles: [],+ spend: 0,};-const mockOrganization: Organization = {- organization_id: "org-1",- organization_alias: "Test Organization",- budget_id: "budget-1",- metadata: {},- models: ["gpt-3.5-turbo", "gpt-4"],- spend: 100,- model_spend: { "gpt-3.5-turbo": 50, "gpt-4": 50 },- created_at: "2024-10-01T10:00:00Z",- created_by: "user-1",- updated_at: "2024-11-01T10:00:00Z",- updated_by: "user-1",- litellm_budget_table: {},- teams: [],- users: [],- members: [],-};--// Mock hook implementationsconst mockUseKeys = useKeys as MockedFunction<typeof useKeys>;-const mockUseFilterLogic = useFilterLogic as MockedFunction<typeof useFilterLogic>;const mockUseTeams = useTeams as MockedFunction<typeof useTeams>;-beforeEach(() => {- // Reset mocks before each test- vi.clearAllMocks();-- // Setup default mock implementations- mockUseKeys.mockReturnValue({+const keysResult = (keys: KeyResponse[], data: Partial<KeysResponse> = {}, extra: Record<string, unknown> = {}) =>+ ({data: {- keys: [mockKey],- total_count: 1,+ keys,+ total_count: keys.length,current_page: 1,total_pages: 1,+ ...data,} as KeysResponse,isPending: false,isFetching: false,+ isError: false,refetch: vi.fn(),- } as any);-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "team-1",- "Organization ID": "org-1",- "Key Alias": "Test Key Alias",- "User ID": "user-1",- "User Email": "[email protected]",- "User Role": "user",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [mockKey],- filteredTotalCount: null,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ ...extra,+ }) as any;++beforeEach(() => {+ vi.clearAllMocks();++ mockUseKeys.mockReturnValue(keysResult([mockKey]));- // Mock useTeams hook (used by KeyInfoView)mockUseTeams.mockReturnValue({teams: [mockTeam],setTeams: vi.fn(),@@ -222,33 +162,12 @@ beforeEach(() => {});it("should render VirtualKeysTable component", () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);-+ renderWithProviders(<VirtualKeysTable />);expect(screen.getByText("Test Key Alias")).toBeInTheDocument();});it("should display key information correctly", async () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("Test Key Alias")).toBeInTheDocument();@@ -258,17 +177,7 @@ it("should display key information correctly", async () => {});it("should display user email correctly", async () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("[email protected]")).toBeInTheDocument();@@ -276,121 +185,36 @@ it("should display user email correctly", async () => {});it("should show loading message only on initial load (isPending)", () => {- // Mock initial loading state- mockUseKeys.mockReturnValue({- data: null,- isPending: true,- isFetching: true,- refetch: vi.fn(),- } as any);-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ mockUseKeys.mockReturnValue(keysResult([], {}, { data: null, isPending: true, isFetching: true }));- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);- // Check that loading message is shown on initial loadexpect(screen.getByText("🚅 Loading keys...")).toBeInTheDocument();-- // Check that actual key data is not shownexpect(screen.queryByText("Test Key Alias")).not.toBeInTheDocument();expect(screen.queryByText("Test Team")).not.toBeInTheDocument();});-it("should show 'No keys found' message when filteredKeys is empty", () => {- // Mock empty filteredKeys- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+it("should show 'No keys found' message when the key list is empty", () => {+ mockUseKeys.mockReturnValue(keysResult([]));- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);expect(screen.getByText("No keys found")).toBeInTheDocument();});it("should handle models with more than 3 entries to trigger expansion UI", () => {- const keyWithManyModels = {- ...mockKey,- models: ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "claude-3", "claude-3-5-sonnet"],- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithManyModels],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ mockUseKeys.mockReturnValue(+ keysResult([{ ...mockKey, models: ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "claude-3", "claude-3-5-sonnet"] }]),+ );- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);- // This test ensures the ChevronDownIcon import (line 6) is used- // by having a key with > 3 models which triggers the expansion logic- // that uses ChevronDownIcon and ChevronRightIconexpect(screen.getByText("Test Key Alias")).toBeInTheDocument();});it("should render table headers correctly", () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ renderWithProviders(<VirtualKeysTable />);- renderWithProviders(<VirtualKeysTable {...mockProps} />);-- // Check that main headers are rendered (testing the header.isPlaceholder condition path)expect(screen.getByText("Key ID")).toBeInTheDocument();expect(screen.getByText("Key Alias")).toBeInTheDocument();expect(screen.getByText("Team")).toBeInTheDocument();@@ -399,442 +223,164 @@ it("should render table headers correctly", () => {});it("should handle column resizing hover events", () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);- // Find a header cell with data-header-id attributeconst headerCell = document.querySelector("[data-header-id]") as HTMLElement;-expect(headerCell).toBeInTheDocument();- // Check that the resizer element exists within the headerconst resizer = headerCell?.querySelector(".resizer") as HTMLElement;expect(resizer).toBeInTheDocument();-- // Initially, resizer should have opacity 0expect(resizer.style.opacity).toBe("0");- // Simulate mouse enter using fireEvent - should set opacity to 0.5 (lines 612-616)fireEvent.mouseEnter(headerCell);expect(resizer.style.opacity).toBe("0.5");- // Simulate mouse leave using fireEvent - should set opacity back to 0 (lines 618-622)fireEvent.mouseLeave(headerCell);expect(resizer.style.opacity).toBe("0");});it("should open KeyInfoView when clicking on a key ID button", async () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);- // Wait for the table to renderawait waitFor(() => {expect(screen.getByText("Test Key Alias")).toBeInTheDocument();});- // Verify table is visible before clicking - check for table-specific textexpect(screen.getByText(/Showing.*results/)).toBeInTheDocument();- // Find the key ID button (it shows the full token value, truncation is CSS-only)const keyIdButton = screen.getByText("sk-1234567890abcdef");- expect(keyIdButton).toBeInTheDocument();-- // Click on the key ID buttonfireEvent.click(keyIdButton);- // Wait for KeyInfoView to appear - check for unique elements that only exist in KeyInfoViewawait waitFor(() => {expect(screen.getByText("Back to Keys")).toBeInTheDocument();- // KeyInfoHeader shows "Created At" metadata labelexpect(screen.getByText("Created At")).toBeInTheDocument();});- // Verify that table-specific elements are no longer visible- // The "Showing X of Y results" text should not be visible when KeyInfoView is openexpect(screen.queryByText(/Showing.*results/)).not.toBeInTheDocument();});it("should display 'Default Proxy Admin' for user_id when value is 'default_user_id'", async () => {- const keyWithDefaultUserId = {- ...mockKey,- user_id: "default_user_id",- user_email: "",- user: { user_id: "default_user_id", user_email: "", user_alias: null },- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithDefaultUserId],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ mockUseKeys.mockReturnValue(+ keysResult([+ {+ ...mockKey,+ user_id: "default_user_id",+ user_email: "",+ user: { user_id: "default_user_id", user_email: "", user_alias: null },+ },+ ]),+ );- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("Default Proxy Admin")).toBeInTheDocument();});});-it("should display 'Default Proxy Admin' for created_by when value is 'default_user_id'", async () => {- const keyWithDefaultCreatedBy = {- ...mockKey,- created_by: "default_user_id",- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithDefaultCreatedBy],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };-- renderWithProviders(<VirtualKeysTable {...mockProps} />);-- await waitFor(() => {- // The created_by column should display "Default Proxy Admin"- const defaultProxyAdminElements = screen.getAllByText("Default Proxy Admin");- expect(defaultProxyAdminElements.length).toBeGreaterThan(0);- });-});-it("should display created_by_user email in 'Created By' column when available", async () => {- const keyWithCreatedByUser = {- ...mockKey,- created_by: "some-uuid-1234",- created_by_user: {- user_id: "some-uuid-1234",- user_email: "[email protected]",- user_alias: null,- },- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithCreatedByUser],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ mockUseKeys.mockReturnValue(+ keysResult([+ {+ ...mockKey,+ created_by: "some-uuid-1234",+ created_by_user: { user_id: "some-uuid-1234", user_email: "[email protected]", user_alias: null },+ },+ ]),+ );- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("[email protected]")).toBeInTheDocument();});});-it("should display created_by_user alias over email when both available", async () => {- const keyWithCreatedByUser = {- ...mockKey,- created_by: "some-uuid-1234",- created_by_user: {- user_id: "some-uuid-1234",- user_email: "[email protected]",- user_alias: "The Creator",- },- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithCreatedByUser],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+it("should display created_by_user alias over email when both are available", async () => {+ mockUseKeys.mockReturnValue(+ keysResult([+ {+ ...mockKey,+ created_by: "some-uuid-1234",+ created_by_user: { user_id: "some-uuid-1234", user_email: "[email protected]", user_alias: "The Creator" },+ },+ ]),+ );- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("The Creator")).toBeInTheDocument();});+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();});it("should render table without crashing when models is null", async () => {- const keyWithNullModels = {- ...mockKey,- models: null as unknown as string[],- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithNullModels],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, models: null as unknown as string[] }]));- // This should not throw an error- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("Test Key Alias")).toBeInTheDocument();});});-it("should render table without crashing when models is undefined", async () => {- const keyWithUndefinedModels = {- ...mockKey,- models: undefined as unknown as string[],- };-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithUndefinedModels],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+it("should display 'Unknown' for last_active when value is null", async () => {+ mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, last_active: null }]));- // This should not throw an error- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {- expect(screen.getByText("Test Key Alias")).toBeInTheDocument();+ expect(screen.getByText("Unknown")).toBeInTheDocument();});});-it("should render Last Active column header with info icon", () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+describe("server-side filtering – the LIT-4080 regression guard", () => {+ it("threads an active User ID filter into the useKeys query so any refetch keeps it", async () => {+ renderWithProviders(<VirtualKeysTable />);- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ fireEvent.click(screen.getByRole("button", { name: "Filters" }));- expect(screen.getByText("Last Active")).toBeInTheDocument();-});+ const userIdInput = await screen.findByPlaceholderText("Enter User ID...");+ fireEvent.change(userIdInput, { target: { value: "user-42" } });-it("should display formatted date for last_active when value exists", async () => {- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ await waitFor(() => {+ expect(mockUseKeys).toHaveBeenLastCalledWith(1, 50, expect.objectContaining({ userID: "user-42" }));+ });+ });- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ it("does not send filter params to useKeys when no filter is active", () => {+ renderWithProviders(<VirtualKeysTable />);- await waitFor(() => {- const expectedDate = new Date("2024-11-20T14:30:00Z").toLocaleDateString();- expect(screen.getByText(expectedDate)).toBeInTheDocument();+ const lastCall = mockUseKeys.mock.calls[mockUseKeys.mock.calls.length - 1];+ expect(lastCall[2] ?? {}).toMatchObject({ userID: undefined, teamID: undefined, keyHash: undefined });});-});-it("should display 'Unknown' for last_active when value is null", async () => {- const keyWithNullLastActive = {- ...mockKey,- last_active: null,- };+ it("drops the filter from the useKeys query when Reset Filters is clicked", async () => {+ renderWithProviders(<VirtualKeysTable />);- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [keyWithNullLastActive],- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ fireEvent.click(screen.getByRole("button", { name: "Filters" }));+ const userIdInput = await screen.findByPlaceholderText("Enter User ID...");+ fireEvent.change(userIdInput, { target: { value: "user-42" } });- const mockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: {- sortBy: "created_at",- sortOrder: "desc" as const,- },- };+ await waitFor(() => {+ expect(mockUseKeys).toHaveBeenLastCalledWith(1, 50, expect.objectContaining({ userID: "user-42" }));+ });- renderWithProviders(<VirtualKeysTable {...mockProps} />);+ fireEvent.click(screen.getByRole("button", { name: "Reset Filters" }));- await waitFor(() => {- expect(screen.getByText("Unknown")).toBeInTheDocument();+ await waitFor(() => {+ const lastCall = mockUseKeys.mock.calls[mockUseKeys.mock.calls.length - 1];+ expect((lastCall[2] ?? {}).userID).toBeUndefined();+ });});});-const defaultMockProps = {- teams: [mockTeam],- organizations: [mockOrganization],- onSortChange: vi.fn(),- currentSort: { sortBy: "created_at", sortOrder: "desc" as const },-};--describe("pagination display – total count and page count", () => {- it("should show total_count from useKeys when no filter is active (filteredTotalCount is null)", async () => {- mockUseKeys.mockReturnValue({- data: {- keys: [mockKey],- total_count: 509,- current_page: 1,- total_pages: 11,- } as KeysResponse,- isPending: false,- isFetching: false,- refetch: vi.fn(),- } as any);-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [mockKey],- filteredTotalCount: null,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+describe("pagination display – total count comes from useKeys", () => {+ it("shows total_count and page count from the useKeys response", async () => {+ mockUseKeys.mockReturnValue(keysResult([mockKey], { total_count: 509, total_pages: 11 }));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("Showing 1 - 50 of 509 results")).toBeInTheDocument();@@ -842,86 +388,21 @@ describe("pagination display – total count and page count", () => {});});- it("should show filteredTotalCount in pagination text when a filter search returns results", async () => {- mockUseKeys.mockReturnValue({- data: {- keys: [mockKey],- total_count: 509,- current_page: 1,- total_pages: 11,- } as KeysResponse,- isPending: false,- isFetching: false,- refetch: vi.fn(),- } as any);-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "aaaaa",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [mockKey],- filteredTotalCount: 1,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ it("reflects a narrowed total when a filtered fetch returns fewer results", async () => {+ mockUseKeys.mockReturnValue(keysResult([mockKey], { total_count: 1, total_pages: 1 }));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByText("Showing 1 - 1 of 1 results")).toBeInTheDocument();expect(screen.getByText("Page 1 of 1")).toBeInTheDocument();});});-- it("should not show stale unfiltered totals when filteredTotalCount is set", async () => {- mockUseKeys.mockReturnValue({- data: {- keys: [mockKey],- total_count: 509,- current_page: 1,- total_pages: 11,- } as KeysResponse,- isPending: false,- isFetching: false,- refetch: vi.fn(),- } as any);-- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "aaaaa",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [mockKey],- filteredTotalCount: 1,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });-- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);-- await waitFor(() => {- expect(screen.queryByText(/509 results/)).not.toBeInTheDocument();- expect(screen.queryByText(/of 11/)).not.toBeInTheDocument();- });- });});describe("refetch button", () => {it("should show Fetch button in normal state", () => {- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);const fetchButton = screen.getByTitle("Fetch data");expect(fetchButton).toBeInTheDocument();@@ -930,64 +411,31 @@ describe("refetch button", () => {});it("should show Fetching state and keep table data visible during refetch", () => {- mockUseKeys.mockReturnValue({- data: {- keys: [mockKey],- total_count: 1,- current_page: 1,- total_pages: 1,- } as KeysResponse,- isPending: false,- isFetching: true,- refetch: vi.fn(),- } as any);-- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);-- // Button should show "Fetching" and be disabled- expect(screen.getByText("Fetching")).toBeInTheDocument();- const fetchButton = screen.getByTitle("Fetch data");- expect(fetchButton).toBeDisabled();+ mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { isFetching: true }));- // Table data should still be visible (stale data)- expect(screen.getByText("Test Key Alias")).toBeInTheDocument();+ renderWithProviders(<VirtualKeysTable />);- // "Loading keys..." should NOT appear during refetch+ expect(screen.getByText("Fetching")).toBeInTheDocument();+ expect(screen.getByTitle("Fetch data")).toBeDisabled();+ expect(screen.getByText("Test Key Alias")).toBeInTheDocument();expect(screen.queryByText("🚅 Loading keys...")).not.toBeInTheDocument();});it("should call refetch when Fetch button is clicked", () => {const mockRefetch = vi.fn();- mockUseKeys.mockReturnValue({- data: {- keys: [mockKey],- total_count: 1,- current_page: 1,- total_pages: 1,- } as KeysResponse,- isPending: false,- isFetching: false,- refetch: mockRefetch,- } as any);-- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { refetch: mockRefetch }));- const fetchButton = screen.getByTitle("Fetch data");- fireEvent.click(fetchButton);+ renderWithProviders(<VirtualKeysTable />);++ fireEvent.click(screen.getByTitle("Fetch data"));expect(mockRefetch).toHaveBeenCalledTimes(1);});it("should show Fetch button enabled on error so user can retry", () => {- mockUseKeys.mockReturnValue({- data: null,- isPending: false,- isFetching: false,- isError: true,- refetch: vi.fn(),- } as any);+ mockUseKeys.mockReturnValue(keysResult([], {}, { data: null, isError: true }));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);const fetchButton = screen.getByTitle("Fetch data");expect(fetchButton).not.toBeDisabled();@@ -997,24 +445,9 @@ describe("refetch button", () => {describe("Status column reflects key.blocked / scim_blocked metadata", () => {it("should render Active for a non-blocked key", async () => {- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [{ ...mockKey, blocked: false, metadata: {} }],- filteredTotalCount: null,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: false, metadata: {} }]));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByTestId(`key-status-${mockKey.token_id}`)).toHaveTextContent("Active");@@ -1022,24 +455,9 @@ describe("Status column reflects key.blocked / scim_blocked metadata", () => {});it("should render Blocked when key.blocked is true", async () => {- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [{ ...mockKey, blocked: true, metadata: {} }],- filteredTotalCount: null,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: true, metadata: {} }]));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);await waitFor(() => {expect(screen.getByTestId(`key-status-${mockKey.token_id}`)).toHaveTextContent("Blocked");@@ -1048,24 +466,9 @@ describe("Status column reflects key.blocked / scim_blocked metadata", () => {});it("should mark a SCIM-blocked key with the SCIM tooltip reason", async () => {- mockUseFilterLogic.mockReturnValue({- filters: {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- },- filteredKeys: [{ ...mockKey, blocked: true, metadata: { scim_blocked: true } }],- filteredTotalCount: null,- allTeams: [mockTeam],- allOrganizations: [mockOrganization],- handleFilterChange: vi.fn(),- handleFilterReset: vi.fn(),- });+ mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: true, metadata: { scim_blocked: true } }]));- renderWithProviders(<VirtualKeysTable {...defaultMockProps} />);+ renderWithProviders(<VirtualKeysTable />);const tag = await screen.findByTestId(`key-status-${mockKey.token_id}`);expect(tag).toHaveTextContent("Blocked");diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsxindex 0c95d5dcfb7..0c71c4526ad 100644--- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx+++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx@@ -1,14 +1,15 @@"use client";-import { useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";+import { useKeys, KeyListCallOptions } from "@/app/(dashboard)/hooks/keys/useKeys";import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations";+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";+import { useQuery } from "@tanstack/react-query";+import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";import { formatNumberWithCommas } from "@/utils/dataUtils";import { ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, SwitchVerticalIcon } from "@heroicons/react/outline";import {ColumnDef,flexRender,getCoreRowModel,- getPaginationRowModel,- getSortedRowModel,PaginationState,SortingState,useReactTable,@@ -27,57 +28,57 @@ import {} from "@tremor/react";import { InfoCircleOutlined, SyncOutlined } from "@ant-design/icons";import { Button as AntButton, Popover, Skeleton, Tag, Tooltip, Typography } from "antd";-import React, { useEffect, useDeferredValue, useMemo, useState } from "react";+import React, { useDeferredValue, useMemo, useState } from "react";import { getModelDisplayName } from "../key_team_helpers/fetch_available_models_team_key";-import { useFilterLogic } from "../key_team_helpers/filter_logic";+import { fetchAllTeams } from "../key_team_helpers/filter_helpers";import { PaginatedKeyAliasSelect } from "../KeyAliasSelect/PaginatedKeyAliasSelect/PaginatedKeyAliasSelect";import { KeyResponse, Team } from "../key_team_helpers/key_list";import FilterComponent, { FilterOption } from "../molecules/filter";import DefaultProxyAdminTag from "../common_components/DefaultProxyAdminTag";-import { Organization } from "../networking";import KeyInfoView from "../templates/key_info_view";-interface VirtualKeysTableProps {- teams: Team[] | null;- organizations: Organization[] | null;- onSortChange?: (sortBy: string, sortOrder: "asc" | "desc") => void;- currentSort?: {- sortBy: string;- sortOrder: "asc" | "desc";- };-}--/**- * VirtualKeysTable – a new table for keys that mimics the table styling used in view_logs.- * The team selector and filtering have been removed so that all keys are shown.- */--export function VirtualKeysTable({ teams, organizations, onSortChange, currentSort }: VirtualKeysTableProps) {- const { data: fetchedOrganizations } = useOrganizations();- const resolvedOrganizations = fetchedOrganizations ?? organizations ?? [];+type KeyFilterState = {+ "Team ID": string;+ "Organization ID": string;+ "Key Alias": string;+ "User ID": string;+ "Key Hash": string;+};++const DEFAULT_KEY_FILTERS: KeyFilterState = {+ "Team ID": "",+ "Organization ID": "",+ "Key Alias": "",+ "User ID": "",+ "Key Hash": "",+};++type KeyListFilterOptions = Pick<+ KeyListCallOptions,+ "teamID" | "organizationID" | "selectedKeyAlias" | "userID" | "keyHash"+>;++const toKeyListFilters = (filters: KeyFilterState): KeyListFilterOptions => ({+ teamID: filters["Team ID"].trim() || undefined,+ organizationID: filters["Organization ID"].trim() || undefined,+ selectedKeyAlias: filters["Key Alias"].trim() || undefined,+ userID: filters["User ID"].trim() || undefined,+ keyHash: filters["Key Hash"].trim() || undefined,+});++export function VirtualKeysTable() {+ const { accessToken } = useAuthorized();+ const { data: fetchedOrganizations, isLoading: isOrgsLoading } = useOrganizations();+ const resolvedOrganizations = useMemo(() => fetchedOrganizations ?? [], [fetchedOrganizations]);const [selectedKey, setSelectedKey] = useState<KeyResponse | null>(null);- const [sorting, setSorting] = React.useState<SortingState>(() => {- if (currentSort) {- return [- {- id: currentSort.sortBy,- desc: currentSort.sortOrder === "desc",- },- ];- }- return [- {- id: "created_at",- desc: true,- },- ];- });+ const [sorting, setSorting] = React.useState<SortingState>([{ id: "created_at", desc: true }]);const [tablePagination, setTablePagination] = React.useState<PaginationState>({pageIndex: 0,pageSize: 50,});+ const [filters, setFilters] = useState<KeyFilterState>(DEFAULT_KEY_FILTERS);+ const [debouncedFilters] = useDebouncedValue(filters, { wait: 300 });- // Extract sort parameters from sorting stateconst sortBy = sorting.length > 0 ? sorting[0].id : null;const sortOrder = sorting.length > 0 ? (sorting[0].desc ? "desc" : "asc") : null;@@ -88,29 +89,22 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoisError,refetch,} = useKeys(tablePagination.pageIndex + 1, tablePagination.pageSize, {+ ...toKeyListFilters(debouncedFilters),sortBy: sortBy || undefined,sortOrder: sortOrder || undefined,expand: "user",});const [expandedAccordions, setExpandedAccordions] = useState<Record<string, boolean>>({});- // Use the filter logic hook-const keyList = useMemo(() => keys?.keys ?? [], [keys]);- const {- filters,- filteredKeys,- filteredTotalCount,- allTeams,- allOrganizations,- handleFilterChange,- handleFilterReset,- } = useFilterLogic({- keys: keyList,- teams,- organizations,+ const { data: fetchedTeams, isLoading: isTeamsLoading } = useQuery<Team[]>({+ queryKey: ["allTeamsForKeyFilters", accessToken],+ queryFn: async () => (accessToken ? await fetchAllTeams(accessToken) : []),+ enabled: !!accessToken,+ staleTime: 30000,});+ const allTeams = useMemo<Team[]>(() => fetchedTeams ?? [], [fetchedTeams]);// Defer the transition so the button stays in loading state until the table// has rendered with the new data (mirrors the spend-logs pattern)@@ -121,23 +115,23 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSorefetch();};- const totalCount = filteredTotalCount ?? keys?.total_count ?? 0;-- // Add a useEffect to call refresh when a key is created- useEffect(() => {- if (refetch) {- const handleStorageChange = () => {- refetch();- };+ const handleFilterChange = (newFilters: Record<string, string>) => {+ setFilters({+ "Team ID": newFilters["Team ID"] || "",+ "Organization ID": newFilters["Organization ID"] || "",+ "Key Alias": newFilters["Key Alias"] || "",+ "User ID": newFilters["User ID"] || "",+ "Key Hash": newFilters["Key Hash"] || "",+ });+ setTablePagination((prev) => ({ ...prev, pageIndex: 0 }));+ };- // Listen for storage events that might indicate a key was created- window.addEventListener("storage", handleStorageChange);+ const handleFilterReset = () => {+ setFilters(DEFAULT_KEY_FILTERS);+ setTablePagination((prev) => ({ ...prev, pageIndex: 0 }));+ };- return () => {- window.removeEventListener("storage", handleStorageChange);- };- }- }, [refetch]);+ const totalCount = keys?.total_count ?? 0;const columns: ColumnDef<KeyResponse>[] = useMemo(() => [@@ -237,7 +231,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSocell: (info) => {const teamId = info.getValue() as string | null;if (!teamId) return "-";- const team = teams?.find((t) => t.team_id === teamId);+ const team = allTeams.find((t) => t.team_id === teamId);const displayValue = team?.team_alias || teamId;const width = info.cell.column.getSize();return (@@ -471,7 +465,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoreturn `$${formatNumberWithCommas(maxBudget)}`;}const teamId = info.row.original.team_id;- const team = teams?.find((t) => t.team_id === teamId);+ const team = allTeams.find((t) => t.team_id === teamId);if (team?.max_budget != null) {return `$${formatNumberWithCommas(team.max_budget)} (Team)`;}@@ -591,7 +585,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo},},],- [teams, resolvedOrganizations],+ [allTeams, resolvedOrganizations],);const filterOptions: FilterOption[] = [@@ -599,6 +593,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoname: "Team ID",label: "Team ID",isSearchable: true,+ loading: isTeamsLoading,searchFn: async (searchText: string) => {if (!allTeams || allTeams.length === 0) return [];@@ -618,10 +613,11 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoname: "Organization ID",label: "Organization ID",isSearchable: true,+ loading: isOrgsLoading,searchFn: async (searchText: string) => {- if (!allOrganizations || allOrganizations.length === 0) return [];+ if (!resolvedOrganizations || resolvedOrganizations.length === 0) return [];- const filteredOrgs = allOrganizations.filter(+ const filteredOrgs = resolvedOrganizations.filter((org) => org.organization_id?.toLowerCase().includes(searchText.toLowerCase()) ?? false,);@@ -651,7 +647,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo];const table = useReactTable({- data: filteredKeys,+ data: keyList,columns: columns.filter((col) => col.id !== "expander"),columnResizeMode: "onChange",columnResizeDirection: "ltr",@@ -662,45 +658,16 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoonSortingChange: (updaterOrValue) => {const newSorting = typeof updaterOrValue === "function" ? updaterOrValue(sorting) : updaterOrValue;setSorting(newSorting);- if (newSorting && newSorting.length > 0) {- const sortState = newSorting[0];- const sortBy = sortState.id;- const sortOrder = sortState.desc ? "desc" : "asc";- // Update filters state without triggering debouncedSearch- // The useKeys hook will automatically refetch with the new sort parameters- handleFilterChange(- {- ...filters,- "Sort By": sortBy,- "Sort Order": sortOrder,- },- true, // skipDebounce - let useKeys handle the API call with correct page size- );- onSortChange?.(sortBy, sortOrder);- }+ setTablePagination((prev) => ({ ...prev, pageIndex: 0 }));},onPaginationChange: setTablePagination,getCoreRowModel: getCoreRowModel(),- getSortedRowModel: getSortedRowModel(),- getPaginationRowModel: getPaginationRowModel(),enableSorting: true,- manualSorting: false,+ manualSorting: true,manualPagination: true,pageCount: Math.ceil(totalCount / tablePagination.pageSize),});- // Update local sorting state when currentSort prop changes- React.useEffect(() => {- if (currentSort) {- setSorting([- {- id: currentSort.sortBy,- desc: currentSort.sortOrder === "desc",- },- ]);- }- }, [currentSort]);-const { pageIndex, pageSize } = table.getState().pagination;const start = pageIndex * pageSize + 1;const end = Math.min((pageIndex + 1) * pageSize, totalCount);@@ -713,7 +680,6 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSoonClose={() => setSelectedKey(null)}keyData={selectedKey}teams={allTeams}- onDelete={refetch}/>) : (<div className="border-b py-4 flex-1 overflow-hidden">@@ -867,7 +833,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo</div></TableCell></TableRow>- ) : filteredKeys.length > 0 ? (+ ) : keyList.length > 0 ? (table.getRowModel().rows.map((row) => (<TableRow key={row.id} className="h-8">{row.getVisibleCells().map((cell) => (diff --git a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.test.tsx b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.test.tsxdeleted file mode 100644index 23259528687..00000000000--- a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.test.tsx+++ /dev/null@@ -1,181 +0,0 @@-import { act, renderHook, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { useFilterLogic } from "./filter_logic";-import { keyListCall } from "../networking";--vi.mock("../networking", () => ({- keyListCall: vi.fn(),-}));--vi.mock("./filter_helpers", () => ({- fetchAllTeams: vi.fn().mockResolvedValue([]),- fetchAllOrganizations: vi.fn().mockResolvedValue([]),-}));--const mockKey = {- token: "abc123",- key_alias: "aaaaa",- team_id: null,- organization_id: null,-};--const defaultProps = {- keys: [mockKey] as any[],- teams: [],- organizations: [],-};--const makeApiResponse = (overrides: { keys?: any[]; total_count?: number; total_pages?: number } = {}) => ({- keys: overrides.keys ?? [mockKey],- total_count: overrides.total_count ?? 1,- current_page: 1,- total_pages: overrides.total_pages ?? 1,-});--describe("useFilterLogic – filteredTotalCount", () => {- beforeEach(() => {- vi.clearAllMocks();- vi.mocked(keyListCall).mockResolvedValue(makeApiResponse({ total_count: 509, total_pages: 11 }));- });-- it("should expose filteredTotalCount as null before any filter search runs", () => {- const { result } = renderHook(() => useFilterLogic(defaultProps));-- expect(result.current.filteredTotalCount).toBeNull();- });-- it("should set filteredTotalCount to the API total_count after a Key Alias filter is applied", async () => {- vi.mocked(keyListCall).mockResolvedValue(makeApiResponse({ keys: [mockKey], total_count: 1, total_pages: 1 }));-- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Key Alias": "aaaaa" });- });-- await waitFor(- () => {- expect(result.current.filteredTotalCount).toBe(1);- },- { timeout: 500 },- );- });-- it("should reflect the filtered total_count even when it differs from the full key count", async () => {- vi.mocked(keyListCall).mockResolvedValue(makeApiResponse({ total_count: 7, total_pages: 1 }));-- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Team ID": "team-x" });- });-- await waitFor(- () => {- expect(result.current.filteredTotalCount).toBe(7);- },- { timeout: 500 },- );- });-- it("should reset filteredTotalCount to null when handleFilterReset is called", async () => {- vi.mocked(keyListCall).mockResolvedValue(makeApiResponse({ total_count: 1 }));-- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Key Alias": "aaaaa" });- });-- await waitFor(- () => {- expect(result.current.filteredTotalCount).toBe(1);- },- { timeout: 500 },- );-- act(() => {- result.current.handleFilterReset();- });-- // filteredTotalCount resets synchronously before the debounced reset search completes- expect(result.current.filteredTotalCount).toBeNull();- });-- it("should pass the Key Alias value to keyListCall", async () => {- vi.mocked(keyListCall).mockResolvedValue(makeApiResponse({ total_count: 2 }));-- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Key Alias": "my-alias" });- });-- await waitFor(- () => {- expect(keyListCall).toHaveBeenCalledWith(- expect.any(String), // accessToken- null, // organizationID (empty → null)- null, // teamID (empty → null)- "my-alias", // selectedKeyAlias ← the filter value- null, // userID- null, // keyHash- 1, // page (resets to 1 on filter change)- expect.any(Number), // pageSize (defaultPageSize)- expect.anything(), // sortBy- expect.anything(), // sortOrder- );- },- { timeout: 500 },- );- });-- it("should not update filteredTotalCount when keyListCall throws", async () => {- vi.mocked(keyListCall).mockRejectedValue(new Error("Network error"));-- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Key Alias": "bad-alias" });- });-- await waitFor(- () => {- expect(keyListCall).toHaveBeenCalled();- },- { timeout: 500 },- );-- expect(result.current.filteredTotalCount).toBeNull();- });-- it("should not enter an infinite update loop when keys is a fresh array reference on every render", () => {- const sourceKeys = [mockKey];- let renderCount = 0;-- const { result } = renderHook(() => {- renderCount += 1;- const value = useFilterLogic({ keys: [...sourceKeys], teams: [], organizations: [] });- if (renderCount > 25) {- throw new Error(`useFilterLogic re-rendered ${renderCount} times; setFilteredKeys is looping`);- }- return value;- });-- expect(result.current.filteredKeys).toEqual([mockKey]);- expect(renderCount).toBeLessThanOrEqual(25);- });-- it("should not trigger a debounced search when skipDebounce is true", async () => {- const { result } = renderHook(() => useFilterLogic(defaultProps));-- act(() => {- result.current.handleFilterChange({ "Sort By": "spend", "Sort Order": "asc" }, true);- });-- await new Promise((resolve) => setTimeout(resolve, 350));-- expect(keyListCall).not.toHaveBeenCalled();- expect(result.current.filteredTotalCount).toBeNull();- });-});diff --git a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsxdeleted file mode 100644index e31a6fbee38..00000000000--- a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx+++ /dev/null@@ -1,188 +0,0 @@-import { useCallback, useEffect, useState, useRef } from "react";-import { KeyResponse } from "../key_team_helpers/key_list";-import { keyListCall, Organization } from "../networking";-import { Team } from "../key_team_helpers/key_list";-import { fetchAllOrganizations, fetchAllTeams } from "./filter_helpers";-import { debounce } from "lodash";-import { defaultPageSize } from "../constants";-import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";--export interface FilterState {- "Team ID": string;- "Organization ID": string;- "Key Alias": string;- [key: string]: string;- "User ID": string;- "Sort By": string;- "Sort Order": string;-}--export function useFilterLogic({- keys,- teams,- organizations,-}: {- keys: KeyResponse[];- teams: Team[] | null;- organizations: Organization[] | null;-}) {- const defaultFilters: FilterState = {- "Team ID": "",- "Organization ID": "",- "Key Alias": "",- "User ID": "",- "Sort By": "created_at",- "Sort Order": "desc",- };- const { accessToken } = useAuthorized();- const [filters, setFilters] = useState<FilterState>(defaultFilters);- const [allTeams, setAllTeams] = useState<Team[]>(teams || []);- const [allOrganizations, setAllOrganizations] = useState<Organization[]>(organizations || []);- const [filteredKeys, setFilteredKeys] = useState<KeyResponse[]>(keys);- const [filteredTotalCount, setFilteredTotalCount] = useState<number | null>(null);- const lastSearchTimestamp = useRef(0);- const debouncedSearch = useCallback(- debounce(async (filters: FilterState) => {- if (!accessToken) {- return;- }-- const currentTimestamp = Date.now();- lastSearchTimestamp.current = currentTimestamp;-- try {- // Make the API call using userListCall with all filter parameters- const data = await keyListCall(- accessToken,- filters["Organization ID"] || null,- filters["Team ID"] || null,- filters["Key Alias"] || null,- filters["User ID"] || null,- filters["Key Hash"] || null,- 1, // Reset to first page when searching- defaultPageSize,- filters["Sort By"] || null,- filters["Sort Order"] || null,- );-- // Only update state if this is the most recent search- if (currentTimestamp === lastSearchTimestamp.current) {- if (data) {- setFilteredKeys(data.keys);- setFilteredTotalCount(data.total_count ?? null);- console.log("called from debouncedSearch filters:", JSON.stringify(filters));- console.log("called from debouncedSearch data:", JSON.stringify(data));- }- }- } catch (error) {- console.error("Error searching users:", error);- }- }, 300),- [accessToken],- );- // Apply filters to keys whenever keys or filters change- useEffect(() => {- if (!keys) {- setFilteredKeys([]);- return;- }-- let result = [...keys];-- // Apply Team ID filter- if (filters["Team ID"]) {- result = result.filter((key) => key.team_id === filters["Team ID"]);- }-- // Apply Organization ID filter- if (filters["Organization ID"]) {- result = result.filter((key) => (key.organization_id ?? key.org_id) === filters["Organization ID"]);- }-- setFilteredKeys((prev) =>- prev.length === result.length && prev.every((key, index) => key === result[index]) ? prev : result,- );- }, [keys, filters]);-- // Fetch all data for filters when component mounts- useEffect(() => {- const loadAllFilterData = async () => {- // Load all teams - no organization filter needed here- const teamsData = await fetchAllTeams(accessToken);- if (teamsData.length > 0) {- setAllTeams(teamsData);- }-- // Load all organizations- const orgsData = await fetchAllOrganizations(accessToken);- if (orgsData.length > 0) {- setAllOrganizations(orgsData);- }- };-- if (accessToken) {- loadAllFilterData();- }- }, [accessToken]);-- // Update teams and organizations when props change- useEffect(() => {- if (teams && teams.length > 0) {- setAllTeams((prevTeams) => {- // Only update if we don't already have a larger set of teams- return prevTeams.length < teams.length ? teams : prevTeams;- });- }- }, [teams]);-- useEffect(() => {- if (organizations && organizations.length > 0) {- setAllOrganizations((prevOrgs) => {- // Only update if we don't already have a larger set of organizations- return prevOrgs.length < organizations.length ? organizations : prevOrgs;- });- }- }, [organizations]);-- const handleFilterChange = (newFilters: Record<string, string>, skipDebounce: boolean = false) => {- // Update filters state- setFilters({- "Team ID": newFilters["Team ID"] || "",- "Organization ID": newFilters["Organization ID"] || "",- "Key Alias": newFilters["Key Alias"] || "",- "User ID": newFilters["User ID"] || "",- "Sort By": newFilters["Sort By"] || "created_at",- "Sort Order": newFilters["Sort Order"] || "desc",- });-- // Only trigger debouncedSearch if skipDebounce is false- // This allows sorting to be handled by the parent component's useKeys hook- if (!skipDebounce) {- // Fetch keys based on new filters- const updatedFilters = {- ...filters,- ...newFilters,- };- debouncedSearch(updatedFilters);- }- };-- const handleFilterReset = () => {- // Reset filters state- setFilters(defaultFilters);- setFilteredTotalCount(null);-- // Reset selections- debouncedSearch(defaultFilters);- };-- return {- filters,- filteredKeys,- filteredTotalCount,- allTeams,- allOrganizations,- handleFilterChange,- handleFilterReset,- };-}diff --git a/ui/litellm-dashboard/src/components/molecules/filter.test.tsx b/ui/litellm-dashboard/src/components/molecules/filter.test.tsxindex 3a15c5c84f1..d956cd93168 100644--- a/ui/litellm-dashboard/src/components/molecules/filter.test.tsx+++ b/ui/litellm-dashboard/src/components/molecules/filter.test.tsx@@ -326,6 +326,67 @@ describe("FilterComponent", () => {});});+ it("shows a loading state (not an empty list) while a searchable filter's data is still loading", async () => {+ const user = userEvent.setup({ delay: null });+ const mockSearchFn = vi.fn().mockResolvedValue([]);++ const options: FilterOption[] = [+ {+ name: "model",+ label: "Model",+ isSearchable: true,+ loading: true,+ searchFn: mockSearchFn,+ },+ ];++ renderWithProviders(+ <FilterComponent options={options} onApplyFilters={mockOnApplyFilters} onResetFilters={mockOnResetFilters} />,+ );++ await user.click(screen.getByRole("button", { name: "Filters" }));++ const modelLabel = screen.getByText("Model");+ const modelSelect = within(modelLabel.closest("div")!).getByRole("combobox");+ await user.click(modelSelect);++ await waitFor(() => {+ expect(screen.getByText("Loading...")).toBeInTheDocument();+ });+ expect(screen.queryByText("No results found")).not.toBeInTheDocument();+ // It must not cache an empty initial-options list while the source is still loading.+ expect(mockSearchFn).not.toHaveBeenCalled();+ });++ it("loads initial options once a searchable filter's data finishes loading", async () => {+ const user = userEvent.setup({ delay: null });+ const mockSearchFn = vi.fn().mockResolvedValue([{ label: "Team A", value: "team-a" }]);+ const baseOption: FilterOption = { name: "model", label: "Model", isSearchable: true, searchFn: mockSearchFn };++ const { rerender } = renderWithProviders(+ <FilterComponent+ options={[{ ...baseOption, loading: true }]}+ onApplyFilters={mockOnApplyFilters}+ onResetFilters={mockOnResetFilters}+ />,+ );++ await user.click(screen.getByRole("button", { name: "Filters" }));+ expect(mockSearchFn).not.toHaveBeenCalled();++ rerender(+ <FilterComponent+ options={[{ ...baseOption, loading: false }]}+ onApplyFilters={mockOnApplyFilters}+ onResetFilters={mockOnResetFilters}+ />,+ );++ await waitFor(() => {+ expect(mockSearchFn).toHaveBeenCalledWith("");+ });+ });+it("should handle search errors gracefully", async () => {const user = userEvent.setup({ delay: null });const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});diff --git a/ui/litellm-dashboard/src/components/molecules/filter.tsx b/ui/litellm-dashboard/src/components/molecules/filter.tsxindex 7086892c32d..45ad3a6b9ca 100644--- a/ui/litellm-dashboard/src/components/molecules/filter.tsx+++ b/ui/litellm-dashboard/src/components/molecules/filter.tsx@@ -17,6 +17,7 @@ export interface FilterOption {searchFn?: (searchText: string) => Promise<Array<{ label: string; value: string }>>;options?: Array<{ label: string; value: string }>;customComponent?: React.ComponentType<FilterOptionCustomComponentProps>;+ loading?: boolean;}interface FilterValues {@@ -74,7 +75,7 @@ const FilterComponent: React.FC<FilterComponentProps> = ({// Load initial options for searchable filtersconst loadInitialOptions = useCallback(async (option: FilterOption) => {- if (!option.isSearchable || !option.searchFn || initialOptionsLoaded[option.name]) return;+ if (!option.isSearchable || !option.searchFn || option.loading || initialOptionsLoaded[option.name]) return;setSearchLoadingMap((prev) => ({ ...prev, [option.name]: true }));setInitialOptionsLoaded((prev) => ({ ...prev, [option.name]: true }));@@ -145,6 +146,7 @@ const FilterComponent: React.FC<FilterComponentProps> = ({{showFilters && (<div className="grid grid-cols-3 gap-x-6 gap-y-4 mb-6">{options.map((option) => {+ const isOptionLoading = searchLoadingMap[option.name] || option.loading;return (<div key={option.name} className="flex flex-col gap-2"><label className="text-sm text-gray-600">{option.label || option.name}</label>@@ -166,10 +168,10 @@ const FilterComponent: React.FC<FilterComponentProps> = ({}}}filterOption={false}- loading={searchLoadingMap[option.name]}+ loading={isOptionLoading}options={searchOptionsMap[option.name] || []}allowClear- notFoundContent={searchLoadingMap[option.name] ? "Loading..." : "No results found"}+ notFoundContent={isOptionLoading ? "Loading..." : "No results found"}/>) : option.options ? (<Selectdiff --git a/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx b/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsxindex abbc92f0210..0bf0a48f285 100644--- a/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx@@ -267,6 +267,15 @@ vi.mock("@/app/(dashboard)/hooks/keys/useResetKeySpend", () => ({}),}));+// useQueryClient also needs a provider; the delete-path invalidation is covered in key_info_view.test.tsx+vi.mock("@tanstack/react-query", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();+ return {+ ...actual,+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),+ };+});+// KeyEditView mock: triggers onSubmit with our injected form valuesvi.mock("./key_edit_view", async () => {const React = await import("react");diff --git a/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx b/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsxindex c762e1ac14b..5e9156fcacf 100644--- a/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx@@ -7,7 +7,8 @@ import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { useResetKeySpend } from "@/app/(dashboard)/hooks/keys/useResetKeySpend";import { KeyResponse, Team } from "../key_team_helpers/key_list";-import { keyUpdateCall } from "../networking";+import { keyDeleteCall, keyUpdateCall } from "../networking";+import { QueryClient } from "@tanstack/react-query";import KeyInfoView from "./key_info_view";const editViewMocks = vi.hoisted(() => ({@@ -787,4 +788,38 @@ describe("KeyInfoView", () => {expect(keyUpdateCall).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ policies: [] }));});});++ describe("delete flow", () => {+ it("invalidates the keys list query after a successful delete so active filters survive (LIT-4080)", async () => {+ const invalidateSpy = vi.spyOn(QueryClient.prototype, "invalidateQueries");+ vi.mocked(useAuthorized).mockReturnValue({+ ...baseUseAuthorizedMock,+ userId: "proxy-admin-user",+ userRole: "proxy_admin",+ });++ renderWithProviders(+ <KeyInfoView+ keyData={MOCK_KEY_DATA}+ onClose={() => {}}+ keyId="test-key-id"+ onKeyDataUpdate={() => {}}+ teams={[]}+ />,+ );++ await userEvent.click(await screen.findByRole("button", { name: /delete key/i }));++ const confirmInput = await screen.findByPlaceholderText(MOCK_KEY_DATA.key_alias);+ await userEvent.type(confirmInput, MOCK_KEY_DATA.key_alias);+ await userEvent.click(screen.getByRole("button", { name: /^delete$/i }));++ await waitFor(() => {+ expect(keyDeleteCall).toHaveBeenCalledWith("test-token", MOCK_KEY_DATA.token);+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ["keys", "list"] });+ });++ invalidateSpy.mockRestore();+ });+ });});diff --git a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx b/ui/litellm-dashboard/src/components/templates/key_info_view.tsxindex 4244ae2d794..24d5c78c72b 100644--- a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_info_view.tsx@@ -19,6 +19,8 @@ import LoggingSettingsView from "../logging_settings_view";import NotificationManager from "../molecules/notifications_manager";import { getPolicyInfoWithGuardrails, keyDeleteCall, keyUpdateCall } from "../networking";import { useResetKeySpend } from "@/app/(dashboard)/hooks/keys/useResetKeySpend";+import { keyKeys } from "@/app/(dashboard)/hooks/keys/useKeys";+import { useQueryClient } from "@tanstack/react-query";import ObjectPermissionsView from "../object_permissions_view";import { RegenerateKeyModal } from "../organisms/RegenerateKeyModal";import { parseErrorMessage } from "../shared/errorUtils";@@ -64,6 +66,7 @@ export default function KeyInfoView({backButtonText = "Back to Keys",}: KeyInfoViewProps) {const { accessToken, userId: userID, userRole, premiumUser } = useAuthorized();+ const queryClient = useQueryClient();const canEditGuardrails = premiumUser || (userRole != null && rolesWithWriteAccess.includes(userRole));const { teams: teamsData } = useTeams();const { data: projects } = useProjects();@@ -322,6 +325,7 @@ export default function KeyInfoView({if (!accessToken) return;await keyDeleteCall(accessToken as string, currentKeyData.token || currentKeyData.token_id);NotificationManager.success("Key deleted successfully");+ await queryClient.invalidateQueries({ queryKey: keyKeys.lists() });if (onDelete) {onDelete();}diff --git a/ui/litellm-dashboard/src/components/user_dashboard.test.tsx b/ui/litellm-dashboard/src/components/user_dashboard.test.tsxindex 1517fadce2a..01764613bf5 100644--- a/ui/litellm-dashboard/src/components/user_dashboard.test.tsx+++ b/ui/litellm-dashboard/src/components/user_dashboard.test.tsx@@ -85,7 +85,6 @@ const defaultProps = {setTeams: vi.fn(),setKeys: vi.fn(),premiumUser: false,- organizations: [] as any[],addKey: vi.fn(),createClicked: false,};diff --git a/ui/litellm-dashboard/src/components/user_dashboard.tsx b/ui/litellm-dashboard/src/components/user_dashboard.tsxindex db262bc84a1..dc26257b70c 100644--- a/ui/litellm-dashboard/src/components/user_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/user_dashboard.tsx@@ -45,7 +45,6 @@ interface UserDashboardProps {setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>;setKeys: (keys: KeyResponse[]) => void;premiumUser: boolean;- organizations: Organization[] | null;addKey: (data: any) => void;createClicked: boolean;autoOpenCreate?: boolean;@@ -69,7 +68,6 @@ const UserDashboard: React.FC<UserDashboardProps> = ({setTeams,setKeys,premiumUser,- organizations,addKey,createClicked,autoOpenCreate,@@ -338,7 +336,7 @@ const UserDashboard: React.FC<UserDashboardProps> = ({prefillData={prefillData}/>)}- <VirtualKeysTable teams={teams} organizations={organizations} />+ <VirtualKeysTable /></Col></Grid></div>