Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(ui): deep-link virtual key detail view via ?key= query param (#34591)

ryan-crabbe-berri21de59b32e5a
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.test.ts
new file mode 100644
index 00000000000..a829d921600
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.test.ts
@@ -0,0 +1,53 @@
+/* @vitest-environment jsdom */
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useKeyDetailRouting } from "./detailNavigation";
+
+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(window.location.search) }));
+
+describe("useKeyDetailRouting", () => {
+ beforeEach(() => {
+ window.history.pushState(null, "", "/api-keys/");
+ });
+
+ it("openKey sets ?key= via history.pushState (no full navigation)", () => {
+ const spy = vi.spyOn(window.history, "pushState");
+ const { result } = renderHook(() => useKeyDetailRouting());
+ act(() => result.current.openKey("88a145505dd6"));
+ expect(spy).toHaveBeenCalledWith(null, "", expect.stringContaining("key=88a145505dd6"));
+ spy.mockRestore();
+ });
+
+ it("openKey preserves unrelated query params like the legacy ?page=", () => {
+ window.history.pushState(null, "", "/?page=api-keys");
+ const spy = vi.spyOn(window.history, "pushState");
+ const { result } = renderHook(() => useKeyDetailRouting());
+ act(() => result.current.openKey("88a145505dd6"));
+ const url = spy.mock.calls.at(-1)?.[2] as string;
+ expect(url).toContain("page=api-keys");
+ expect(url).toContain("key=88a145505dd6");
+ spy.mockRestore();
+ });
+
+ it("close removes only the key param", () => {
+ window.history.pushState(null, "", "/?page=api-keys&key=88a145505dd6");
+ const spy = vi.spyOn(window.history, "pushState");
+ const { result } = renderHook(() => useKeyDetailRouting());
+ act(() => result.current.close());
+ const url = spy.mock.calls.at(-1)?.[2] as string;
+ expect(url).toContain("page=api-keys");
+ expect(url).not.toContain("key=");
+ spy.mockRestore();
+ });
+
+ it("exposes keyId from ?key=", () => {
+ window.history.pushState(null, "", "/api-keys/?key=88a145505dd6");
+ const { result } = renderHook(() => useKeyDetailRouting());
+ expect(result.current.keyId).toBe("88a145505dd6");
+ });
+
+ it("keyId is null when no key param is present", () => {
+ const { result } = renderHook(() => useKeyDetailRouting());
+ expect(result.current.keyId).toBeNull();
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.ts b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.ts
new file mode 100644
index 00000000000..85b3a6e046d
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-keys/detailNavigation.ts
@@ -0,0 +1,32 @@
+import { useSearchParams } from "next/navigation";
+import { useCallback } from "react";
+
+import { navigateWithParams } from "../navigateWithParams";
+
+export interface KeyDetailRouting {
+ keyId: string | null;
+ openKey: (id: string) => void;
+ close: () => void;
+}
+
+export function useKeyDetailRouting(): KeyDetailRouting {
+ const searchParams = useSearchParams();
+
+ const openKey = useCallback((id: string) => {
+ navigateWithParams((params) => {
+ params.set("key", id);
+ });
+ }, []);
+
+ const close = useCallback(() => {
+ navigateWithParams((params) => {
+ params.delete("key");
+ });
+ }, []);
+
+ return {
+ keyId: searchParams?.get("key") ?? null,
+ openKey,
+ close,
+ };
+}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeyInfo.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeyInfo.ts
new file mode 100644
index 00000000000..57950953d74
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeyInfo.ts
@@ -0,0 +1,25 @@
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
+
+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
+import { KeyResponse } from "@/components/key_team_helpers/key_list";
+import { keyInfoV1Call } from "@/components/networking";
+
+import { keyKeys } from "./useKeys";
+
+export function useKeyInfo(keyId: string | null, options?: { enabled?: boolean }): UseQueryResult<KeyResponse> {
+ const { accessToken } = useAuthorized();
+
+ return useQuery<KeyResponse>({
+ queryKey: [...keyKeys.detail(keyId ?? ""), accessToken],
+ queryFn: async () => {
+ if (!accessToken || !keyId) throw new Error("Missing access token or key id");
+ const keyData = await keyInfoV1Call(accessToken, keyId);
+ return {
+ ...keyData["info"],
+ token: keyId,
+ api_key: keyId,
+ };
+ },
+ enabled: Boolean(accessToken && keyId) && (options?.enabled ?? true),
+ });
+}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/detailNavigation.ts b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/detailNavigation.ts
index 5e120e42740..71f8bc82a07 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/detailNavigation.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/detailNavigation.ts
@@ -1,6 +1,8 @@
import { useSearchParams } from "next/navigation";
import { useCallback } from "react";
+import { navigateWithParams } from "../navigateWithParams";
+
export interface ModelDetailRouting {
modelId: string | null;
teamId: string | null;
@@ -9,14 +11,6 @@ export interface ModelDetailRouting {
close: () => void;
}
-function navigateWithParams(mutate: (params: URLSearchParams) => void): void {
- const params = new URLSearchParams(window.location.search);
- mutate(params);
- const qs = params.toString();
- const url = qs ? `${window.location.pathname}?${qs}` : window.location.pathname;
- window.history.pushState(null, "", url);
-}
-
export function useModelDetailRouting(): ModelDetailRouting {
const searchParams = useSearchParams();
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/navigateWithParams.ts b/ui/litellm-dashboard/src/app/(dashboard)/navigateWithParams.ts
new file mode 100644
index 00000000000..c49c73c3578
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/navigateWithParams.ts
@@ -0,0 +1,7 @@
+export function navigateWithParams(mutate: (params: URLSearchParams) => void): void {
+ const params = new URLSearchParams(window.location.search);
+ mutate(params);
+ const qs = params.toString();
+ const url = qs ? `${window.location.pathname}?${qs}` : window.location.pathname;
+ window.history.pushState(null, "", url);
+}
diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx
index 95f45ea199e..708990647c8 100644
--- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx
+++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.test.tsx
@@ -4,9 +4,12 @@ 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 { useKeyInfo } from "@/app/(dashboard)/hooks/keys/useKeyInfo";
import { KeysResponse, useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";
import useTeams from "@/app/(dashboard)/hooks/useTeams";
+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(window.location.search) }));
+
// Resolve debounced values synchronously so an applied filter lands in the useKeys query within the test tick.
vi.mock("@tanstack/react-pacer/debouncer", async () => {
const React = await vi.importActual<typeof import("react")>("react");
@@ -43,6 +46,10 @@ vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({
keyKeys: { lists: () => ["keys", "list"] },
}));
+vi.mock("@/app/(dashboard)/hooks/keys/useKeyInfo", () => ({
+ useKeyInfo: vi.fn(),
+}));
+
vi.mock("@/app/(dashboard)/hooks/useTeams", () => ({
default: vi.fn(),
}));
@@ -59,7 +66,7 @@ vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({
}));
const mockKey: KeyResponse = {
- token: "sk-1234567890abcdef",
+ token: "88a145505dd6e87e2ea166fcef1e4b53948dbdb32af6431dfd05ec06b571ee52",
token_id: "key-1",
key_name: "test-key",
key_alias: "Test Key Alias",
@@ -108,7 +115,7 @@ const mockKey: KeyResponse = {
end_user_rpm_limit: 10,
end_user_max_budget: 10,
last_refreshed_at: Date.now(),
- api_key: "sk-1234567890abcdef",
+ api_key: "88a145505dd6e87e2ea166fcef1e4b53948dbdb32af6431dfd05ec06b571ee52",
user_role: "user",
rpm_limit_per_model: {},
tpm_limit_per_model: {},
@@ -139,6 +146,10 @@ const mockTeam: Team = {
const mockUseKeys = useKeys as MockedFunction<typeof useKeys>;
const mockUseTeams = useTeams as MockedFunction<typeof useTeams>;
+const mockUseKeyInfo = useKeyInfo as MockedFunction<typeof useKeyInfo>;
+
+const keyInfoResult = (data: KeyResponse | undefined, isError = false) =>
+ ({ data, isError }) as ReturnType<typeof useKeyInfo>;
const keysResult = (keys: KeyResponse[], data: Partial<KeysResponse> = {}, extra: Record<string, unknown> = {}) =>
({
@@ -161,7 +172,10 @@ const openFilters = () => fireEvent.click(screen.getByRole("button", { name: "Fi
beforeEach(() => {
vi.clearAllMocks();
+ window.history.pushState(null, "", "/");
+
mockUseKeys.mockReturnValue(keysResult([mockKey]));
+ mockUseKeyInfo.mockReturnValue(keyInfoResult(undefined));
mockUseTeams.mockReturnValue({
teams: [mockTeam],
@@ -344,24 +358,69 @@ it("sorts by spend ascending when 'Spend ascending' is chosen from the Spend / B
});
});
-it("should open KeyInfoView when clicking the key cell", async () => {
+it("clicking the key cell deep-links via ?key=", async () => {
renderWithProviders(<VirtualKeysTable />);
await waitFor(() => {
expect(screen.getByText("Test Key Alias")).toBeInTheDocument();
});
- expect(screen.getByTestId("pagination-range")).toBeInTheDocument();
-
fireEvent.click(screen.getByText("Test Key Alias"));
+ expect(window.location.search).toContain(`key=${encodeURIComponent(mockKey.token)}`);
+});
+
+it("renders KeyInfoView when the URL has ?key= for a key on the current page, without refetching it", async () => {
+ window.history.pushState(null, "", `/?key=${encodeURIComponent(mockKey.token)}`);
+
+ renderWithProviders(<VirtualKeysTable />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Back to Keys")).toBeInTheDocument();
+ });
+ expect(screen.queryByTestId("pagination-range")).not.toBeInTheDocument();
+ expect(mockUseKeyInfo).toHaveBeenLastCalledWith(mockKey.token, { enabled: false });
+
+ fireEvent.click(screen.getByText("Back to Keys"));
+
+ expect(window.location.search).not.toContain("key=");
+});
+
+it("fetches the key by id when the URL has ?key= for a key not in the loaded page", async () => {
+ window.history.pushState(null, "", "/?key=other-key-hash");
+ mockUseKeyInfo.mockReturnValue(
+ keyInfoResult({ ...mockKey, token: "other-key-hash", key_alias: "Fetched Key Alias" }),
+ );
+
+ renderWithProviders(<VirtualKeysTable />);
+
await waitFor(() => {
expect(screen.getByText("Back to Keys")).toBeInTheDocument();
});
+ expect(mockUseKeyInfo).toHaveBeenLastCalledWith("other-key-hash", { enabled: true });
+ expect(screen.getAllByText("Fetched Key Alias").length).toBeGreaterThan(0);
+});
+it("shows a loading state while a deep-linked key is being fetched", () => {
+ window.history.pushState(null, "", "/?key=other-key-hash");
+
+ renderWithProviders(<VirtualKeysTable />);
+
+ expect(screen.getByText("Loading key...")).toBeInTheDocument();
expect(screen.queryByTestId("pagination-range")).not.toBeInTheDocument();
});
+it("shows 'Key not found' when the deep-linked key fails to load", async () => {
+ window.history.pushState(null, "", "/?key=missing-key-hash");
+ mockUseKeyInfo.mockReturnValue(keyInfoResult(undefined, true));
+
+ renderWithProviders(<VirtualKeysTable />);
+
+ await waitFor(() => {
+ expect(screen.getByText("Key not found")).toBeInTheDocument();
+ });
+});
+
it("should display 'Default Proxy Admin' for user_id when value is 'default_user_id'", async () => {
mockUseKeys.mockReturnValue(
keysResult([
diff --git a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx
index fe929dc0179..eb96136ed6b 100644
--- a/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx
+++ b/ui/litellm-dashboard/src/components/VirtualKeysPage/VirtualKeysTable.tsx
@@ -1,5 +1,7 @@
"use client";
+import { useKeyDetailRouting } from "@/app/(dashboard)/api-keys/detailNavigation";
+import { useKeyInfo } from "@/app/(dashboard)/hooks/keys/useKeyInfo";
import { useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";
import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
import { useAllTeams } from "@/app/(dashboard)/hooks/teams/useTeams";
@@ -18,7 +20,7 @@ import { ColumnFiltersState, OnChangeFn, PaginationState, SortingState } from "@
import { KeyRound } from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
-import { KeyResponse, Team } from "../key_team_helpers/key_list";
+import { Team } from "../key_team_helpers/key_list";
import KeyInfoView from "../templates/key_info_view";
import { getKeyTableColumns, KEY_TABLE_HIDDEN_COLUMNS } from "./keyTableColumns";
@@ -47,7 +49,7 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
const { data: fetchedTeams } = useAllTeams();
const allTeams = useMemo<Team[]>(() => fetchedTeams ?? [], [fetchedTeams]);
- const [selectedKey, setSelectedKey] = useState<KeyResponse | null>(null);
+ const { keyId: selectedKeyId, openKey, close: closeKeyDetail } = useKeyDetailRouting();
const [sorting, setSorting] = useState<SortingState>(DEFAULT_SORTING);
const [tablePagination, setTablePagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 50 });
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
@@ -103,9 +105,18 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
}, []);
const columns = useMemo(
- () => getKeyTableColumns({ allTeams, organizations, onSelectKey: setSelectedKey }),
- [allTeams, organizations],
+ () => getKeyTableColumns({ allTeams, organizations, onSelectKey: (key) => openKey(key.token) }),
+ [allTeams, organizations, openKey],
+ );
+
+ const selectedKeyFromList = useMemo(
+ () => keyList.find((key) => key.token === selectedKeyId),
+ [keyList, selectedKeyId],
);
+ const { data: fetchedSelectedKey, isError: selectedKeyLoadFailed } = useKeyInfo(selectedKeyId, {
+ enabled: !selectedKeyFromList,
+ });
+ const selectedKey = selectedKeyFromList ?? fetchedSelectedKey;
const teamOptions = useMemo(
() =>
@@ -142,12 +153,15 @@ export function VirtualKeysTable({ headerActions }: VirtualKeysTableProps) {
[allTeams, organizations],
);
- if (selectedKey) {
+ if (selectedKeyId) {
+ if (!selectedKey && !selectedKeyLoadFailed) {
+ return <div className="p-4 text-sm text-muted-foreground">Loading key...</div>;
+ }
return (
<div className="w-full h-full overflow-hidden">
<KeyInfoView
- keyId={selectedKey.token}
- onClose={() => setSelectedKey(null)}
+ keyId={selectedKeyId}
+ onClose={closeKeyDetail}
keyData={selectedKey}
teams={allTeams}
onDelete={refetch}