From 5111442dab24d78b50e5a3acda133aae26390a2f Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Wed, 16 Sep 2026 09:25:35 -0700 Subject: [PATCH] fix(ui): address review on logs-tabs url state Keep ?tab=deleted-teams while org memberships load so org admins keep their deep link, stop the hidden Audit Logs panel and failed requests from clamping the page keys, drop an audit_log_id that is not on the settled page, keep the drawer close animation, keep the current page when Deleted Keys/Teams headers are clicked, derive the sort allow-lists from the column definitions and make table sorting controlled only. --- .../DeletedKeysPage/DeletedKeysPage.test.tsx | 78 ++++++- .../DeletedKeysPage/DeletedKeysPage.tsx | 11 +- .../DeletedKeysTable.test.tsx | 11 +- .../DeletedKeysTable/DeletedKeysTable.tsx | 14 +- .../DeletedKeysTableColumns.tsx | 6 +- .../DeletedTeamsPage.test.tsx | 74 ++++-- .../DeletedTeamsPage/DeletedTeamsPage.tsx | 11 +- .../DeletedTeamsTable.test.tsx | 15 +- .../DeletedTeamsTable/DeletedTeamsTable.tsx | 14 +- .../DeletedTeamsTableColumns.tsx | 6 +- .../view_logs/AuditLogsPanel.test.tsx | 220 +++++++++++++++--- .../components/view_logs/AuditLogsPanel.tsx | 17 +- .../src/components/view_logs/index.test.tsx | 81 +++++-- .../src/components/view_logs/index.tsx | 5 +- 14 files changed, 458 insertions(+), 105 deletions(-) diff --git a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.test.tsx b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.test.tsx index dc6888dc13b..d231a522e07 100644 --- a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.test.tsx +++ b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.test.tsx @@ -1,8 +1,10 @@ -import { screen, waitFor, within } from "@testing-library/react"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import type { OnUrlUpdateFunction } from "nuqs/adapters/testing"; +import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing"; +import type { ReactElement } from "react"; import { vi, it, expect, beforeEach, MockedFunction, type Mock } from "vitest"; -import { renderWithProviders } from "../../../tests/test-utils"; +import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils"; import DeletedKeysPage from "./DeletedKeysPage"; import { useDeletedKeys, DeletedKeyResponse } from "@/app/(dashboard)/hooks/keys/useKeys"; @@ -154,6 +156,20 @@ const rowAliases = (aliases: string[]) => const lastUrl = (onUrlUpdate: Mock) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams; +const renderKeepingUrlWrites = (ui: ReactElement, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) => + render( + + {ui} + , + ); + +const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150)); + it("requests the page and page size named by the deleted_keys_ URL keys", () => { renderWithProviders(, { searchParams: { deleted_keys_page: "3", deleted_keys_page_size: "25" } }); @@ -179,6 +195,34 @@ it("writes deleted_keys_page when the next page is requested", async () => { expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(2, 50); }); +it("writes deleted_keys_page_size when the page size changes", async () => { + const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); + mockUseDeletedKeys.mockReturnValue(deletedKeysResult([mockDeletedKey], 120)); + renderWithProviders(, { onUrlUpdate }); + + await chooseSelectOption(user, screen.getByTestId("pagination-page-size"), "100"); + + await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_page_size")).toBe("100")); + expect(lastUrl(onUrlUpdate)?.has("page_size")).toBe(false); + expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(1, 100); +}); + +it("keeps ?deleted_keys_page= when the deleted keys request fails", async () => { + const onUrlUpdate = vi.fn(); + mockUseDeletedKeys.mockReturnValue({ + data: undefined, + isLoading: false, + isError: true, + } as unknown as ReturnType); + renderKeepingUrlWrites(, "?deleted_keys_page=3", onUrlUpdate); + + await flushUrlWrites(); + + expect(onUrlUpdate).not.toHaveBeenCalled(); + expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(3, 50); +}); + it.each([ ["asc", ["cheap-key", "pricey-key"]], ["desc", ["pricey-key", "cheap-key"]], @@ -192,24 +236,36 @@ it.each([ }); it("falls back to deleted_at descending when deleted_keys_sort_by is not a sortable column", () => { - mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 2)); + mockUseDeletedKeys.mockReturnValue(deletedKeysResult([...SORT_KEYS].reverse(), 2)); renderWithProviders(, { searchParams: { deleted_keys_sort_by: "key_alias" } }); expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["cheap-key", "pricey-key"]); }); -it("writes deleted_keys_sort_by and a direction that matches the rendered order when a header is clicked", async () => { +it("writes deleted_keys_sort_by and deleted_keys_sort_order when a sorted header is clicked again", async () => { const user = userEvent.setup(); const onUrlUpdate = vi.fn(); mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 2)); - renderWithProviders(, { onUrlUpdate }); + renderWithProviders(, { searchParams: { deleted_keys_sort_by: "spend" }, onUrlUpdate }); + expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["pricey-key", "cheap-key"]); + + await user.click(screen.getByTestId("sort-header-spend")); + + await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_order")).toBe("asc")); + expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_by")).toBe("spend"); + expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false); + expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["cheap-key", "pricey-key"]); +}); + +it("stays on the current page when a header is clicked, since sorting only reorders the loaded page", async () => { + const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); + mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 120)); + renderWithProviders(, { searchParams: { deleted_keys_page: "3" }, onUrlUpdate }); await user.click(screen.getByTestId("sort-header-spend")); await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_by")).toBe("spend")); - const ascending = lastUrl(onUrlUpdate)?.get("deleted_keys_sort_order") === "asc"; - expect(rowAliases(["cheap-key", "pricey-key"])).toEqual( - ascending ? ["cheap-key", "pricey-key"] : ["pricey-key", "cheap-key"], - ); - expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false); + expect(lastUrl(onUrlUpdate)?.get("deleted_keys_page")).toBe("3"); + expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(3, 50); }); diff --git a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.tsx b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.tsx index b998ef5493e..06ab4a62029 100644 --- a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.tsx +++ b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysPage.tsx @@ -1,4 +1,6 @@ "use client"; +import { useCallback } from "react"; +import { OnChangeFn, SortingState } from "@tanstack/react-table"; import { Info } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/shared/Alert"; import { useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable"; @@ -18,6 +20,13 @@ const TABLE_STATE_OPTIONS: UrlTableStateOptions = { export default function DeletedKeysPage() { const { premiumUser } = useAuthorized(); const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TABLE_STATE_OPTIONS); + const sortLoadedPage = useCallback>( + (updater) => { + onSortingChange(updater); + onPaginationChange(pagination); + }, + [onSortingChange, onPaginationChange, pagination], + ); const { data: keysData, isLoading, isError } = useDeletedKeys(pagination.pageIndex + 1, pagination.pageSize); @@ -38,7 +47,7 @@ export default function DeletedKeysPage() { isLoading={isLoading} isError={isError} sorting={sorting} - onSortingChange={onSortingChange} + onSortingChange={sortLoadedPage} pagination={pagination} onPaginationChange={onPaginationChange} /> diff --git a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.test.tsx b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.test.tsx index 17121dcecd6..61171783198 100644 --- a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.test.tsx +++ b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.test.tsx @@ -1,3 +1,4 @@ +import { functionalUpdate, type SortingState, type Updater } from "@tanstack/react-table"; import { screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { vi, it, expect, beforeEach } from "vitest"; @@ -29,10 +30,14 @@ const makeDeletedKey = (overrides: Partial = {}): DeletedKey ...overrides, }) as DeletedKeyResponse; +const DELETED_AT_DESC: SortingState = [{ id: "deleted_at", desc: true }]; + const defaultProps = { keys: [makeDeletedKey()], totalCount: 1, isLoading: false, + sorting: DELETED_AT_DESC, + onSortingChange: vi.fn(), pagination: { pageIndex: 0, pageSize: 50 }, onPaginationChange: vi.fn(), }; @@ -65,7 +70,7 @@ it("should propagate pagination changes when the next page button is clicked", a expect(defaultProps.onPaginationChange).toHaveBeenCalled(); }); -it("should sort the current page by deleted_at descending by default", () => { +it("sorts the current page by the deleted_at descending sorting it is given", () => { const keys = [ makeDeletedKey({ token: "sk-older", key_alias: "older-key", deleted_at: "2024-01-01T10:00:00Z" }), makeDeletedKey({ token: "sk-newer", key_alias: "newer-key", deleted_at: "2024-06-01T10:00:00Z" }), @@ -107,7 +112,7 @@ it("leaves the default_user_id placeholder unlinked", () => { it("sorts by the controlled sorting prop and reports header clicks through onSortingChange", async () => { const user = userEvent.setup(); - const onSortingChange = vi.fn(); + const onSortingChange = vi.fn<(updater: Updater) => void>(); const keys = [ makeDeletedKey({ token: "sk-cheap", key_alias: "cheap-key", spend: 1 }), makeDeletedKey({ token: "sk-pricey", key_alias: "pricey-key", spend: 9 }), @@ -129,4 +134,6 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor await user.click(screen.getByTestId("sort-header-deleted_at")); expect(onSortingChange).toHaveBeenCalledTimes(1); + const [next] = functionalUpdate(onSortingChange.mock.calls[0][0], [{ id: "spend", desc: true }]); + expect(next?.id).toBe("deleted_at"); }); diff --git a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.tsx b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.tsx index c8b1880de7a..6c302f0baa4 100644 --- a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.tsx +++ b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTable.tsx @@ -2,7 +2,7 @@ import { OnChangeFn, PaginationState, SortingState } from "@tanstack/react-table"; import { Inbox } from "lucide-react"; -import { useMemo, useState } from "react"; +import { useMemo } from "react"; import { DataTable } from "@/components/shared/DataTable"; import { DeletedKeyResponse } from "@/app/(dashboard)/hooks/keys/useKeys"; @@ -14,14 +14,12 @@ interface DeletedKeysTableProps { totalCount: number; isLoading: boolean; isError?: boolean; - sorting?: SortingState; - onSortingChange?: OnChangeFn; + sorting: SortingState; + onSortingChange: OnChangeFn; pagination: PaginationState; onPaginationChange: OnChangeFn; } -const DEFAULT_SORTING: SortingState = [{ id: "deleted_at", desc: true }]; - function EmptyState() { return (
@@ -44,8 +42,6 @@ export function DeletedKeysTable({ pagination, onPaginationChange, }: DeletedKeysTableProps) { - const [internalSorting, setInternalSorting] = useState(DEFAULT_SORTING); - const columns = useMemo(() => getDeletedKeysTableColumns(), []); return ( @@ -54,8 +50,8 @@ export function DeletedKeysTable({ columns={columns} getRowId={(key, index) => key.token || String(index)} sortingMode="client" - sorting={sorting ?? internalSorting} - onSortingChange={onSortingChange ?? setInternalSorting} + sorting={sorting} + onSortingChange={onSortingChange} paginationMode="server" pagination={pagination} onPaginationChange={onPaginationChange} diff --git a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTableColumns.tsx b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTableColumns.tsx index 5a8f45ec554..239ec51cde8 100644 --- a/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTableColumns.tsx +++ b/ui/litellm-dashboard/src/components/DeletedKeysPage/DeletedKeysTable/DeletedKeysTableColumns.tsx @@ -29,8 +29,6 @@ function UserLinkCell({ userId }: { userId: string | null | undefined }) { ); } -export const DELETED_KEYS_SORT_FIELDS: readonly string[] = ["spend", "created_at", "deleted_at"]; - export const getDeletedKeysTableColumns = (): ColumnDef[] => [ { id: "token", @@ -142,3 +140,7 @@ export const getDeletedKeysTableColumns = (): ColumnDef[] => cell: ({ row }) => , }, ]; + +export const DELETED_KEYS_SORT_FIELDS: readonly string[] = getDeletedKeysTableColumns().flatMap((column) => + column.enableSorting && column.id ? [column.id] : [], +); diff --git a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.test.tsx b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.test.tsx index c1b4fe0dda8..402243d3ee1 100644 --- a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.test.tsx +++ b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.test.tsx @@ -1,8 +1,10 @@ -import { fireEvent, screen, waitFor, within } from "@testing-library/react"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import type { OnUrlUpdateFunction } from "nuqs/adapters/testing"; +import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing"; +import type { ReactElement } from "react"; import { vi, it, expect, beforeEach, MockedFunction, type Mock } from "vitest"; -import { renderWithProviders } from "../../../tests/test-utils"; +import { renderWithProviders, testQueryClient } from "../../../tests/test-utils"; import DeletedTeamsPage from "./DeletedTeamsPage"; import { useDeletedTeams, DeletedTeam } from "@/app/(dashboard)/hooks/teams/useTeams"; @@ -71,14 +73,15 @@ it("requests the next page from the server when Next is clicked", () => { expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(2, 25); }); -it("offers the shared page sizes and refetches with the selected one", async () => { +it("offers the shared page sizes, refetches with the selected one and writes deleted_teams_page_size", async () => { const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); mockUseDeletedTeams.mockReturnValue({ data: { teams: [mockDeletedTeam], total: 137 }, isLoading: false, } as unknown as ReturnType); - renderWithProviders(); + renderWithProviders(, { onUrlUpdate }); await user.click(screen.getByTestId("pagination-page-size")); const options = await screen.findAllByRole("option"); @@ -87,6 +90,10 @@ it("offers the shared page sizes and refetches with the selected one", async () await user.click(screen.getByRole("option", { name: "100" })); expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(1, 100); + await waitFor(() => + expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("deleted_teams_page_size")).toBe("100"), + ); + expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("page_size")).toBe(false); }); it("should show the enterprise notice for a non-premium user", () => { @@ -131,6 +138,20 @@ const rowAliases = (aliases: string[]) => const lastUrl = (onUrlUpdate: Mock) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams; +const renderKeepingUrlWrites = (ui: ReactElement, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) => + render( + + {ui} + , + ); + +const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150)); + it("requests the page and page size named by the deleted_teams_ URL keys", () => { renderWithProviders(, { searchParams: { deleted_teams_page: "3", deleted_teams_page_size: "50" }, @@ -158,6 +179,21 @@ it("writes deleted_teams_page when the next page is requested", async () => { expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(2, 25); }); +it("keeps ?deleted_teams_page= when the deleted teams request fails", async () => { + const onUrlUpdate = vi.fn(); + mockUseDeletedTeams.mockReturnValue({ + data: undefined, + isLoading: false, + isError: true, + } as unknown as ReturnType); + renderKeepingUrlWrites(, "?deleted_teams_page=3", onUrlUpdate); + + await flushUrlWrites(); + + expect(onUrlUpdate).not.toHaveBeenCalled(); + expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(3, 25); +}); + it.each([ ["asc", ["cheap-team", "pricey-team"]], ["desc", ["pricey-team", "cheap-team"]], @@ -171,24 +207,36 @@ it.each([ }); it("falls back to deleted_at descending when deleted_teams_sort_by is not a sortable column", () => { - mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 2)); + mockUseDeletedTeams.mockReturnValue(deletedTeamsResult([...SORT_TEAMS].reverse(), 2)); renderWithProviders(, { searchParams: { deleted_teams_sort_by: "team_alias" } }); expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["cheap-team", "pricey-team"]); }); -it("writes deleted_teams_sort_by and a direction that matches the rendered order when a header is clicked", async () => { +it("writes deleted_teams_sort_by and deleted_teams_sort_order when a sorted header is clicked again", async () => { const user = userEvent.setup(); const onUrlUpdate = vi.fn(); mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 2)); - renderWithProviders(, { onUrlUpdate }); + renderWithProviders(, { searchParams: { deleted_teams_sort_by: "spend" }, onUrlUpdate }); + expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["pricey-team", "cheap-team"]); + + await user.click(screen.getByTestId("sort-header-spend")); + + await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_order")).toBe("asc")); + expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_by")).toBe("spend"); + expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false); + expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["cheap-team", "pricey-team"]); +}); + +it("stays on the current page when a header is clicked, since sorting only reorders the loaded page", async () => { + const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); + mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 137)); + renderWithProviders(, { searchParams: { deleted_teams_page: "3" }, onUrlUpdate }); await user.click(screen.getByTestId("sort-header-spend")); await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_by")).toBe("spend")); - const ascending = lastUrl(onUrlUpdate)?.get("deleted_teams_sort_order") === "asc"; - expect(rowAliases(["cheap-team", "pricey-team"])).toEqual( - ascending ? ["cheap-team", "pricey-team"] : ["pricey-team", "cheap-team"], - ); - expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false); + expect(lastUrl(onUrlUpdate)?.get("deleted_teams_page")).toBe("3"); + expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(3, 25); }); diff --git a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.tsx b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.tsx index aeae0a8964e..9447a4ff21e 100644 --- a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.tsx +++ b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsPage.tsx @@ -1,4 +1,6 @@ "use client"; +import { useCallback } from "react"; +import { OnChangeFn, SortingState } from "@tanstack/react-table"; import { Info } from "lucide-react"; import { Alert, AlertDescription, AlertTitle } from "@/components/shared/Alert"; import { DEFAULT_PAGE_SIZE_OPTIONS, useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable"; @@ -18,6 +20,13 @@ const TABLE_STATE_OPTIONS: UrlTableStateOptions = { export default function DeletedTeamsPage() { const { premiumUser } = useAuthorized(); const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TABLE_STATE_OPTIONS); + const sortLoadedPage = useCallback>( + (updater) => { + onSortingChange(updater); + onPaginationChange(pagination); + }, + [onSortingChange, onPaginationChange, pagination], + ); const { data: teamsData, isLoading, isError } = useDeletedTeams(pagination.pageIndex + 1, pagination.pageSize); return ( @@ -36,7 +45,7 @@ export default function DeletedTeamsPage() { isLoading={isLoading} isError={isError} sorting={sorting} - onSortingChange={onSortingChange} + onSortingChange={sortLoadedPage} pagination={pagination} onPaginationChange={onPaginationChange} rowCount={teamsData?.total ?? 0} diff --git a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.test.tsx b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.test.tsx index 7a19a8cfbea..3a40d272f07 100644 --- a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.test.tsx +++ b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.test.tsx @@ -1,3 +1,4 @@ +import { functionalUpdate, type SortingState, type Updater } from "@tanstack/react-table"; import { screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { vi, it, expect, beforeEach } from "vitest"; @@ -25,7 +26,11 @@ const makeDeletedTeam = (overrides: Partial = {}): DeletedTeam => ( ...overrides, }); +const DELETED_AT_DESC: SortingState = [{ id: "deleted_at", desc: true }]; + const paginationProps = { + sorting: DELETED_AT_DESC, + onSortingChange: vi.fn(), pagination: { pageIndex: 0, pageSize: 25 }, onPaginationChange: vi.fn(), }; @@ -44,7 +49,7 @@ it("should display team information", () => { expect(screen.getByText("org-1")).toBeInTheDocument(); }); -it("should sort teams by deleted_at descending by default", () => { +it("sorts teams by the deleted_at descending sorting it is given", () => { const teams = [ makeDeletedTeam({ team_id: "team-old", team_alias: "older-team", deleted_at: "2024-01-01T10:00:00Z" }), makeDeletedTeam({ team_id: "team-new", team_alias: "newer-team", deleted_at: "2024-06-01T10:00:00Z" }), @@ -74,6 +79,8 @@ it("renders the shared pagination footer with the server row count", () => { teams={[makeDeletedTeam()]} isLoading={false} rowCount={137} + sorting={DELETED_AT_DESC} + onSortingChange={vi.fn()} pagination={{ pageIndex: 2, pageSize: 50 }} onPaginationChange={vi.fn()} />, @@ -105,7 +112,7 @@ it("leaves the default_user_id placeholder unlinked in the deleted by cell", () it("sorts by the controlled sorting prop and reports header clicks through onSortingChange", async () => { const user = userEvent.setup(); - const onSortingChange = vi.fn(); + const onSortingChange = vi.fn<(updater: Updater) => void>(); const teams = [ makeDeletedTeam({ team_id: "team-cheap", team_alias: "cheap-team", spend: 1 }), makeDeletedTeam({ team_id: "team-pricey", team_alias: "pricey-team", spend: 9 }), @@ -115,9 +122,9 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor teams={teams} isLoading={false} rowCount={2} + {...paginationProps} sorting={[{ id: "spend", desc: true }]} onSortingChange={onSortingChange} - {...paginationProps} />, ); @@ -128,4 +135,6 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor await user.click(screen.getByTestId("sort-header-deleted_at")); expect(onSortingChange).toHaveBeenCalledTimes(1); + const [next] = functionalUpdate(onSortingChange.mock.calls[0][0], [{ id: "spend", desc: true }]); + expect(next?.id).toBe("deleted_at"); }); diff --git a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.tsx b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.tsx index 28e279cbd6c..c0029c7f7b1 100644 --- a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.tsx +++ b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTable.tsx @@ -2,7 +2,7 @@ import { OnChangeFn, PaginationState, SortingState } from "@tanstack/react-table"; import { Inbox } from "lucide-react"; -import { useMemo, useState } from "react"; +import { useMemo } from "react"; import { DataTable } from "@/components/shared/DataTable"; import { DeletedTeam } from "@/app/(dashboard)/hooks/teams/useTeams"; @@ -13,15 +13,13 @@ interface DeletedTeamsTableProps { teams: DeletedTeam[]; isLoading: boolean; isError?: boolean; - sorting?: SortingState; - onSortingChange?: OnChangeFn; + sorting: SortingState; + onSortingChange: OnChangeFn; pagination: PaginationState; onPaginationChange: OnChangeFn; rowCount: number; } -const DEFAULT_SORTING: SortingState = [{ id: "deleted_at", desc: true }]; - function EmptyState() { return (
@@ -44,8 +42,6 @@ export function DeletedTeamsTable({ onPaginationChange, rowCount, }: DeletedTeamsTableProps) { - const [internalSorting, setInternalSorting] = useState(DEFAULT_SORTING); - const columns = useMemo(() => getDeletedTeamsTableColumns(), []); return ( @@ -54,8 +50,8 @@ export function DeletedTeamsTable({ columns={columns} getRowId={(team, index) => team.team_id || String(index)} sortingMode="client" - sorting={sorting ?? internalSorting} - onSortingChange={onSortingChange ?? setInternalSorting} + sorting={sorting} + onSortingChange={onSortingChange} paginationMode="server" pagination={pagination} onPaginationChange={onPaginationChange} diff --git a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTableColumns.tsx b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTableColumns.tsx index c613af4c633..598686f061b 100644 --- a/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTableColumns.tsx +++ b/ui/litellm-dashboard/src/components/DeletedTeamsPage/DeletedTeamsTable/DeletedTeamsTableColumns.tsx @@ -18,8 +18,6 @@ function EntityCell({ value, href }: { value: string | null | undefined; href: s ); } -export const DELETED_TEAMS_SORT_FIELDS: readonly string[] = ["spend", "created_at", "deleted_at"]; - export const getDeletedTeamsTableColumns = (): ColumnDef[] => [ { id: "team_alias", @@ -119,3 +117,7 @@ export const getDeletedTeamsTableColumns = (): ColumnDef[] => [ }, }, ]; + +export const DELETED_TEAMS_SORT_FIELDS: readonly string[] = getDeletedTeamsTableColumns().flatMap((column) => + column.enableSorting && column.id ? [column.id] : [], +); diff --git a/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.test.tsx b/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.test.tsx index 8880cd2d061..326a476644b 100644 --- a/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.test.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.test.tsx @@ -1,6 +1,7 @@ -import { fireEvent, screen, waitFor, within } from "@testing-library/react"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import type { OnUrlUpdateFunction } from "nuqs/adapters/testing"; +import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing"; import { beforeEach, describe, expect, it, type Mock, vi } from "vitest"; import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils"; @@ -58,17 +59,24 @@ const ROWS: AuditLogEntry[] = [ }, ]; -const respondWith = (total: number, rows: AuditLogEntry[] = []) => { - const response = { - audit_logs: rows, - total, - page: 1, - page_size: PAGE_SIZE, - total_pages: Math.ceil(total / PAGE_SIZE), - }; - return vi.mocked(uiAuditLogsCall).mockResolvedValue(response); +const PAGE_TWO_ROW: AuditLogEntry = { + ...ROWS[0], + id: "log-3", + object_id: "key-obj-789", + table_name: "LiteLLM_VerificationToken", }; +const auditLogsResponse = (total: number, rows: AuditLogEntry[] = [], page = 1) => ({ + audit_logs: rows, + total, + page, + page_size: PAGE_SIZE, + total_pages: Math.ceil(total / PAGE_SIZE), +}); + +const respondWith = (total: number, rows: AuditLogEntry[] = []) => + vi.mocked(uiAuditLogsCall).mockResolvedValue(auditLogsResponse(total, rows)); + const lastCall = () => vi.mocked(uiAuditLogsCall).mock.calls.at(-1)?.[0]; const sentIdParams = () => ID_PARAM_KEYS.filter((key) => lastCall()?.params?.[key] !== undefined); const lastUrl = (onUrlUpdate: Mock) => onUrlUpdate.mock.calls.at(-1)?.[0]; @@ -90,11 +98,39 @@ interface UrlOptions { const renderPanel = (urlOptions: UrlOptions = {}) => renderWithProviders(, urlOptions); -const TEXT_FILTERS: { filterId: string; placeholder: string; paramKey: keyof AuditLogsParams }[] = [ - { filterId: "object_id", placeholder: "Enter object ID…", paramKey: "object_id" }, - { filterId: "changed_by", placeholder: "Enter user ID…", paramKey: "changed_by" }, - { filterId: "team_id", placeholder: "Enter team ID…", paramKey: "object_team_id" }, - { filterId: "key_hash", placeholder: "Enter key hash…", paramKey: "object_key_hash" }, +interface UrlHarnessProps { + searchParams: string; + onUrlUpdate: OnUrlUpdateFunction; + isActive?: boolean; +} + +function UrlHarness({ searchParams, onUrlUpdate, isActive = true }: UrlHarnessProps) { + return ( + + + + + + ); +} + +const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150)); + +const TEXT_FILTERS: { filterId: string; placeholder: string; paramKey: keyof AuditLogsParams; urlKey: string }[] = [ + { filterId: "object_id", placeholder: "Enter object ID…", paramKey: "object_id", urlKey: "audit_filter_object_id" }, + { filterId: "changed_by", placeholder: "Enter user ID…", paramKey: "changed_by", urlKey: "audit_filter_changed_by" }, + { filterId: "team_id", placeholder: "Enter team ID…", paramKey: "object_team_id", urlKey: "audit_filter_team" }, + { + filterId: "key_hash", + placeholder: "Enter key hash…", + paramKey: "object_key_hash", + urlKey: "audit_filter_key_hash", + }, ]; const SELECT_FILTERS: { @@ -103,9 +139,29 @@ const SELECT_FILTERS: { option: string; paramKey: keyof AuditLogsParams; value: string; + urlKey: string; }[] = [ - { label: "Action", comboboxIndex: 0, option: "Created", paramKey: "action", value: "created" }, - { label: "Table", comboboxIndex: 1, option: "Teams", paramKey: "table_name", value: "LiteLLM_TeamTable" }, + { + label: "Action", + comboboxIndex: 0, + option: "Created", + paramKey: "action", + value: "created", + urlKey: "audit_filter_action", + }, + { + label: "Table", + comboboxIndex: 1, + option: "Teams", + paramKey: "table_name", + value: "LiteLLM_TeamTable", + urlKey: "audit_filter_table", + }, +]; + +const URL_FILTERS = [ + ...TEXT_FILTERS.map(({ urlKey, paramKey }) => ({ urlKey, paramKey, value: "val-1" })), + ...SELECT_FILTERS.map(({ urlKey, paramKey, value }) => ({ urlKey, paramKey, value })), ]; describe("AuditLogsPanel", () => { @@ -145,24 +201,30 @@ describe("AuditLogsPanel", () => { expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_search")).toBe(false); }); - it.each(TEXT_FILTERS)("maps the $filterId drawer filter to params.$paramKey", async ({ placeholder, paramKey }) => { - const user = userEvent.setup(); - renderPanel(); - await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled()); + it.each(TEXT_FILTERS)( + "maps the $filterId drawer filter to params.$paramKey and ?$urlKey=", + async ({ placeholder, paramKey, urlKey }) => { + const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); + renderPanel({ onUrlUpdate }); + await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled()); - await user.click(screen.getByTestId("datatable-filters-trigger")); - fireEvent.change(await screen.findByPlaceholderText(placeholder), { target: { value: "val-1" } }); - await user.click(screen.getByTestId("filter-drawer-apply")); + await user.click(screen.getByTestId("datatable-filters-trigger")); + fireEvent.change(await screen.findByPlaceholderText(placeholder), { target: { value: "val-1" } }); + await user.click(screen.getByTestId("filter-drawer-apply")); - await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe("val-1")); - expect(sentIdParams()).toEqual([paramKey]); - }); + await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe("val-1")); + expect(sentIdParams()).toEqual([paramKey]); + await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get(urlKey)).toBe("val-1")); + }, + ); it.each(SELECT_FILTERS)( - "maps the $label drawer select to params.$paramKey", - async ({ comboboxIndex, option, paramKey, value }) => { + "maps the $label drawer select to params.$paramKey and ?$urlKey=", + async ({ comboboxIndex, option, paramKey, value, urlKey }) => { const user = userEvent.setup(); - renderPanel(); + const onUrlUpdate = vi.fn(); + renderPanel({ onUrlUpdate }); await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled()); await user.click(screen.getByTestId("datatable-filters-trigger")); @@ -172,6 +234,7 @@ describe("AuditLogsPanel", () => { await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe(value)); expect(sentIdParams()).toEqual([paramKey]); + await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get(urlKey)).toBe(value)); }, ); @@ -204,6 +267,56 @@ describe("AuditLogsPanel", () => { await waitFor(() => expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 2 of 5")); }); + it.each(URL_FILTERS)("sends ?$urlKey= as params.$paramKey", async ({ urlKey, paramKey, value }) => { + renderPanel({ searchParams: { [urlKey]: value } }); + + await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe(value)); + expect(sentIdParams()).toEqual([paramKey]); + }); + + it("writes audit_page_size when the page size changes", async () => { + const user = userEvent.setup(); + const onUrlUpdate = vi.fn(); + respondWith(120); + renderPanel({ onUrlUpdate }); + await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled()); + + await chooseSelectOption(user, screen.getByTestId("pagination-page-size"), "100"); + + await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get("audit_page_size")).toBe("100")); + expect(lastUrl(onUrlUpdate)?.searchParams.has("page_size")).toBe(false); + await waitFor(() => expect(lastCall()?.page_size).toBe(100)); + }); + + it("keeps ?audit_page= while the tab is inactive, then requests that page once it opens", async () => { + const onUrlUpdate = vi.fn(); + respondWith(120); + const { rerender } = render( + , + ); + + await flushUrlWrites(); + expect(onUrlUpdate).not.toHaveBeenCalled(); + expect(uiAuditLogsCall).not.toHaveBeenCalled(); + + rerender(); + + await waitFor(() => expect(lastCall()?.page).toBe(3)); + expect(onUrlUpdate).not.toHaveBeenCalled(); + }); + + it("keeps ?audit_page= when the audit log request fails", async () => { + const onUrlUpdate = vi.fn(); + vi.mocked(uiAuditLogsCall).mockRejectedValue(new Error("audit logs unavailable")); + render(); + + await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled()); + await flushUrlWrites(); + + expect(onUrlUpdate).not.toHaveBeenCalled(); + expect(lastCall()?.page).toBe(3); + }); + it("ignores the unprefixed page, search and filter keys that belong to Request Logs", async () => { renderPanel({ searchParams: { page: "4", search: "nope", filter_team: "other-team" } }); @@ -263,22 +376,61 @@ describe("AuditLogsPanel", () => { describe("detail drawer deep link", () => { it("opens the drawer for ?audit_log_id= when that row is on the loaded page", async () => { + const onUrlUpdate = vi.fn(); respondWith(2, ROWS); - renderPanel({ searchParams: { audit_log_id: "log-2" } }); + render(); const dialog = await screen.findByRole("dialog"); expect(within(dialog).getByText("user-obj-456")).toBeInTheDocument(); expect(within(dialog).queryByText("team-obj-123")).not.toBeInTheDocument(); + await flushUrlWrites(); + expect(onUrlUpdate).not.toHaveBeenCalled(); }); - it("keeps the drawer closed when ?audit_log_id= is not on the loaded page", async () => { + it("keeps the drawer closed and drops ?audit_log_id= when that row is not on the loaded page", async () => { + const onUrlUpdate = vi.fn(); respondWith(2, ROWS); - renderPanel({ searchParams: { audit_log_id: "log-missing" } }); + render(); await screen.findByText("team-obj-123"); + await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled()); + expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_log_id")).toBe(false); + expect(lastUrl(onUrlUpdate)?.searchParams.get("audit_page_size")).toBe("25"); + expect(lastUrl(onUrlUpdate)?.options.history).toBe("replace"); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); + it("drops ?audit_log_id= while the Audit Logs tab is inactive", async () => { + const onUrlUpdate = vi.fn(); + respondWith(2, ROWS); + render(); + + await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled()); + expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_log_id")).toBe(false); + expect(uiAuditLogsCall).not.toHaveBeenCalled(); + }); + + it("waits for the requested page instead of dropping ?audit_log_id= against the previous page's rows", async () => { + const onUrlUpdate = vi.fn(); + const pageTwo = Promise.withResolvers>>(); + vi.mocked(uiAuditLogsCall).mockImplementation(({ page }) => + page === 2 ? pageTwo.promise : Promise.resolve(auditLogsResponse(120, ROWS)), + ); + const { rerender } = render(); + await screen.findByText("team-obj-123"); + + rerender(); + await waitFor(() => expect(lastCall()?.page).toBe(2)); + await flushUrlWrites(); + expect(onUrlUpdate).not.toHaveBeenCalled(); + + pageTwo.resolve(auditLogsResponse(120, [PAGE_TWO_ROW], 2)); + + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByText("key-obj-789")).toBeInTheDocument(); + expect(onUrlUpdate).not.toHaveBeenCalled(); + }); + it("pushes ?audit_log_id= when a row is opened and removes it on close", async () => { const user = userEvent.setup(); const onUrlUpdate = vi.fn(); diff --git a/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.tsx b/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.tsx index 30e8b0e2d18..cb0bbbc2e52 100644 --- a/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/AuditLogsPanel.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { useDebouncedValue } from "@tanstack/react-pacer/debouncer"; import { useQuery, keepPreviousData } from "@tanstack/react-query"; import { ColumnFiltersState } from "@tanstack/react-table"; @@ -107,6 +107,17 @@ export default function AuditLogsPanel({ const rows = query.data?.audit_logs ?? EMPTY_ROWS; const selectedLog = useMemo(() => rows.find((log) => log.id === selectedLogId) ?? null, [rows, selectedLogId]); + const [drawerLog, setDrawerLog] = useState(null); + if (selectedLog !== null && selectedLog !== drawerLog) { + setDrawerLog(selectedLog); + } + + const hasSettledPage = query.isSuccess && !query.isPlaceholderData; + const isSelectionMissing = selectedLogId !== null && selectedLog === null; + const isSelectionStale = isSelectionMissing && (!isActive || hasSettledPage); + useEffect(() => { + if (isSelectionStale) void setSelectedLogId(null, { history: "replace" }); + }, [isSelectionStale, setSelectedLogId]); const handleViewLog = useCallback((log: AuditLogEntry) => void setSelectedLogId(log.id), [setSelectedLogId]); const closeDrawer = useCallback(() => void setSelectedLogId(null), [setSelectedLogId]); @@ -148,7 +159,7 @@ export default function AuditLogsPanel({ - + ); } diff --git a/ui/litellm-dashboard/src/components/view_logs/index.test.tsx b/ui/litellm-dashboard/src/components/view_logs/index.test.tsx index 25de39e826e..8dc04ab65eb 100644 --- a/ui/litellm-dashboard/src/components/view_logs/index.test.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/index.test.tsx @@ -1,5 +1,6 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { render, screen, waitFor } from "@testing-library/react"; +import type { PropsWithChildren } from "react"; import userEvent from "@testing-library/user-event"; import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing"; import { beforeEach, describe, expect, it, type Mock, vi } from "vitest"; @@ -64,23 +65,40 @@ const renderAs = (sessionRole: string, organizations: unknown[] = [], urlOptions return renderWithProviders(, urlOptions); }; -const renderKeepingMountUrlWrites = (sessionRole: string, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) => { +interface OrganizationsResult { + data: unknown[] | undefined; + isLoading?: boolean; +} + +const keepingMountUrlWrites = (searchParams: string, onUrlUpdate: OnUrlUpdateFunction) => + function Providers({ children }: PropsWithChildren) { + return ( + + {children} + + ); + }; + +const renderKeepingMountUrlWrites = ( + sessionRole: string, + searchParams: string, + onUrlUpdate: OnUrlUpdateFunction, + organizations: OrganizationsResult = { data: [] }, +) => { useAuthorizedMock.mockReturnValue({ userId: "user-1", userRole: sessionRole }); - useOrganizationsMock.mockReturnValue({ data: [] }); - return render( - - - - - , - ); + useOrganizationsMock.mockReturnValue(organizations); + return render(, { + wrapper: keepingMountUrlWrites(searchParams, onUrlUpdate), + }); }; +const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150)); + const lastUrl = (onUrlUpdate: Mock) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams; const tabNames = () => screen.getAllByRole("tab").map((tab) => tab.textContent); @@ -279,6 +297,41 @@ describe("SpendLogsTable", () => { expect(screen.getByRole("tab", { name: "Deleted Teams" })).toHaveAttribute("aria-selected", "true"); }); + it("keeps ?tab=deleted-teams while an org admin's memberships load, then lands on it", async () => { + const onUrlUpdate = vi.fn(); + const { rerender } = renderKeepingMountUrlWrites("Internal User", "?tab=deleted-teams", onUrlUpdate, { + data: undefined, + isLoading: true, + }); + + await flushUrlWrites(); + expect(onUrlUpdate).not.toHaveBeenCalled(); + + useOrganizationsMock.mockReturnValue({ data: ORG_ADMIN_MEMBERSHIPS, isLoading: false }); + rerender(); + + expect(screen.getByRole("tab", { name: "Deleted Teams" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByTestId("deleted-teams-page")).toBeInTheDocument(); + await flushUrlWrites(); + expect(onUrlUpdate).not.toHaveBeenCalled(); + }); + + it("clears ?tab=deleted-teams once the memberships load without an org_admin role", async () => { + const onUrlUpdate = vi.fn(); + const { rerender } = renderKeepingMountUrlWrites("Internal User", "?tab=deleted-teams", onUrlUpdate, { + data: undefined, + isLoading: true, + }); + await flushUrlWrites(); + + useOrganizationsMock.mockReturnValue({ data: [], isLoading: false }); + rerender(); + + await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled()); + expect(lastUrl(onUrlUpdate)?.has("tab")).toBe(false); + expect(screen.getByRole("tab", { name: "Request Logs" })).toHaveAttribute("aria-selected", "true"); + }); + it("keeps ?tab=audit-logs while credentials resolve, then lands on it once the admin role is known", async () => { const onUrlUpdate = vi.fn(); useAuthorizedMock.mockReturnValue({ userId: null, userRole: null }); diff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsx index 8fe722ed39d..180788c0cce 100644 --- a/ui/litellm-dashboard/src/components/view_logs/index.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx @@ -1,3 +1,4 @@ +import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations"; import useCan from "@/app/(dashboard)/hooks/useCan"; import { useUrlTab } from "@/hooks/useUrlTab"; import DeletedKeysPage from "../DeletedKeysPage/DeletedKeysPage"; @@ -37,6 +38,7 @@ const tabContentClassName = (tabId: LogsTabId): string => export default function SpendLogsTable({ accessToken, token, userRole, userID, premiumUser }: SpendLogsTableProps) { const canViewAuditLogs = useCan("viewAuditLogs"); const canViewDeletedTeams = useCan("viewDeletedTeams"); + const { isLoading: isOrgMembershipLoading } = useOrganizations(); const tabs: LogsTab[] = [ REQUEST_LOGS_TAB, @@ -44,7 +46,8 @@ export default function SpendLogsTable({ accessToken, token, userRole, userID, p DELETED_KEYS_TAB, ...(canViewDeletedTeams ? [DELETED_TEAMS_TAB] : []), ]; - const visibleSlugs: readonly LogsTabSlug[] = userRole ? tabs.map((tab) => tab.slug) : LOGS_TAB_SLUGS; + const isRoleResolved = Boolean(userRole) && !isOrgMembershipLoading; + const visibleSlugs: readonly LogsTabSlug[] = isRoleResolved ? tabs.map((tab) => tab.slug) : LOGS_TAB_SLUGS; const [activeSlug, setActiveSlug] = useUrlTab(visibleSlugs, REQUEST_LOGS_TAB.slug); if (!accessToken || !token || !userRole || !userID) {