From 60a4b05f73bfb4001f044bd31444e72716823232 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Sat, 27 Jun 2026 15:19:47 -0700 Subject: [PATCH 1/5] fix(ui): keep virtual-keys filters across delete and refresh (LIT-4080) Filtering virtual keys by User ID and then deleting a key reset the filter to show all keys, and re-clicking Fetch did not re-apply it. The page ran two competing fetch paths: useKeys (React Query) fetched the page unfiltered while a separate useFilterLogic hook held its own filteredKeys list and, on any refresh, only re-applied Team and Organization client-side, silently dropping the User ID and Key Alias filters. Delete refreshed through the unfiltered useKeys path, so the filtered view collapsed back to everything VirtualKeysTable now owns its filter state and feeds every filter (team, organization, key alias, user id, key hash) straight into the useKeys options, so the filters are part of the React Query key. Any refetch or invalidation re-runs the same filtered query, which makes the reset-on-delete bug structurally impossible. Free-text inputs are debounced with @tanstack/react-pacer, sorting and pagination are server-side, and changing a filter or sort resets to page 1 Delete now invalidates keyKeys.lists() from key_info_view, matching the create path, instead of prop-drilling a refetch; the window "storage" refetch effect is removed. The dual-path useFilterLogic hook (and its test) are deleted Regression coverage: VirtualKeysTable threads an active User ID filter into the useKeys query and clears it on reset, useKeys encodes filter options in its query key so a filter change refetches, and key_info_view invalidates the keys list on delete --- .../(dashboard)/hooks/keys/useKeys.test.ts | 25 + .../VirtualKeysPage/VirtualKeysTable.test.tsx | 839 +++--------------- .../VirtualKeysPage/VirtualKeysTable.tsx | 118 +-- .../key_team_helpers/filter_logic.test.tsx | 181 ---- .../key_team_helpers/filter_logic.tsx | 188 ---- .../KeyInfoView.handleKeyUpdate.test.tsx | 9 + .../templates/key_info_view.test.tsx | 37 +- .../components/templates/key_info_view.tsx | 4 + 8 files changed, 256 insertions(+), 1145 deletions(-) delete mode 100644 ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.test.tsx delete mode 100644 ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx 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.ts index 4f534b4117e3..0867b9351c10 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 @@ -459,6 +459,31 @@ describe("useKeys", () => { const callUrl = mockFetch.mock.calls[0][0]; 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"); + }); }); describe("useDeletedKeys", () => { diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx index 4002bbd245f7..449b1933c22f 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(); +// Debounce 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("react"); return { - ...actual, - userListCall: vi.fn().mockResolvedValue({ - users: [ - { - user_id: "user-1", - user_email: "user@example.com", - user_role: "user", - }, - ], - }), - teamListCall: vi.fn().mockResolvedValue([]), + 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 hook vi.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(); - 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,6 +128,7 @@ const mockTeam: Team = { created_at: "2024-10-01T10:00:00Z", keys: [], members_with_roles: [], + spend: 0, }; const mockOrganization: Organization = { @@ -173,48 +149,35 @@ const mockOrganization: Organization = { members: [], }; -// Mock hook implementations const mockUseKeys = useKeys as MockedFunction; -const mockUseFilterLogic = useFilterLogic as MockedFunction; const mockUseTeams = useTeams as MockedFunction; -beforeEach(() => { - // Reset mocks before each test - vi.clearAllMocks(); - - // Setup default mock implementations - mockUseKeys.mockReturnValue({ +const keysResult = (keys: KeyResponse[], data: Partial = {}, extra: Record = {}) => + ({ 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": "user@example.com", - "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; + +const defaultMockProps = { + teams: [mockTeam], + organizations: [mockOrganization], +}; + +beforeEach(() => { + vi.clearAllMocks(); + + mockUseKeys.mockReturnValue(keysResult([mockKey])); - // Mock useTeams hook (used by KeyInfoView) mockUseTeams.mockReturnValue({ teams: [mockTeam], setTeams: vi.fn(), @@ -222,33 +185,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(); - + renderWithProviders(); 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(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); @@ -258,17 +200,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(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("user@example.com")).toBeInTheDocument(); @@ -276,121 +208,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(); + renderWithProviders(); - // Check that loading message is shown on initial load expect(screen.getByText("🚅 Loading keys...")).toBeInTheDocument(); - - // Check that actual key data is not shown expect(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(), - }); - - const mockProps = { - teams: [mockTeam], - organizations: [mockOrganization], - onSortChange: vi.fn(), - currentSort: { - sortBy: "created_at", - sortOrder: "desc" as const, - }, - }; +it("should show 'No keys found' message when the key list is empty", () => { + mockUseKeys.mockReturnValue(keysResult([])); - renderWithProviders(); + renderWithProviders(); 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(), - }); + mockUseKeys.mockReturnValue( + keysResult([{ ...mockKey, models: ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "claude-3", "claude-3-5-sonnet"] }]), + ); - const mockProps = { - teams: [mockTeam], - organizations: [mockOrganization], - onSortChange: vi.fn(), - currentSort: { - sortBy: "created_at", - sortOrder: "desc" as const, - }, - }; + renderWithProviders(); - renderWithProviders(); - - // 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 ChevronRightIcon expect(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(); + renderWithProviders(); - // 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,440 +246,143 @@ 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(); + renderWithProviders(); - // Find a header cell with data-header-id attribute const headerCell = document.querySelector("[data-header-id]") as HTMLElement; - expect(headerCell).toBeInTheDocument(); - // Check that the resizer element exists within the header const resizer = headerCell?.querySelector(".resizer") as HTMLElement; expect(resizer).toBeInTheDocument(); - - // Initially, resizer should have opacity 0 expect(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(); + renderWithProviders(); - // Wait for the table to render await waitFor(() => { expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); }); - // Verify table is visible before clicking - check for table-specific text expect(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 button fireEvent.click(keyIdButton); - // Wait for KeyInfoView to appear - check for unique elements that only exist in KeyInfoView await waitFor(() => { expect(screen.getByText("Back to Keys")).toBeInTheDocument(); - // KeyInfoHeader shows "Created At" metadata label expect(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 open expect(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(); + renderWithProviders(); 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(); - - 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: "creator@example.com", - 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: "creator@example.com", user_alias: null }, + }, + ]), + ); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("creator@example.com")).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: "creator@example.com", - 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, - }, - }; - - renderWithProviders(); - - await waitFor(() => { - expect(screen.getByText("The Creator")).toBeInTheDocument(); - }); -}); - it("should render table without crashing when models is null", async () => { - const keyWithNullModels = { - ...mockKey, - models: null as unknown as string[], - }; + mockUseKeys.mockReturnValue(keysResult([{ ...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, - }, - }; - - // This should not throw an error - renderWithProviders(); + renderWithProviders(); 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(); + renderWithProviders(); 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(); - renderWithProviders(); + 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(); + it("does not send filter params to useKeys when no filter is active", () => { + renderWithProviders(); - 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(); - 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(); + 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(); @@ -842,35 +392,8 @@ 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(); @@ -879,44 +402,6 @@ describe("pagination display – total count and page count", () => { 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(); - - await waitFor(() => { - expect(screen.queryByText(/509 results/)).not.toBeInTheDocument(); - expect(screen.queryByText(/of 11/)).not.toBeInTheDocument(); - }); - }); }); describe("refetch button", () => { @@ -930,62 +415,29 @@ 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); + mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { isFetching: true })); renderWithProviders(); - // Button should show "Fetching" and be disabled expect(screen.getByText("Fetching")).toBeInTheDocument(); - const fetchButton = screen.getByTitle("Fetch data"); - expect(fetchButton).toBeDisabled(); - - // Table data should still be visible (stale data) + expect(screen.getByTitle("Fetch data")).toBeDisabled(); expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); - - // "Loading keys..." should NOT appear during refetch 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); + mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { refetch: mockRefetch })); renderWithProviders(); - const fetchButton = screen.getByTitle("Fetch data"); - fireEvent.click(fetchButton); + 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(); @@ -997,22 +449,7 @@ 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(); @@ -1022,22 +459,7 @@ 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(); @@ -1048,22 +470,7 @@ 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(); diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx index 0c95d5dcfb7f..b5401d1f2a01 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 { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations"; +import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; +import { useQuery } from "@tanstack/react-query"; +import { useDebouncedState } 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,9 +28,9 @@ 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"; @@ -47,12 +48,24 @@ interface VirtualKeysTableProps { }; } -/** - * 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. - */ +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": "", +}; export function VirtualKeysTable({ teams, organizations, onSortChange, currentSort }: VirtualKeysTableProps) { + const { accessToken } = useAuthorized(); const { data: fetchedOrganizations } = useOrganizations(); const resolvedOrganizations = fetchedOrganizations ?? organizations ?? []; const [selectedKey, setSelectedKey] = useState(null); @@ -76,8 +89,9 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo pageIndex: 0, pageSize: 50, }); + const [filters, setFilters] = useState(DEFAULT_KEY_FILTERS); + const [debouncedFilters, setDebouncedFilters] = useDebouncedState(filters, { wait: 300 }); - // Extract sort parameters from sorting state const sortBy = sorting.length > 0 ? sorting[0].id : null; const sortOrder = sorting.length > 0 ? (sorting[0].desc ? "desc" : "asc") : null; @@ -88,29 +102,26 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo isError, refetch, } = useKeys(tablePagination.pageIndex + 1, tablePagination.pageSize, { + teamID: debouncedFilters["Team ID"]?.trim() || undefined, + organizationID: debouncedFilters["Organization ID"]?.trim() || undefined, + selectedKeyAlias: debouncedFilters["Key Alias"]?.trim() || undefined, + userID: debouncedFilters["User ID"]?.trim() || undefined, + keyHash: debouncedFilters["Key Hash"]?.trim() || undefined, sortBy: sortBy || undefined, sortOrder: sortOrder || undefined, expand: "user", }); const [expandedAccordions, setExpandedAccordions] = useState>({}); - // 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 } = useQuery({ + queryKey: ["allTeamsForKeyFilters", accessToken], + queryFn: async () => (accessToken ? await fetchAllTeams(accessToken) : []), + enabled: !!accessToken, + staleTime: 30000, }); + const allTeams = fetchedTeams && fetchedTeams.length > 0 ? fetchedTeams : teams ?? []; // 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 +132,26 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo refetch(); }; - 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) => { + const nextFilters: KeyFilterState = { + "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"] || "", + }; + setFilters(nextFilters); + setDebouncedFilters(nextFilters); + 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); + setDebouncedFilters(DEFAULT_KEY_FILTERS); + setTablePagination((prev) => ({ ...prev, pageIndex: 0 })); + }; - return () => { - window.removeEventListener("storage", handleStorageChange); - }; - } - }, [refetch]); + const totalCount = keys?.total_count ?? 0; const columns: ColumnDef[] = useMemo( () => [ @@ -619,9 +633,9 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo label: "Organization ID", isSearchable: true, 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 +665,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,29 +676,16 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo onSortingChange: (updaterOrValue) => { const newSorting = typeof updaterOrValue === "function" ? updaterOrValue(sorting) : updaterOrValue; setSorting(newSorting); + setTablePagination((prev) => ({ ...prev, pageIndex: 0 })); 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); + onSortChange?.(sortState.id, sortState.desc ? "desc" : "asc"); } }, onPaginationChange: setTablePagination, getCoreRowModel: getCoreRowModel(), - getSortedRowModel: getSortedRowModel(), - getPaginationRowModel: getPaginationRowModel(), enableSorting: true, - manualSorting: false, + manualSorting: true, manualPagination: true, pageCount: Math.ceil(totalCount / tablePagination.pageSize), }); @@ -713,7 +714,6 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo onClose={() => setSelectedKey(null)} keyData={selectedKey} teams={allTeams} - onDelete={refetch} /> ) : (
@@ -867,7 +867,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo
- ) : filteredKeys.length > 0 ? ( + ) : keyList.length > 0 ? ( table.getRowModel().rows.map((row) => ( {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.tsx deleted file mode 100644 index 232595286873..000000000000 --- 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.tsx deleted file mode 100644 index e31a6fbee382..000000000000 --- 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(defaultFilters); - const [allTeams, setAllTeams] = useState(teams || []); - const [allOrganizations, setAllOrganizations] = useState(organizations || []); - const [filteredKeys, setFilteredKeys] = useState(keys); - const [filteredTotalCount, setFilteredTotalCount] = useState(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, 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/templates/KeyInfoView.handleKeyUpdate.test.tsx b/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx index abbc92f02104..0bf0a48f2852 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(); + return { + ...actual, + useQueryClient: () => ({ invalidateQueries: vi.fn() }), + }; +}); + // KeyEditView mock: triggers onSubmit with our injected form values vi.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.tsx index c762e1ac14b2..5e9156fcacfa 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( + {}} + 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.tsx index 4244ae2d794d..24d5c78c72ba 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(); } From 3139758377243877e3b876f4fc606ee6c14a3bd4 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 29 Jun 2026 09:17:28 -0700 Subject: [PATCH 2/5] refactor(ui): simplify virtual-keys table data flow VirtualKeysTable now fetches its own teams and organizations via useOrganizations and the existing all-teams query instead of taking them as props, so the prop-drill through UserDashboard and the two page callers (page.tsx, ApiKeysDashboard) is gone along with their redundant organization state and fetch Filter state collapses from a useState plus a useDebouncedState mirror into a single source whose debounced copy is derived with useDebouncedValue, and one typed toKeyListFilters adapter maps it to the key/list query options. Behavior is unchanged; same 300ms debounce and the same reset timing The unused onSortChange/currentSort props and their sync effect are removed since no caller passed them, leaving sorting fully internal Adds a created_by_user alias-over-email regression test that fails if the display precedence is swapped --- .../api-keys/ApiKeysDashboard.test.tsx | 4 - .../(dashboard)/api-keys/ApiKeysDashboard.tsx | 7 -- .../src/app/(dashboard)/page.tsx | 8 +- .../VirtualKeysPage/VirtualKeysTable.test.tsx | 96 +++++++++---------- .../VirtualKeysPage/VirtualKeysTable.tsx | 88 +++++------------ .../src/components/user_dashboard.test.tsx | 1 - .../src/components/user_dashboard.tsx | 4 +- 7 files changed, 74 insertions(+), 134 deletions(-) diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/ApiKeysDashboard.test.tsx index 3a3251ea76ab..13689afcb52d 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.tsx index 54f4bf41a21a..ae0c443910a8 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(null); const [keys, setKeys] = useState([]); - const [organizations, setOrganizations] = useState([]); const [createClicked, setCreateClicked] = useState(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)/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/page.tsx index c5d28fab8a0a..cb4a4a0de039 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(null); const [keys, setKeys] = useState([]); - const [organizations, setOrganizations] = useState([]); 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.tsx index 449b1933c22f..6389b82c9fd7 100644 --- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx +++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx @@ -3,14 +3,14 @@ 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 useTeams from "@/app/(dashboard)/hooks/useTeams"; -// Debounce synchronously so an applied filter lands in the useKeys query within the test tick. +// 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("react"); return { + 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() }]; @@ -131,24 +131,6 @@ const mockTeam: Team = { 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: [], -}; - const mockUseKeys = useKeys as MockedFunction; const mockUseTeams = useTeams as MockedFunction; @@ -168,11 +150,6 @@ const keysResult = (keys: KeyResponse[], data: Partial = {}, extra ...extra, }) as any; -const defaultMockProps = { - teams: [mockTeam], - organizations: [mockOrganization], -}; - beforeEach(() => { vi.clearAllMocks(); @@ -185,12 +162,12 @@ beforeEach(() => { }); it("should render VirtualKeysTable component", () => { - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); }); it("should display key information correctly", async () => { - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); @@ -200,7 +177,7 @@ it("should display key information correctly", async () => { }); it("should display user email correctly", async () => { - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("user@example.com")).toBeInTheDocument(); @@ -210,7 +187,7 @@ it("should display user email correctly", async () => { it("should show loading message only on initial load (isPending)", () => { mockUseKeys.mockReturnValue(keysResult([], {}, { data: null, isPending: true, isFetching: true })); - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("🚅 Loading keys...")).toBeInTheDocument(); expect(screen.queryByText("Test Key Alias")).not.toBeInTheDocument(); @@ -220,7 +197,7 @@ it("should show loading message only on initial load (isPending)", () => { it("should show 'No keys found' message when the key list is empty", () => { mockUseKeys.mockReturnValue(keysResult([])); - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("No keys found")).toBeInTheDocument(); }); @@ -230,13 +207,13 @@ it("should handle models with more than 3 entries to trigger expansion UI", () = keysResult([{ ...mockKey, models: ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "claude-3", "claude-3-5-sonnet"] }]), ); - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); }); it("should render table headers correctly", () => { - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("Key ID")).toBeInTheDocument(); expect(screen.getByText("Key Alias")).toBeInTheDocument(); @@ -246,7 +223,7 @@ it("should render table headers correctly", () => { }); it("should handle column resizing hover events", () => { - renderWithProviders(); + renderWithProviders(); const headerCell = document.querySelector("[data-header-id]") as HTMLElement; expect(headerCell).toBeInTheDocument(); @@ -263,7 +240,7 @@ it("should handle column resizing hover events", () => { }); it("should open KeyInfoView when clicking on a key ID button", async () => { - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); @@ -294,7 +271,7 @@ it("should display 'Default Proxy Admin' for user_id when value is 'default_user ]), ); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Default Proxy Admin")).toBeInTheDocument(); @@ -312,17 +289,36 @@ it("should display created_by_user email in 'Created By' column when available", ]), ); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("creator@example.com")).toBeInTheDocument(); }); }); +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: "creator@example.com", user_alias: "The Creator" }, + }, + ]), + ); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("The Creator")).toBeInTheDocument(); + }); + expect(screen.queryByText("creator@example.com")).not.toBeInTheDocument(); +}); + it("should render table without crashing when models is null", async () => { mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, models: null as unknown as string[] }])); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Test Key Alias")).toBeInTheDocument(); @@ -332,7 +328,7 @@ it("should render table without crashing when models is null", async () => { it("should display 'Unknown' for last_active when value is null", async () => { mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, last_active: null }])); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Unknown")).toBeInTheDocument(); @@ -341,7 +337,7 @@ it("should display 'Unknown' for last_active when value is null", async () => { 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(); + renderWithProviders(); fireEvent.click(screen.getByRole("button", { name: "Filters" })); @@ -354,14 +350,14 @@ describe("server-side filtering – the LIT-4080 regression guard", () => { }); it("does not send filter params to useKeys when no filter is active", () => { - renderWithProviders(); + renderWithProviders(); const lastCall = mockUseKeys.mock.calls[mockUseKeys.mock.calls.length - 1]; expect(lastCall[2] ?? {}).toMatchObject({ userID: undefined, teamID: undefined, keyHash: undefined }); }); it("drops the filter from the useKeys query when Reset Filters is clicked", async () => { - renderWithProviders(); + renderWithProviders(); fireEvent.click(screen.getByRole("button", { name: "Filters" })); const userIdInput = await screen.findByPlaceholderText("Enter User ID..."); @@ -384,7 +380,7 @@ 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(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Showing 1 - 50 of 509 results")).toBeInTheDocument(); @@ -395,7 +391,7 @@ describe("pagination display – total count comes from useKeys", () => { it("reflects a narrowed total when a filtered fetch returns fewer results", async () => { mockUseKeys.mockReturnValue(keysResult([mockKey], { total_count: 1, total_pages: 1 })); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByText("Showing 1 - 1 of 1 results")).toBeInTheDocument(); @@ -406,7 +402,7 @@ describe("pagination display – total count comes from useKeys", () => { describe("refetch button", () => { it("should show Fetch button in normal state", () => { - renderWithProviders(); + renderWithProviders(); const fetchButton = screen.getByTitle("Fetch data"); expect(fetchButton).toBeInTheDocument(); @@ -417,7 +413,7 @@ describe("refetch button", () => { it("should show Fetching state and keep table data visible during refetch", () => { mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { isFetching: true })); - renderWithProviders(); + renderWithProviders(); expect(screen.getByText("Fetching")).toBeInTheDocument(); expect(screen.getByTitle("Fetch data")).toBeDisabled(); @@ -429,7 +425,7 @@ describe("refetch button", () => { const mockRefetch = vi.fn(); mockUseKeys.mockReturnValue(keysResult([mockKey], {}, { refetch: mockRefetch })); - renderWithProviders(); + renderWithProviders(); fireEvent.click(screen.getByTitle("Fetch data")); @@ -439,7 +435,7 @@ describe("refetch button", () => { it("should show Fetch button enabled on error so user can retry", () => { mockUseKeys.mockReturnValue(keysResult([], {}, { data: null, isError: true })); - renderWithProviders(); + renderWithProviders(); const fetchButton = screen.getByTitle("Fetch data"); expect(fetchButton).not.toBeDisabled(); @@ -451,7 +447,7 @@ describe("Status column reflects key.blocked / scim_blocked metadata", () => { it("should render Active for a non-blocked key", async () => { mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: false, metadata: {} }])); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByTestId(`key-status-${mockKey.token_id}`)).toHaveTextContent("Active"); @@ -461,7 +457,7 @@ describe("Status column reflects key.blocked / scim_blocked metadata", () => { it("should render Blocked when key.blocked is true", async () => { mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: true, metadata: {} }])); - renderWithProviders(); + renderWithProviders(); await waitFor(() => { expect(screen.getByTestId(`key-status-${mockKey.token_id}`)).toHaveTextContent("Blocked"); @@ -472,7 +468,7 @@ describe("Status column reflects key.blocked / scim_blocked metadata", () => { it("should mark a SCIM-blocked key with the SCIM tooltip reason", async () => { mockUseKeys.mockReturnValue(keysResult([{ ...mockKey, blocked: true, metadata: { scim_blocked: true } }])); - renderWithProviders(); + renderWithProviders(); 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.tsx index b5401d1f2a01..bc3ae3afd48a 100644 --- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx +++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx @@ -1,9 +1,9 @@ "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 { useDebouncedState } from "@tanstack/react-pacer/debouncer"; +import { useDebouncedValue } from "@tanstack/react-pacer/debouncer"; import { formatNumberWithCommas } from "@/utils/dataUtils"; import { ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, SwitchVerticalIcon } from "@heroicons/react/outline"; import { @@ -35,19 +35,8 @@ import { PaginatedKeyAliasSelect } from "../KeyAliasSelect/PaginatedKeyAliasSele 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"; - }; -} - type KeyFilterState = { "Team ID": string; "Organization ID": string; @@ -64,33 +53,31 @@ const DEFAULT_KEY_FILTERS: KeyFilterState = { "Key Hash": "", }; -export function VirtualKeysTable({ teams, organizations, onSortChange, currentSort }: VirtualKeysTableProps) { +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 } = useOrganizations(); - const resolvedOrganizations = fetchedOrganizations ?? organizations ?? []; + const resolvedOrganizations = useMemo(() => fetchedOrganizations ?? [], [fetchedOrganizations]); const [selectedKey, setSelectedKey] = useState(null); - const [sorting, setSorting] = React.useState(() => { - if (currentSort) { - return [ - { - id: currentSort.sortBy, - desc: currentSort.sortOrder === "desc", - }, - ]; - } - return [ - { - id: "created_at", - desc: true, - }, - ]; - }); + const [sorting, setSorting] = React.useState([{ id: "created_at", desc: true }]); const [tablePagination, setTablePagination] = React.useState({ pageIndex: 0, pageSize: 50, }); const [filters, setFilters] = useState(DEFAULT_KEY_FILTERS); - const [debouncedFilters, setDebouncedFilters] = useDebouncedState(filters, { wait: 300 }); + const [debouncedFilters] = useDebouncedValue(filters, { wait: 300 }); const sortBy = sorting.length > 0 ? sorting[0].id : null; const sortOrder = sorting.length > 0 ? (sorting[0].desc ? "desc" : "asc") : null; @@ -102,11 +89,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo isError, refetch, } = useKeys(tablePagination.pageIndex + 1, tablePagination.pageSize, { - teamID: debouncedFilters["Team ID"]?.trim() || undefined, - organizationID: debouncedFilters["Organization ID"]?.trim() || undefined, - selectedKeyAlias: debouncedFilters["Key Alias"]?.trim() || undefined, - userID: debouncedFilters["User ID"]?.trim() || undefined, - keyHash: debouncedFilters["Key Hash"]?.trim() || undefined, + ...toKeyListFilters(debouncedFilters), sortBy: sortBy || undefined, sortOrder: sortOrder || undefined, expand: "user", @@ -121,7 +104,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo enabled: !!accessToken, staleTime: 30000, }); - const allTeams = fetchedTeams && fetchedTeams.length > 0 ? fetchedTeams : teams ?? []; + const allTeams = useMemo(() => 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) @@ -133,21 +116,18 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo }; const handleFilterChange = (newFilters: Record) => { - const nextFilters: KeyFilterState = { + 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"] || "", - }; - setFilters(nextFilters); - setDebouncedFilters(nextFilters); + }); setTablePagination((prev) => ({ ...prev, pageIndex: 0 })); }; const handleFilterReset = () => { setFilters(DEFAULT_KEY_FILTERS); - setDebouncedFilters(DEFAULT_KEY_FILTERS); setTablePagination((prev) => ({ ...prev, pageIndex: 0 })); }; @@ -251,7 +231,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo cell: (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 ( @@ -485,7 +465,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo return `$${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)`; } @@ -605,7 +585,7 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo }, }, ], - [teams, resolvedOrganizations], + [allTeams, resolvedOrganizations], ); const filterOptions: FilterOption[] = [ @@ -677,10 +657,6 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo const newSorting = typeof updaterOrValue === "function" ? updaterOrValue(sorting) : updaterOrValue; setSorting(newSorting); setTablePagination((prev) => ({ ...prev, pageIndex: 0 })); - if (newSorting && newSorting.length > 0) { - const sortState = newSorting[0]; - onSortChange?.(sortState.id, sortState.desc ? "desc" : "asc"); - } }, onPaginationChange: setTablePagination, getCoreRowModel: getCoreRowModel(), @@ -690,18 +666,6 @@ export function VirtualKeysTable({ teams, organizations, onSortChange, currentSo 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); diff --git a/ui/litellm-dashboard/src/components/user_dashboard.test.tsx b/ui/litellm-dashboard/src/components/user_dashboard.test.tsx index 1517fadce2ae..01764613bf51 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.tsx index db262bc84a1d..dc26257b70c7 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>; 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 = ({ setTeams, setKeys, premiumUser, - organizations, addKey, createClicked, autoOpenCreate, @@ -338,7 +336,7 @@ const UserDashboard: React.FC = ({ prefillData={prefillData} /> )} - + From b795979a630219d0f5f7ea542b9f1b1bb0f5cdb3 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 29 Jun 2026 10:21:26 -0700 Subject: [PATCH 3/5] test(ui): add required last_active to useKeys mock fixtures The KeyResponse type requires last_active, so the typed mockKeys fixtures were missing it. Add it so the file type-checks cleanly. --- .../src/app/(dashboard)/hooks/keys/useKeys.test.ts | 2 ++ 1 file changed, 2 insertions(+) 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.ts index 2c7e3a1af0e2..8c9b33f2c3e1 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, From d94e79cfb531f6c1260a0334a9fb9d54686b081f Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 29 Jun 2026 10:32:46 -0700 Subject: [PATCH 4/5] chore(ui): ratchet lint budgets after virtual-keys refactor Deleting filter_logic.tsx and simplifying VirtualKeysTable lowered the no-explicit-any (2026 to 2016) and complexity (128 to 127) counts, so the eslint-metrics.json baseline was stale and failed the frontend-lint budget gate. Regenerate it, and drop the now-dead filter_logic.tsx suppression entry for the file this PR removed. --- ui/litellm-dashboard/eslint-metrics.json | 4 ++-- ui/litellm-dashboard/eslint-suppressions.json | 14 -------------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/ui/litellm-dashboard/eslint-metrics.json b/ui/litellm-dashboard/eslint-metrics.json index 01c5a2415620..deef1136b431 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.json index 770c953d3f30..5d3a54f9e810 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": 1 From 285e44d17deec7d4099ba47260c026997b3b835e Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 29 Jun 2026 12:23:33 -0700 Subject: [PATCH 5/5] fix(ui): show a loading state for data-backed filter dropdowns The Team ID and Organization ID filters source their options from async hooks (teams / organizations). While that data was still loading the dropdowns rendered 'No results found', so they looked empty rather than loading. Add an opt-in loading flag to FilterOption that the searchable select surfaces as a spinner and a 'Loading...' empty state, and wire it from the teams and organizations query loading states. While loading, the filter no longer caches an empty initial-options list, so the real options appear once the data arrives. --- .../VirtualKeysPage/VirtualKeysTable.tsx | 6 +- .../src/components/molecules/filter.test.tsx | 61 +++++++++++++++++++ .../src/components/molecules/filter.tsx | 8 ++- 3 files changed, 70 insertions(+), 5 deletions(-) diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx index bc3ae3afd48a..0c71c4526ad2 100644 --- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx +++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx @@ -68,7 +68,7 @@ const toKeyListFilters = (filters: KeyFilterState): KeyListFilterOptions => ({ export function VirtualKeysTable() { const { accessToken } = useAuthorized(); - const { data: fetchedOrganizations } = useOrganizations(); + const { data: fetchedOrganizations, isLoading: isOrgsLoading } = useOrganizations(); const resolvedOrganizations = useMemo(() => fetchedOrganizations ?? [], [fetchedOrganizations]); const [selectedKey, setSelectedKey] = useState(null); const [sorting, setSorting] = React.useState([{ id: "created_at", desc: true }]); @@ -98,7 +98,7 @@ export function VirtualKeysTable() { const keyList = useMemo(() => keys?.keys ?? [], [keys]); - const { data: fetchedTeams } = useQuery({ + const { data: fetchedTeams, isLoading: isTeamsLoading } = useQuery({ queryKey: ["allTeamsForKeyFilters", accessToken], queryFn: async () => (accessToken ? await fetchAllTeams(accessToken) : []), enabled: !!accessToken, @@ -593,6 +593,7 @@ export function VirtualKeysTable() { name: "Team ID", label: "Team ID", isSearchable: true, + loading: isTeamsLoading, searchFn: async (searchText: string) => { if (!allTeams || allTeams.length === 0) return []; @@ -612,6 +613,7 @@ export function VirtualKeysTable() { name: "Organization ID", label: "Organization ID", isSearchable: true, + loading: isOrgsLoading, searchFn: async (searchText: string) => { if (!resolvedOrganizations || resolvedOrganizations.length === 0) return []; diff --git a/ui/litellm-dashboard/src/components/molecules/filter.test.tsx b/ui/litellm-dashboard/src/components/molecules/filter.test.tsx index 3a15c5c84f14..d956cd931681 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( + , + ); + + 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( + , + ); + + await user.click(screen.getByRole("button", { name: "Filters" })); + expect(mockSearchFn).not.toHaveBeenCalled(); + + rerender( + , + ); + + 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.tsx index 7086892c32d8..45ad3a6b9cac 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>; options?: Array<{ label: string; value: string }>; customComponent?: React.ComponentType; + loading?: boolean; } interface FilterValues { @@ -74,7 +75,7 @@ const FilterComponent: React.FC = ({ // Load initial options for searchable filters const 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 = ({ {showFilters && (
{options.map((option) => { + const isOptionLoading = searchLoadingMap[option.name] || option.loading; return (
@@ -166,10 +168,10 @@ const FilterComponent: React.FC = ({ } }} 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 ? (