From 0bb89fd5590c67e8eb4cc0bd5e38ab13b6282245 Mon Sep 17 00:00:00 2001
From: ryan-crabbe-berri
Date: Wed, 16 Sep 2026 10:27:59 -0700
Subject: [PATCH] feat(ui): persist guardrails state in the URL
The Guardrails page now keeps its tab, table sort and page, detail tab, garden search, card and filters, test playground selection and search, and submission search, status and open submission in query params. Non-admins land on Submitted Guardrails instead of an empty tab strip.
The Guardrails Monitor keeps its date range, overview sort, detail tab and log viewer filter, sample size and open request in the URL. The logs query key now includes the date range so changing it refetches logs. LogViewer takes optional view state and keeps its own state when none is passed, so ToolDetail is unchanged.
---
.../_components/GuardrailDetail.test.tsx | 135 ++++++++++++++++--
.../_components/GuardrailDetail.tsx | 24 ++--
.../GuardrailsMonitorView.test.tsx | 72 +++++++++-
.../_components/GuardrailsMonitorView.tsx | 26 +---
.../_components/GuardrailsOverview.test.tsx | 54 ++++++-
.../_components/GuardrailsOverview.tsx | 53 +++----
.../_components/useGuardrailDetailUrlState.ts | 37 +++++
.../_components/useMonitorDateRange.ts | 54 +++++++
.../GuardrailTestPlayground.test.tsx | 126 ++++++++++++----
.../_components/GuardrailTestPlayground.tsx | 32 +++--
.../_components/GuardrailsPanel.test.tsx | 91 +++++++++++-
.../_components/GuardrailsPanel.tsx | 15 +-
.../_components/TeamGuardrailsTab.test.tsx | 108 +++++++++++++-
.../_components/TeamGuardrailsTab.tsx | 16 +--
.../_components/guardrail_garden.test.tsx | 124 +++++++++++++++-
.../_components/guardrail_garden.tsx | 38 +++--
.../guardrail_garden_detail.test.tsx | 73 +++++++++-
.../_components/guardrail_garden_detail.tsx | 8 +-
.../guardrail_info.characterization.test.tsx | 7 +-
.../_components/guardrail_info.test.tsx | 98 +++++++++++--
.../guardrails/_components/guardrail_info.tsx | 4 +-
.../_components/guardrail_table.test.tsx | 89 +++++++++++-
.../_components/guardrail_table.tsx | 18 ++-
.../_components/useGardenDetailTab.ts | 10 ++
.../_components/useGuardrailDetailTab.ts | 10 ++
.../_components/useTeamGuardrailsUrlState.ts | 24 ++++
.../GuardrailsMonitor/LogViewer.test.tsx | 83 +++++++++++
.../GuardrailsMonitor/LogViewer.tsx | 49 ++++---
.../GuardrailsMonitor/useLogViewerState.ts | 22 +++
29 files changed, 1295 insertions(+), 205 deletions(-)
create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/useGuardrailDetailUrlState.ts
create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/useMonitorDateRange.ts
create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGardenDetailTab.ts
create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGuardrailDetailTab.ts
create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useTeamGuardrailsUrlState.ts
create mode 100644 ui/litellm-dashboard/src/components/GuardrailsMonitor/useLogViewerState.ts
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.test.tsx
index 9f2a4c42228..5e97206d92f 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.test.tsx
@@ -1,8 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import userEvent from "@testing-library/user-event";
-import { render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { UrlUpdateEvent } from "nuqs/adapters/testing";
+import { renderWithProviders, screen, testQueryClient, waitFor } from "@/../tests/test-utils";
import type { GuardrailUsageDetail } from "@/app/(dashboard)/hooks/guardrails/useGuardrailsUsage";
+import type { LogViewerState } from "@/components/GuardrailsMonitor/useLogViewerState";
import { GuardrailDetail } from "./GuardrailDetail";
const mockUseGuardrailsUsageDetail = vi.fn();
@@ -16,7 +17,20 @@ vi.mock("@/components/networking", () => ({
}));
vi.mock("@/components/GuardrailsMonitor/LogViewer", () => ({
- LogViewer: ({ guardrailName }: { guardrailName: string }) => {guardrailName}
,
+ LogViewer: ({ guardrailName, viewState }: { guardrailName: string; viewState?: LogViewerState }) => (
+
+ {guardrailName}
+
+
+
+
+
+ ),
}));
vi.mock("./EvaluationSettingsModal", () => ({
@@ -59,15 +73,19 @@ const defaultProps = {
endDate: "2026-07-24",
};
-function renderDetail(props: Partial = {}) {
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- return render(, {
- wrapper: ({ children }) => {children},
- });
+function renderDetail(
+ props: Partial = {},
+ urlOptions: { searchParams?: string; onUrlUpdate?: (event: UrlUpdateEvent) => void } = {},
+) {
+ return renderWithProviders(, urlOptions);
}
+const lastUrlUpdate = (onUrlUpdate: ReturnType void>>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0];
+
describe("GuardrailDetail", () => {
beforeEach(() => {
+ testQueryClient.clear();
vi.clearAllMocks();
mockUseGuardrailsUsageDetail.mockReturnValue(loaded(detail));
mockGetGuardrailsUsageLogs.mockResolvedValue({ logs: [], total: 0 });
@@ -152,6 +170,19 @@ describe("GuardrailDetail", () => {
expect(screen.getByTestId("log-viewer")).toHaveTextContent("pii-detector");
});
+ it("should request the logs again when the date range changes", async () => {
+ const { rerender } = renderDetail();
+ await waitFor(() => expect(mockGetGuardrailsUsageLogs).toHaveBeenCalledTimes(1));
+
+ rerender();
+
+ await waitFor(() => expect(mockGetGuardrailsUsageLogs).toHaveBeenCalledTimes(2));
+ expect(mockGetGuardrailsUsageLogs).toHaveBeenLastCalledWith(
+ "test-token",
+ expect.objectContaining({ guardrailId: "pii-detector", startDate: "2026-06-01", endDate: "2026-06-15" }),
+ );
+ });
+
it("should keep the evaluation settings modal closed until its button is clicked", async () => {
const user = userEvent.setup();
renderDetail();
@@ -171,4 +202,92 @@ describe("GuardrailDetail", () => {
);
expect(mockGetGuardrailsUsageLogs).not.toHaveBeenCalled();
});
+
+ describe("URL state", () => {
+ it("should select the Logs tab when ?tab=logs", async () => {
+ renderDetail({}, { searchParams: "?tab=logs" });
+
+ expect(await screen.findByRole("tab", { name: "Logs" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "false");
+ });
+
+ it("should write the clicked tab to ?tab= and drop it for the overview", async () => {
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ renderDetail({}, { onUrlUpdate });
+
+ await user.click(await screen.findByRole("tab", { name: "Logs" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("tab")).toBe("logs"));
+
+ await user.click(screen.getByRole("tab", { name: "Overview" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("tab")).toBe(false));
+ expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("should hand the log filter, sample size and open request from the URL to the log viewer", async () => {
+ renderDetail({}, { searchParams: "?tab=logs&log_filter=blocked&log_sample=50&request_id=req-3" });
+
+ const viewer = await screen.findByTestId("log-viewer");
+ expect(viewer).toHaveAttribute("data-filter", "blocked");
+ expect(viewer).toHaveAttribute("data-sample", "50");
+ expect(viewer).toHaveAttribute("data-request", "req-3");
+ });
+
+ it("should fall back to all logs and a sample of 10 for unknown values", async () => {
+ renderDetail({}, { searchParams: "?log_filter=everything&log_sample=7" });
+
+ const viewer = await screen.findByTestId("log-viewer");
+ expect(viewer).toHaveAttribute("data-filter", "all");
+ expect(viewer).toHaveAttribute("data-sample", "10");
+ expect(viewer).toHaveAttribute("data-request", "");
+ });
+
+ it("should write the log viewer's filter, sample size and open request to the URL", async () => {
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ renderDetail({}, { onUrlUpdate });
+
+ await user.click(await screen.findByRole("button", { name: "show blocked" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("log_filter")).toBe("blocked"));
+ expect(screen.getByTestId("log-viewer")).toHaveAttribute("data-filter", "blocked");
+
+ await user.click(screen.getByRole("button", { name: "sample 50" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("log_sample")).toBe("50"));
+
+ await user.click(screen.getByRole("button", { name: "open req-9" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("request_id")).toBe("req-9"));
+ expect(lastUrlUpdate(onUrlUpdate)?.options.history).toBe("push");
+
+ await user.click(screen.getByRole("button", { name: "close request" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("request_id")).toBe(false));
+ expect(lastUrlUpdate(onUrlUpdate)?.options.history).toBe("replace");
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("log_filter")).toBe("blocked");
+ });
+
+ it("should drop the detail tab and log viewer state when going back", async () => {
+ const user = userEvent.setup();
+ const onBack = vi.fn();
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ renderDetail(
+ { onBack },
+ {
+ searchParams:
+ "?guardrail=pii-detector&start_date=2026-07-01&tab=logs&log_filter=blocked&log_sample=100&request_id=req-3",
+ onUrlUpdate,
+ },
+ );
+
+ await user.click(await screen.findByRole("button", { name: /back to overview/i }));
+
+ expect(onBack).toHaveBeenCalledOnce();
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ const update = lastUrlUpdate(onUrlUpdate);
+ for (const key of ["tab", "log_filter", "log_sample", "request_id"]) {
+ expect(update?.searchParams.has(key)).toBe(false);
+ }
+ expect(update?.searchParams.get("guardrail")).toBe("pii-detector");
+ expect(update?.searchParams.get("start_date")).toBe("2026-07-01");
+ expect(update?.options.history).toBe("replace");
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
index 86b596d4bcd..e30e8b6a8f5 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
@@ -13,6 +13,7 @@ import { GuardrailUsageBreakdown } from "./GuardrailUsageBreakdown";
import { LogViewer } from "@/components/GuardrailsMonitor/LogViewer";
import { MetricCard } from "@/components/GuardrailsMonitor/MetricCard";
import type { LogEntry } from "@/components/GuardrailsMonitor/mockData";
+import { useGuardrailDetailUrlState } from "./useGuardrailDetailUrlState";
interface GuardrailDetailProps {
guardrailId: string;
@@ -29,7 +30,7 @@ const STATUS_TONE: Record = {
};
export function GuardrailDetail({ guardrailId, onBack, accessToken = null, startDate, endDate }: GuardrailDetailProps) {
- const [activeTab, setActiveTab] = useState("overview");
+ const { tab: activeTab, setTab: setActiveTab, logViewerState, clear: clearUrlState } = useGuardrailDetailUrlState();
const [evaluationModalOpen, setEvaluationModalOpen] = useState(false);
const [logsPage] = useState(1);
const logsPageSize = 50;
@@ -40,7 +41,7 @@ export function GuardrailDetail({ guardrailId, onBack, accessToken = null, start
error: detailError,
} = useGuardrailsUsageDetail(guardrailId, { accessToken, startDate, endDate });
const { data: logsData, isLoading: logsLoading } = useQuery({
- queryKey: ["guardrails-usage-logs", guardrailId, logsPage, logsPageSize],
+ queryKey: ["guardrails-usage-logs", guardrailId, startDate, endDate, logsPage, logsPageSize],
queryFn: () =>
getGuardrailsUsageLogs(accessToken!, {
guardrailId,
@@ -90,6 +91,11 @@ export function GuardrailDetail({ guardrailId, onBack, accessToken = null, start
avgLatency: undefined as number | undefined,
};
+ const handleBack = () => {
+ clearUrlState();
+ onBack();
+ };
+
if (detailLoading && !detailData) {
return (
@@ -100,7 +106,7 @@ export function GuardrailDetail({ guardrailId, onBack, accessToken = null, start
if (detailError && !detailData) {
return (
-
)}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.test.tsx
index 7be120a4cb7..165d676b47f 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.test.tsx
@@ -1,8 +1,8 @@
-import { type UrlUpdateEvent } from "nuqs/adapters/testing";
+import { NuqsTestingAdapter, type UrlUpdateEvent } from "nuqs/adapters/testing";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import GuardrailsPanel from "./GuardrailsPanel";
import { getGuardrailsList, deleteGuardrailCall } from "@/components/networking";
-import { fireEvent, renderWithProviders, screen, waitFor, within } from "@/../tests/test-utils";
+import { fireEvent, render, renderWithProviders, screen, waitFor, within } from "@/../tests/test-utils";
vi.mock("@/components/networking", () => ({
getGuardrailsList: vi.fn(),
@@ -204,6 +204,23 @@ describe("GuardrailsPanel", () => {
expect(await screen.findByTestId("guardrail-info-view")).toHaveTextContent("test-guardrail-1");
});
+ it("should drop the detail tab together with ?guardrail= when the info view is closed", async () => {
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ renderWithProviders(
, {
+ searchParams: "?tab=guardrails&guardrail=test-guardrail-1&detail_tab=settings",
+ onUrlUpdate,
+ });
+
+ fireEvent.click(await screen.findByRole("button", { name: "Close Guardrail Info" }));
+
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ const lastUpdate = onUrlUpdate.mock.calls.at(-1)![0];
+ expect(lastUpdate.searchParams.has("guardrail")).toBe(false);
+ expect(lastUpdate.searchParams.has("detail_tab")).toBe(false);
+ expect(lastUpdate.searchParams.get("tab")).toBe("guardrails");
+ expect(lastUpdate.options.history).toBe("replace");
+ });
+
it("should clear ?guardrail= by replacing history when the info view is closed", async () => {
const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
renderWithProviders(
, {
@@ -221,3 +238,73 @@ describe("GuardrailsPanel", () => {
});
});
});
+
+describe("GuardrailsPanel tab in the URL", () => {
+ const lastTabUpdate = (onUrlUpdate: ReturnType
void>>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(getGuardrailsList).mockResolvedValue({ guardrails: [] });
+ });
+
+ it("should select the Guardrails tab for an admin when the URL names no tab", () => {
+ renderWithProviders();
+
+ expect(screen.getByRole("tab", { name: "Guardrails" })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("should select the tab named by ?tab=", () => {
+ renderWithProviders(, {
+ searchParams: "?tab=garden",
+ });
+
+ expect(screen.getByRole("tab", { name: "Guardrail Garden" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.getByRole("tab", { name: "Guardrails" })).toHaveAttribute("aria-selected", "false");
+ });
+
+ it("should write the clicked tab to ?tab= and drop it for the default tab", async () => {
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ renderWithProviders(, { onUrlUpdate });
+
+ fireEvent.click(screen.getByRole("tab", { name: "Test Playground" }));
+ await waitFor(() => expect(lastTabUpdate(onUrlUpdate)?.get("tab")).toBe("test"));
+ expect(screen.getByRole("tab", { name: "Test Playground" })).toHaveAttribute("aria-selected", "true");
+
+ fireEvent.click(screen.getByRole("tab", { name: "Submitted Guardrails" }));
+ await waitFor(() => expect(lastTabUpdate(onUrlUpdate)?.get("tab")).toBe("submitted"));
+
+ fireEvent.click(screen.getByRole("tab", { name: "Guardrails" }));
+ await waitFor(() => expect(lastTabUpdate(onUrlUpdate)?.has("tab")).toBe(false));
+ expect(screen.getByRole("tab", { name: "Guardrails" })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("should land a non-admin on Submitted Guardrails when the URL names no tab", () => {
+ renderWithProviders();
+
+ expect(screen.getByRole("tab", { name: "Submitted Guardrails" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.queryByRole("tab", { name: "Guardrails" })).not.toBeInTheDocument();
+ expect(screen.getByText("Mock Team Guardrails Tab")).toBeInTheDocument();
+ });
+
+ it("should send a non-admin with an admin-only ?tab= to Submitted Guardrails and drop the param", async () => {
+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();
+ render(, {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ });
+
+ expect(screen.getByRole("tab", { name: "Submitted Guardrails" })).toHaveAttribute("aria-selected", "true");
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ expect(lastTabUpdate(onUrlUpdate)?.has("tab")).toBe(false);
+ expect(lastTabUpdate(onUrlUpdate)?.get("other")).toBe("1");
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.tsx
index 901e39004f3..85060ac644b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/GuardrailsPanel.tsx
@@ -14,6 +14,7 @@ import { cn } from "@/lib/cva.config";
import AddGuardrailForm from "./add_guardrail_form";
import GuardrailTable from "./guardrail_table";
import { isAdminRole } from "@/utils/roles";
+import { useUrlTab } from "@/hooks/useUrlTab";
import GuardrailInfoView from "./guardrail_info";
import GuardrailTestPlayground from "./GuardrailTestPlayground";
import { toast } from "@/lib/toast";
@@ -23,6 +24,11 @@ import { formatGuardrailMode, getGuardrailLogoAndName } from "./guardrail_info_h
import { CustomCodeModal } from "./custom_code";
import GuardrailGarden from "./guardrail_garden";
import { TeamGuardrailsTab } from "./TeamGuardrailsTab";
+import { GUARDRAIL_DETAIL_TAB_KEY } from "./useGuardrailDetailTab";
+
+const ADMIN_TABS = ["garden", "guardrails", "test", "submitted"] as const;
+type GuardrailsTab = (typeof ADMIN_TABS)[number];
+const MEMBER_TABS: readonly GuardrailsTab[] = ["submitted"];
interface GuardrailsPanelProps {
accessToken: string | null;
@@ -45,7 +51,9 @@ const GuardrailsPanel: React.FC = ({ accessToken, userRole
"guardrail",
parseAsString.withOptions({ history: "push" }),
);
+ const [, setDetailTab] = useQueryState(GUARDRAIL_DETAIL_TAB_KEY);
const isAdmin = userRole ? isAdminRole(userRole) : false;
+ const [activeTab, setActiveTab] = useUrlTab(isAdmin ? ADMIN_TABS : MEMBER_TABS, isAdmin ? "guardrails" : "submitted");
const fetchGuardrails = async () => {
if (!accessToken) {
@@ -69,6 +77,7 @@ const GuardrailsPanel: React.FC = ({ accessToken, userRole
const closeGuardrailDetail = () => {
void setSelectedGuardrailId(null, { history: "replace" });
+ void setDetailTab(null);
};
const handleAddGuardrail = () => {
@@ -133,7 +142,7 @@ const GuardrailsPanel: React.FC = ({ accessToken, userRole
return (
-
+
{isAdmin && (
<>
@@ -143,7 +152,7 @@ const GuardrailsPanel: React.FC = ({ accessToken, userRole
Guardrails
-
+
Test Playground
>
@@ -231,7 +240,7 @@ const GuardrailsPanel: React.FC = ({ accessToken, userRole
/>
-
+
, "userRole"> = {
+ isLoading: false,
+ isAuthorized: true,
token: "test-token",
accessToken: "test-token",
userId: "user-1",
userEmail: "user@example.com",
+ userRoleLabel: "",
+ isViewOnly: false,
premiumUser: false,
disabledPersonalKeyCreation: null,
showSSOBanner: false,
@@ -96,8 +101,8 @@ describe("TeamGuardrailsTab — approve/reject role gate", () => {
expect(screen.getByRole("button", { name: /reject/i })).toBeInTheDocument();
});
- it("hides Approve and Reject buttons when userRole is undefined (defaults to non-admin)", async () => {
- mockUseAuthorized.mockReturnValue({ ...baseAuth, userRole: undefined });
+ it("hides Approve and Reject buttons when the session has no role (defaults to non-admin)", async () => {
+ mockUseAuthorized.mockReturnValue({ ...baseAuth, userRole: "Undefined Role" });
renderWithProviders();
await screen.findByText("test-pending-guardrail");
@@ -140,3 +145,98 @@ describe("TeamGuardrailsTab — approve/reject role gate", () => {
expect(screen.getByLabelText("Remove x-request-id")).toBeInTheDocument();
});
});
+
+describe("TeamGuardrailsTab URL state", () => {
+ const mockUseAuthorized = vi.mocked(useAuthorized);
+ const lastUrlUpdate = (onUrlUpdate: ReturnType>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseAuthorized.mockReturnValue({ ...baseAuth, userRole: "Admin" });
+ vi.mocked(listGuardrailSubmissions).mockResolvedValue({
+ submissions: [pendingSubmission],
+ summary: { total: 1, pending_review: 1, active: 0, rejected: 0 },
+ });
+ });
+
+ it("loads submissions with the search and status from ?sub_q= and ?sub_status=", async () => {
+ renderWithProviders(, {
+ searchParams: "?sub_q=pii&sub_status=pending",
+ });
+
+ expect(screen.getByPlaceholderText("Search guardrails...")).toHaveValue("pii");
+ expect(screen.getByLabelText("Filter by status")).toHaveValue("pending");
+ await waitFor(() =>
+ expect(listGuardrailSubmissions).toHaveBeenCalledWith("test-token", { status: "pending_review", search: "pii" }),
+ );
+ expect(listGuardrailSubmissions).toHaveBeenCalledTimes(1);
+ });
+
+ it("treats an unknown ?sub_status= as all statuses", async () => {
+ renderWithProviders(, { searchParams: "?sub_status=archived" });
+
+ expect(screen.getByLabelText("Filter by status")).toHaveValue("all");
+ await waitFor(() =>
+ expect(listGuardrailSubmissions).toHaveBeenCalledWith("test-token", { status: undefined, search: undefined }),
+ );
+ });
+
+ it("writes the search box to ?sub_q=", async () => {
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, { onUrlUpdate });
+ await screen.findByText("test-pending-guardrail");
+
+ fireEvent.change(screen.getByPlaceholderText("Search guardrails..."), { target: { value: "toxic" } });
+
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("sub_q")).toBe("toxic"));
+ await waitFor(() =>
+ expect(listGuardrailSubmissions).toHaveBeenLastCalledWith("test-token", { status: undefined, search: "toxic" }),
+ );
+ });
+
+ it("writes the status filter to ?sub_status= and removes it for all statuses", async () => {
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, { onUrlUpdate });
+ await screen.findByText("test-pending-guardrail");
+ const statusSelect = screen.getByLabelText("Filter by status");
+
+ fireEvent.change(statusSelect, { target: { value: "rejected" } });
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("sub_status")).toBe("rejected"));
+ await waitFor(() =>
+ expect(listGuardrailSubmissions).toHaveBeenLastCalledWith("test-token", {
+ status: "rejected",
+ search: undefined,
+ }),
+ );
+
+ fireEvent.change(statusSelect, { target: { value: "all" } });
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("sub_status")).toBe(false));
+ });
+
+ it("opens the submission named by ?submission=", async () => {
+ renderWithProviders(, { searchParams: "?submission=guard-1" });
+
+ expect(await screen.findByText("Forward LiteLLM API Key")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Close detail panel" })).toBeInTheDocument();
+ });
+
+ it("pushes ?submission= when a submission is opened and replaces it away when the panel is closed", async () => {
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, {
+ searchParams: "?sub_status=pending",
+ onUrlUpdate,
+ });
+
+ fireEvent.click(await screen.findByRole("button", { name: "Review" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("submission")).toBe("guard-1"));
+ expect(lastUrlUpdate(onUrlUpdate)?.options.history).toBe("push");
+ expect(await screen.findByText("Forward LiteLLM API Key")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Close detail panel" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("submission")).toBe(false));
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("sub_status")).toBe("pending");
+ expect(lastUrlUpdate(onUrlUpdate)?.options.history).toBe("replace");
+ expect(screen.queryByText("Forward LiteLLM API Key")).not.toBeInTheDocument();
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx
index d45cfc3fe7d..c67099ee35f 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/TeamGuardrailsTab.tsx
@@ -40,6 +40,7 @@ import { isValidUrl } from "@/lib/forms/urlValidation";
import { useZodForm } from "@/lib/forms/useZodForm";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
+import { useTeamGuardrailsUrlState } from "./useTeamGuardrailsUrlState";
const GUARDRAIL_MODES = [
{ value: "pre_call", label: "Pre Call" },
@@ -823,10 +824,9 @@ export function TeamGuardrailsTab({ accessToken }: TeamGuardrailsTabProps) {
active: 0,
rejected: 0,
});
- const [search, setSearch] = useState("");
+ const { search, setSearch, statusFilter, setStatusFilter, selectedId, openSubmission, closeSubmission } =
+ useTeamGuardrailsUrlState();
const [searchDebounced] = useDebouncedValue(search, { wait: DEBOUNCE_WAIT_MS });
- const [statusFilter, setStatusFilter] = useState<"all" | GuardrailStatus>("all");
- const [selectedId, setSelectedId] = useState(null);
const [expandedHeaders, setExpandedHeaders] = useState>(new Set());
const [confirmAction, setConfirmAction] = useState<{
id: string;
@@ -956,7 +956,7 @@ export function TeamGuardrailsTab({ accessToken }: TeamGuardrailsTabProps) {
try {
await approveGuardrailSubmission(accessToken, id);
setConfirmAction(null);
- if (selectedId === id) setSelectedId(null);
+ if (selectedId === id) closeSubmission();
await fetchSubmissions();
toast.success("Guardrail approved");
} catch {
@@ -969,7 +969,7 @@ export function TeamGuardrailsTab({ accessToken }: TeamGuardrailsTabProps) {
try {
await rejectGuardrailSubmission(accessToken, id);
setConfirmAction(null);
- if (selectedId === id) setSelectedId(null);
+ if (selectedId === id) closeSubmission();
await fetchSubmissions();
toast.success("Guardrail rejected");
} catch {
@@ -1009,7 +1009,7 @@ export function TeamGuardrailsTab({ accessToken }: TeamGuardrailsTabProps) {
@@ -61,7 +79,7 @@ const GuardrailGarden: React.FC = ({ accessToken, onGuardr
LiteLLM Content Filter
setShowAllLitellm(!showAllLitellm)}
+ onClick={() => void setShowAllLitellm(!showAllLitellm)}
>
{showAllLitellm ? (
<>Show less>
@@ -78,7 +96,7 @@ const GuardrailGarden: React.FC = ({ accessToken, onGuardr
{(showAllLitellm ? litellmCards : litellmCards.slice(0, CARDS_PER_ROW * VISIBLE_ROWS)).map((card) => (
- setSelectedCard(card)} />
+ openCard(card.id)} />
))}
@@ -90,7 +108,7 @@ const GuardrailGarden: React.FC = ({ accessToken, onGuardr
{partnerCards.map((card) => (
- setSelectedCard(card)} />
+ openCard(card.id)} />
))}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.test.tsx
index e17e739267d..e8d0aeeaec8 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.test.tsx
@@ -1,4 +1,6 @@
-import { render, screen } from "@testing-library/react";
+import { render, renderWithProviders, screen, waitFor } from "@/../tests/test-utils";
+import userEvent from "@testing-library/user-event";
+import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { describe, expect, it, vi } from "vitest";
import GuardrailDetailView from "./guardrail_garden_detail";
import type { GuardrailCardInfo } from "./guardrail_garden_data";
@@ -15,8 +17,22 @@ const makeCard = (overrides: Partial = {}): GuardrailCardInfo
...overrides,
});
-const renderDetail = (card: GuardrailCardInfo) =>
- render();
+const evalCardOverrides: Partial = {
+ id: "cf_denied_financial",
+ name: "Denied Financial Advice",
+ category: "litellm",
+ eval: { f1: 97, precision: 98, recall: 96, testCases: 207, latency: "<0.1ms" },
+};
+const cardWithEval = makeCard(evalCardOverrides);
+
+const renderDetail = (card: GuardrailCardInfo, searchParams?: string, onUrlUpdate?: OnUrlUpdateFunction) =>
+ renderWithProviders(
+ ,
+ { searchParams, onUrlUpdate },
+ );
+
+const lastUrlUpdate = (onUrlUpdate: ReturnType>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0];
describe("GuardrailDetailView logo", () => {
it("renders the card logo through the shared Logo component with the bundled src", () => {
@@ -30,3 +46,54 @@ describe("GuardrailDetailView logo", () => {
expect(screen.getByText("B")).toBeInTheDocument();
});
});
+
+describe("GuardrailDetailView tabs", () => {
+ it("shows the overview when the URL names no tab", () => {
+ renderDetail(cardWithEval);
+ expect(screen.getByText("Guardrail Details")).toBeInTheDocument();
+ expect(screen.queryByText("F1 Score")).not.toBeInTheDocument();
+ });
+
+ it("shows the eval results when ?garden_tab=eval", () => {
+ renderDetail(cardWithEval, "?garden_tab=eval");
+ expect(screen.getByText("F1 Score")).toBeInTheDocument();
+ expect(screen.getByText("97%")).toBeInTheDocument();
+ expect(screen.queryByText("Guardrail Details")).not.toBeInTheDocument();
+ });
+
+ it("writes ?garden_tab= when a tab is clicked and removes it when going back to the overview", async () => {
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn();
+ renderDetail(cardWithEval, undefined, onUrlUpdate);
+
+ await user.click(screen.getByText("Eval Results"));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("garden_tab")).toBe("eval"));
+ expect(screen.getByText("F1 Score")).toBeInTheDocument();
+
+ await user.click(screen.getByText("Overview"));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("garden_tab")).toBe(false));
+ expect(screen.getByText("Guardrail Details")).toBeInTheDocument();
+ });
+
+ it("falls back to the overview and drops ?garden_tab=eval for a card without eval results", async () => {
+ const onUrlUpdate = vi.fn();
+ render(, {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ });
+
+ expect(screen.getByText("Guardrail Details")).toBeInTheDocument();
+ expect(screen.queryByText("Eval Results")).not.toBeInTheDocument();
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("garden_tab")).toBe(false);
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("garden_card")).toBe("bedrock");
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.tsx
index dda56a06ab1..ed74d1da71e 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_garden_detail.tsx
@@ -6,6 +6,7 @@ import AddGuardrailForm from "./add_guardrail_form";
import { Logo } from "@/components/molecules/logo/Logo";
import { GUARDRAIL_PRESETS } from "./guardrail_garden_configs";
import { GuardrailCardInfo } from "./guardrail_garden_data";
+import { useGardenDetailTab } from "./useGardenDetailTab";
interface GuardrailDetailViewProps {
card: GuardrailCardInfo;
@@ -16,7 +17,7 @@ interface GuardrailDetailViewProps {
const GuardrailDetailView: React.FC = ({ card, onBack, accessToken, onGuardrailCreated }) => {
const [isAddFormVisible, setIsAddFormVisible] = useState(false);
- const [activeTab, setActiveTab] = useState("overview");
+ const [activeTab, setActiveTab] = useGardenDetailTab(Boolean(card.eval));
const detailRows = [
{ property: "Provider", value: card.category === "litellm" ? "LiteLLM Content Filter" : "Partner Guardrail" },
@@ -38,7 +39,10 @@ const GuardrailDetailView: React.FC = ({ card, onBack,
]
: [];
- const tabs = [{ key: "overview", label: "Overview" }, ...(card.eval ? [{ key: "eval", label: "Eval Results" }] : [])];
+ const tabs = [
+ { key: "overview" as const, label: "Overview" },
+ ...(card.eval ? [{ key: "eval" as const, label: "Eval Results" }] : []),
+ ];
return (
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.characterization.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.characterization.test.tsx
index 5d16e899408..417a6af2dfe 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.characterization.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.characterization.test.tsx
@@ -1,9 +1,9 @@
import * as networking from "@/components/networking";
-import { render, screen, waitFor } from "@testing-library/react";
+import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import GuardrailInfoView from "./guardrail_info";
-import { chooseSelectOption } from "@/../tests/test-utils";
+import { chooseSelectOption, renderWithProviders } from "@/../tests/test-utils";
vi.mock("@/components/networking", () => ({
getGuardrailInfo: vi.fn(),
@@ -83,7 +83,8 @@ const saveChanges = async (user: ReturnType
) => {
await user.click(screen.getByText("Save Changes"));
};
-const renderView = () => render( {}} accessToken="123" isAdmin />);
+const renderView = () =>
+ renderWithProviders( {}} accessToken="123" isAdmin />);
const lastPayload = () => vi.mocked(networking.updateGuardrailCall).mock.calls.at(-1)?.[2];
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.test.tsx
index 836921104ff..090018735a0 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.test.tsx
@@ -1,6 +1,8 @@
import * as networking from "@/components/networking";
import { fireEvent, render, waitFor, within, screen } from "@testing-library/react";
+import { renderWithProviders } from "@/../tests/test-utils";
import userEvent from "@testing-library/user-event";
+import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { afterEach, describe, expect, it, vi } from "vitest";
import GuardrailInfoView from "./guardrail_info";
@@ -65,7 +67,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
// Wait for the loading to complete and data to be rendered
await waitFor(() => {
@@ -103,7 +105,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
expect(await screen.findAllByText("pre_call, post_call (tag-based)")).not.toHaveLength(0);
});
@@ -131,7 +133,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
const logo = await screen.findByAltText("Presidio PII logo");
expect(logo).toHaveAttribute("src", expect.stringContaining("microsoft_azure.svg"));
@@ -161,7 +163,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- const { container } = render(
+ const { container } = renderWithProviders(
{}} accessToken="123" isAdmin={true} />,
);
@@ -212,7 +214,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
await waitFor(() => {
expect(screen.getByText("PII Entity Configuration")).toBeInTheDocument();
@@ -245,7 +247,7 @@ describe("Guardrail Info", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
vi.mocked(networking.updateGuardrailCall).mockResolvedValue({ status: "success" });
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
await waitFor(() => {
expect(screen.getByText("Settings")).toBeInTheDocument();
@@ -331,7 +333,7 @@ describe("Guardrail Info", () => {
});
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
- render( {}} accessToken="123" isAdmin={true} />);
+ renderWithProviders( {}} accessToken="123" isAdmin={true} />);
expect(await screen.findByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tab", { name: "Settings" })).toHaveAttribute("aria-selected", "false");
@@ -355,10 +357,90 @@ describe("Guardrail Info when the guardrail cannot be loaded", () => {
vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
const onClose = vi.fn();
- render();
+ renderWithProviders(
+ ,
+ );
expect(await screen.findByText("Guardrail not found")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /back to guardrails/i }));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
+
+describe("Guardrail Info detail tab in the URL", () => {
+ const loadedGuardrail = {
+ guardrail_id: "123",
+ guardrail_name: "Test Guardrail",
+ litellm_params: { guardrail: "presidio", mode: "pre_call", default_on: true },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ guardrail_definition_location: "database",
+ };
+ const uiSettings = {
+ supported_entities: [],
+ supported_actions: [],
+ pii_entity_categories: [],
+ supported_modes: ["pre_call"],
+ };
+ const mockLoadedGuardrail = () => {
+ vi.mocked(networking.getGuardrailInfo).mockResolvedValue(loadedGuardrail);
+ vi.mocked(networking.getGuardrailUISettings).mockResolvedValue(uiSettings);
+ vi.mocked(networking.getGuardrailProviderSpecificParams).mockResolvedValue({});
+ };
+ const lastUrlUpdate = (onUrlUpdate: ReturnType>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0];
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("selects the Settings tab when ?detail_tab=settings", async () => {
+ mockLoadedGuardrail();
+ renderWithProviders( {}} accessToken="123" isAdmin />, {
+ searchParams: "?detail_tab=settings",
+ });
+
+ expect(await screen.findByRole("tab", { name: "Settings" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "false");
+ });
+
+ it("writes ?detail_tab= when a tab is clicked and removes it for the overview", async () => {
+ mockLoadedGuardrail();
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn();
+ renderWithProviders( {}} accessToken="123" isAdmin />, {
+ onUrlUpdate,
+ });
+
+ await user.click(await screen.findByRole("tab", { name: "Settings" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("detail_tab")).toBe("settings"));
+ expect(screen.getByRole("tab", { name: "Settings" })).toHaveAttribute("aria-selected", "true");
+
+ await user.click(screen.getByRole("tab", { name: "Overview" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("detail_tab")).toBe(false));
+ expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("shows the overview to a non-admin and drops ?detail_tab=settings from the URL", async () => {
+ mockLoadedGuardrail();
+ const onUrlUpdate = vi.fn();
+ render( {}} accessToken="123" isAdmin={false} />, {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ });
+
+ expect(await screen.findByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.queryByRole("tab", { name: "Settings" })).not.toBeInTheDocument();
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("detail_tab")).toBe(false);
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("guardrail")).toBe("123");
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.tsx
index c9162d99934..bd94f8a0bfc 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_info.tsx
@@ -45,6 +45,7 @@ import GuardrailOptionalParams from "./guardrail_optional_params";
import GuardrailProviderFields from "./guardrail_provider_fields";
import PiiConfiguration from "./pii_configuration";
import ToolPermissionRulesEditor, { ToolPermissionConfig } from "./tool_permission/ToolPermissionRulesEditor";
+import { useGuardrailDetailTab } from "./useGuardrailDetailTab";
const DEFAULT_ON_ITEMS = [
{ label: "Yes", value: true },
@@ -70,6 +71,7 @@ const GuardrailInfoView: React.FC = ({ guardrailId, onClose,
const [guardrailProviderSpecificParams, setGuardrailProviderSpecificParams] = useState(null);
const [loading, setLoading] = useState(true);
const [isEditing, setIsEditing] = useState(false);
+ const [detailTab, setDetailTab] = useGuardrailDetailTab(isAdmin);
const form = useForm({ defaultValues: {} });
const [selectedPiiEntities, setSelectedPiiEntities] = useState([]);
const [selectedPiiActions, setSelectedPiiActions] = useState<{ [key: string]: string }>({});
@@ -532,7 +534,7 @@ const GuardrailInfoView: React.FC = ({ guardrailId, onClose,
-
+
Overview
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.test.tsx
index 561a89a191a..6f07fc2e2cd 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.test.tsx
@@ -1,5 +1,6 @@
-import { render, screen } from "@testing-library/react";
+import { renderWithProviders, screen, waitFor } from "@/../tests/test-utils";
import userEvent from "@testing-library/user-event";
+import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { describe, it, expect, vi } from "vitest";
import GuardrailTable from "./guardrail_table";
@@ -24,14 +25,14 @@ const makeGuardrail = (overrides: Partial = {}): Guardrail => ({
describe("GuardrailTable", () => {
it("renders every column header", () => {
- render();
+ renderWithProviders();
for (const header of ["Guardrail ID", "Name", "Provider", "Mode", "Default On", "Created At", "Updated At"]) {
expect(screen.getByText(header)).toBeInTheDocument();
}
});
it("renders the provider logo from the bundled guardrail logo map", () => {
- render();
+ renderWithProviders();
const logo = screen.getByAltText("Presidio PII logo");
expect(logo).toHaveAttribute("src", expect.stringContaining("microsoft_azure.svg"));
});
@@ -40,7 +41,7 @@ describe("GuardrailTable", () => {
const guardrail = makeGuardrail({
litellm_params: { guardrail: "mystery_guard", mode: "pre_call", default_on: false },
});
- render();
+ renderWithProviders();
expect(screen.getByText("mystery_guard")).toBeInTheDocument();
expect(screen.queryByAltText("mystery_guard logo")).not.toBeInTheDocument();
expect(screen.getByText("m")).toBeInTheDocument();
@@ -54,7 +55,7 @@ describe("GuardrailTable", () => {
default_on: true,
},
});
- render();
+ renderWithProviders();
expect(screen.getByText("pre_call, post_call (tag-based)")).toBeInTheDocument();
});
@@ -62,7 +63,7 @@ describe("GuardrailTable", () => {
const user = userEvent.setup();
const onDeleteClick = vi.fn();
const guardrail = makeGuardrail({ guardrail_id: "gr-9", guardrail_name: "Toxicity Filter" });
- render();
+ renderWithProviders();
await user.click(screen.getByTestId("guardrail-actions-gr-9"));
await user.click(await screen.findByTestId("guardrail-action-delete"));
@@ -78,7 +79,7 @@ describe("GuardrailTable", () => {
guardrail_name: "Config Guardrail",
guardrail_definition_location: GuardrailDefinitionLocation.CONFIG,
});
- render();
+ renderWithProviders();
await user.click(screen.getByTestId("guardrail-actions-cfg-1"));
const deleteItem = await screen.findByTestId("guardrail-action-delete");
@@ -86,4 +87,78 @@ describe("GuardrailTable", () => {
expect(deleteItem).toHaveAttribute("data-disabled");
expect(onDeleteClick).not.toHaveBeenCalled();
});
+
+ describe("URL state", () => {
+ const named = [
+ makeGuardrail({ guardrail_id: "gr-b", guardrail_name: "name-bravo", created_at: "2024-03-01" }),
+ makeGuardrail({ guardrail_id: "gr-c", guardrail_name: "name-charlie", created_at: "2024-01-01" }),
+ makeGuardrail({ guardrail_id: "gr-a", guardrail_name: "name-alpha", created_at: "2024-02-01" }),
+ ];
+ const renderedNames = () => screen.getAllByTitle(/^name-/).map((cell) => cell.textContent);
+ const manyGuardrails = Array.from({ length: 30 }, (_, index) =>
+ makeGuardrail({ guardrail_id: `gr-${index}`, guardrail_name: `name-${index}` }),
+ );
+ const lastUrlUpdate = (onUrlUpdate: ReturnType>) =>
+ onUrlUpdate.mock.calls.at(-1)?.[0];
+
+ it("sorts by newest created first when the URL has no sort", () => {
+ renderWithProviders();
+ expect(renderedNames()).toEqual(["name-bravo", "name-alpha", "name-charlie"]);
+ });
+
+ it("sorts by the column and direction in ?sort_by= and ?sort_order=", () => {
+ renderWithProviders(, {
+ searchParams: "?sort_by=guardrail_name&sort_order=asc",
+ });
+ expect(renderedNames()).toEqual(["name-alpha", "name-bravo", "name-charlie"]);
+ });
+
+ it("falls back to the default sort for a column that cannot be sorted", () => {
+ renderWithProviders(, {
+ searchParams: "?sort_by=provider&sort_order=desc",
+ });
+ expect(renderedNames()).toEqual(["name-bravo", "name-alpha", "name-charlie"]);
+ });
+
+ it("writes the clicked sort column and direction to the URL", async () => {
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, { onUrlUpdate });
+
+ await user.click(screen.getByTestId("sort-header-guardrail_name"));
+
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("sort_by")).toBe("guardrail_name"));
+ expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("sort_order")).toBe("asc");
+ expect(renderedNames()).toEqual(["name-alpha", "name-bravo", "name-charlie"]);
+ });
+
+ it("shows the page in ?page= and writes page changes back", async () => {
+ const user = userEvent.setup();
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, {
+ searchParams: "?page=2",
+ onUrlUpdate,
+ });
+
+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 2 of 2");
+ expect(screen.getAllByTitle(/^name-/)).toHaveLength(5);
+
+ await user.click(screen.getByRole("button", { name: "Go to previous page" }));
+
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.has("page")).toBe(false));
+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 1 of 2");
+ expect(screen.getAllByTitle(/^name-/)).toHaveLength(25);
+
+ await user.click(screen.getByRole("button", { name: "Go to next page" }));
+ await waitFor(() => expect(lastUrlUpdate(onUrlUpdate)?.searchParams.get("page")).toBe("2"));
+ });
+
+ it("uses the page size in ?page_size=", () => {
+ renderWithProviders(, {
+ searchParams: "?page_size=50",
+ });
+ expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 1 of 1");
+ expect(screen.getAllByTitle(/^name-/)).toHaveLength(30);
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.tsx b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.tsx
index bbab01e346d..3e36d57ba65 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/guardrail_table.tsx
@@ -1,10 +1,9 @@
"use client";
-import { SortingState } from "@tanstack/react-table";
import { Inbox } from "lucide-react";
-import React, { useMemo, useState } from "react";
+import React, { useMemo } from "react";
-import { DataTable } from "@/components/shared/DataTable";
+import { DataTable, useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable";
import { Guardrail } from "@/components/guardrails/types";
import { getGuardrailTableColumns } from "./guardrailTableColumns";
@@ -16,7 +15,12 @@ interface GuardrailTableProps {
onGuardrailClick: (id: string) => void;
}
-const DEFAULT_SORTING: SortingState = [{ id: "created_at", desc: true }];
+const TABLE_STATE_OPTIONS: UrlTableStateOptions = {
+ sortFields: ["guardrail_id", "guardrail_name", "created_at", "updated_at"],
+ defaultSort: { id: "created_at", desc: true },
+ defaultPageSize: 25,
+ filterColumns: [],
+};
function EmptyState() {
return (
@@ -36,7 +40,7 @@ const GuardrailTable: React.FC = ({
onDeleteClick,
onGuardrailClick,
}) => {
- const [sorting, setSorting] = useState(DEFAULT_SORTING);
+ const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TABLE_STATE_OPTIONS);
const columns = useMemo(
() => getGuardrailTableColumns({ onGuardrailClick, onDeleteClick }),
@@ -47,11 +51,13 @@ const GuardrailTable: React.FC = ({
guardrail.guardrail_id || String(index)}
sortingMode="client"
sorting={sorting}
- onSortingChange={setSorting}
+ onSortingChange={onSortingChange}
isLoading={isLoading}
loadingMessage="Loading guardrails…"
noDataMessage={}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGardenDetailTab.ts b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGardenDetailTab.ts
new file mode 100644
index 00000000000..b8742fc645d
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGardenDetailTab.ts
@@ -0,0 +1,10 @@
+import { useUrlTab } from "@/hooks/useUrlTab";
+
+export const GARDEN_TAB_KEY = "garden_tab";
+
+const GARDEN_TABS_WITH_EVAL = ["overview", "eval"] as const;
+type GardenTab = (typeof GARDEN_TABS_WITH_EVAL)[number];
+const GARDEN_TABS_WITHOUT_EVAL: readonly GardenTab[] = ["overview"];
+
+export const useGardenDetailTab = (hasEval: boolean) =>
+ useUrlTab(hasEval ? GARDEN_TABS_WITH_EVAL : GARDEN_TABS_WITHOUT_EVAL, "overview", GARDEN_TAB_KEY);
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGuardrailDetailTab.ts b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGuardrailDetailTab.ts
new file mode 100644
index 00000000000..0fc77cbb734
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useGuardrailDetailTab.ts
@@ -0,0 +1,10 @@
+import { useUrlTab } from "@/hooks/useUrlTab";
+
+export const GUARDRAIL_DETAIL_TAB_KEY = "detail_tab";
+
+const ADMIN_DETAIL_TABS = ["overview", "settings"] as const;
+type GuardrailDetailTab = (typeof ADMIN_DETAIL_TABS)[number];
+const VIEWER_DETAIL_TABS: readonly GuardrailDetailTab[] = ["overview"];
+
+export const useGuardrailDetailTab = (isAdmin: boolean) =>
+ useUrlTab(isAdmin ? ADMIN_DETAIL_TABS : VIEWER_DETAIL_TABS, "overview", GUARDRAIL_DETAIL_TAB_KEY);
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useTeamGuardrailsUrlState.ts b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useTeamGuardrailsUrlState.ts
new file mode 100644
index 00000000000..de8d957ff09
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails/_components/useTeamGuardrailsUrlState.ts
@@ -0,0 +1,24 @@
+import { parseAsString, parseAsStringLiteral, useQueryState } from "nuqs";
+import { useCallback } from "react";
+
+const STATUS_FILTERS = ["all", "pending", "active", "rejected"] as const;
+
+const searchParser = parseAsString.withDefault("");
+const statusParser = parseAsStringLiteral(STATUS_FILTERS).withDefault("all");
+const submissionParser = parseAsString.withOptions({ history: "push" });
+
+export function useTeamGuardrailsUrlState() {
+ const [search, setSearchParam] = useQueryState("sub_q", searchParser);
+ const [statusFilter, setStatusParam] = useQueryState("sub_status", statusParser);
+ const [selectedId, setSelectedParam] = useQueryState("submission", submissionParser);
+
+ const setSearch = useCallback((value: string) => void setSearchParam(value), [setSearchParam]);
+ const setStatusFilter = useCallback(
+ (value: string) => void setStatusParam(statusParser.parse(value)),
+ [setStatusParam],
+ );
+ const openSubmission = useCallback((id: string) => void setSelectedParam(id), [setSelectedParam]);
+ const closeSubmission = useCallback(() => void setSelectedParam(null, { history: "replace" }), [setSelectedParam]);
+
+ return { search, setSearch, statusFilter, setStatusFilter, selectedId, openSubmission, closeSubmission };
+}
diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
index 083b1e5f3e2..0db477bd0b6 100644
--- a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders, screen, testQueryClient, waitFor, within } from "../../../tests/test-utils";
import type { LogEntry as SpendLogEntry } from "@/components/view_logs/columns";
import { LogViewer } from "./LogViewer";
+import type { LogViewerState } from "./useLogViewerState";
vi.mock("@/components/networking", async (importOriginal) => {
const actual = await importOriginal();
@@ -14,14 +15,17 @@ vi.mock("@/components/networking", async (importOriginal) => {
vi.mock("@/components/view_logs/LogDetailsDrawer", () => ({
LogDetailsDrawer: function LogDetailsDrawerMock({
open,
+ onClose,
logEntry,
}: {
open: boolean;
+ onClose: () => void;
logEntry?: { request_id: string } | null;
}) {
return (
{open ? "open" : "closed"}
+ close drawer
);
},
@@ -108,3 +112,82 @@ describe("GuardrailsMonitor LogViewer not_run rows", () => {
expect(within(row).queryByText("Blocked")).not.toBeInTheDocument();
});
});
+
+describe("GuardrailsMonitor LogViewer view state", () => {
+ const logs = [
+ { id: "log-passed", timestamp: "2026-09-02 09:50:13", action: "passed" as const, input_snippet: "safe prompt" },
+ { id: "log-blocked", timestamp: "2026-09-02 09:51:13", action: "blocked" as const, input_snippet: "bad prompt" },
+ ];
+ const makeViewState = (overrides: Partial = {}): LogViewerState => ({
+ filter: "all",
+ setFilter: vi.fn(),
+ sampleSize: 10,
+ setSampleSize: vi.fn(),
+ requestId: null,
+ setRequestId: vi.fn(),
+ ...overrides,
+ });
+
+ beforeEach(() => {
+ vi.mocked(uiSpendLogsCall).mockReset();
+ vi.mocked(uiSpendLogsCall).mockResolvedValue({ data: [], total: 0 });
+ testQueryClient.clear();
+ });
+
+ it("shows the filter, sample size and open request that the caller passes in", () => {
+ const viewState = makeViewState({ filter: "blocked", sampleSize: 50, requestId: "log-blocked" });
+ renderWithProviders();
+
+ expect(screen.queryByText("safe prompt")).not.toBeInTheDocument();
+ expect(screen.getByText("bad prompt")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "50" })).toHaveClass("bg-primary");
+ expect(screen.getByRole("button", { name: "10" })).not.toHaveClass("bg-primary");
+ expect(screen.getByRole("button", { name: "Blocked" })).toHaveClass("bg-primary");
+ expect(screen.getByTestId("log-details-drawer")).toHaveTextContent("open");
+ expect(vi.mocked(uiSpendLogsCall)).toHaveBeenCalledWith(
+ expect.objectContaining({ params: { request_id: "log-blocked" } }),
+ );
+ });
+
+ it("reports filter, sample size, row and drawer changes to the caller instead of keeping them", async () => {
+ const user = userEvent.setup();
+ const viewState = makeViewState();
+ renderWithProviders();
+
+ await user.click(screen.getByRole("button", { name: "Blocked" }));
+ expect(viewState.setFilter).toHaveBeenCalledWith("blocked");
+ expect(screen.getByText("safe prompt")).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "100" }));
+ expect(viewState.setSampleSize).toHaveBeenCalledWith(100);
+
+ await user.click(screen.getByText("bad prompt"));
+ expect(viewState.setRequestId).toHaveBeenLastCalledWith("log-blocked");
+ expect(screen.getByTestId("log-details-drawer")).toHaveTextContent("closed");
+
+ await user.click(screen.getByRole("button", { name: "close drawer" }));
+ expect(viewState.setRequestId).toHaveBeenLastCalledWith(null);
+ });
+
+ it("keeps its own filter and drawer state when the caller passes none", async () => {
+ const user = userEvent.setup();
+ renderWithProviders();
+
+ await user.click(screen.getByRole("button", { name: "Blocked" }));
+ expect(screen.queryByText("safe prompt")).not.toBeInTheDocument();
+ expect(screen.getByText("bad prompt")).toBeInTheDocument();
+
+ await user.click(screen.getByText("bad prompt"));
+ expect(screen.getByTestId("log-details-drawer")).toHaveTextContent("open");
+
+ await user.click(screen.getByRole("button", { name: "close drawer" }));
+ expect(screen.getByTestId("log-details-drawer")).toHaveTextContent("closed");
+ });
+
+ it("starts on the filter given by filterAction when the caller passes no view state", () => {
+ renderWithProviders();
+
+ expect(screen.getByText("safe prompt")).toBeInTheDocument();
+ expect(screen.queryByText("bad prompt")).not.toBeInTheDocument();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx
index 2abd699ba86..231a027a813 100644
--- a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx
+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx
@@ -1,13 +1,20 @@
import { CircleCheck, ChevronDown, MinusCircle, TriangleAlert, X } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import moment from "moment";
-import React, { useState } from "react";
+import React from "react";
import { Button } from "@/components/ui/button";
import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";
import { uiSpendLogsCall } from "@/components/networking";
import { LogDetailsDrawer } from "@/components/view_logs/LogDetailsDrawer";
import type { LogEntry as ViewLogsLogEntry } from "@/components/view_logs/columns";
import type { LogEntry } from "./mockData";
+import {
+ LOG_FILTERS,
+ LOG_SAMPLE_SIZES,
+ type LogFilter,
+ type LogViewerState,
+ useLocalLogViewerState,
+} from "./useLogViewerState";
const actionConfig: Record<
"blocked" | "passed" | "flagged" | "not_run",
@@ -45,13 +52,14 @@ const actionConfig: Record<
interface LogViewerProps {
guardrailName?: string;
- filterAction?: "all" | "blocked" | "passed" | "flagged";
+ filterAction?: LogFilter;
logs?: LogEntry[];
logsLoading?: boolean;
totalLogs?: number;
accessToken?: string | null;
startDate?: string;
endDate?: string;
+ viewState?: LogViewerState;
}
export function LogViewer({
@@ -63,17 +71,22 @@ export function LogViewer({
accessToken = null,
startDate = "",
endDate = "",
+ viewState,
}: LogViewerProps) {
- const [sampleSize, setSampleSize] = useState(10);
- const [activeFilter, setActiveFilter] = useState(filterAction);
- const [selectedRequestId, setSelectedRequestId] = useState(null);
- const [drawerOpen, setDrawerOpen] = useState(false);
+ const localState = useLocalLogViewerState(filterAction);
+ const {
+ filter: activeFilter,
+ setFilter: setActiveFilter,
+ sampleSize,
+ setSampleSize,
+ requestId: selectedRequestId,
+ setRequestId: setSelectedRequestId,
+ } = viewState ?? localState;
+ const drawerOpen = selectedRequestId !== null;
const filteredLogs = logs.filter((log) => activeFilter === "all" || log.action === activeFilter);
const displayLogs = filteredLogs.slice(0, sampleSize);
const total = totalLogs ?? logs.length;
- const sampleSizes = [10, 50, 100];
- const filters: Array<"all" | "blocked" | "flagged" | "passed"> = ["all", "blocked", "flagged", "passed"];
const startTime = startDate
? moment(startDate).utc().format("YYYY-MM-DD HH:mm:ss")
@@ -96,22 +109,12 @@ export function LogViewer({
});
return res as { data: ViewLogsLogEntry[]; total: number };
},
- enabled: Boolean(accessToken && selectedRequestId && drawerOpen),
+ enabled: Boolean(accessToken && selectedRequestId),
});
const selectedLog: ViewLogsLogEntry | null =
fullLogResponse?.data?.find((log) => log.request_id === selectedRequestId) ?? fullLogResponse?.data?.[0] ?? null;
- const handleLogClick = (log: LogEntry) => {
- setSelectedRequestId(log.id);
- setDrawerOpen(true);
- };
-
- const handleCloseDrawer = () => {
- setDrawerOpen(false);
- setSelectedRequestId(null);
- };
-
return (
@@ -131,7 +134,7 @@ export function LogViewer({
{logs.length > 0 && (
- {filters.map((f) => (
+ {LOG_FILTERS.map((f) => (
Sample:
- {sampleSizes.map((size) => (
+ {LOG_SAMPLE_SIZES.map((size) => (
handleLogClick(log)}
+ onClick={() => setSelectedRequestId(log.id)}
className="w-full text-left px-4 py-3 hover:bg-accent transition-colors flex items-start gap-3"
>
@@ -208,7 +211,7 @@ export function LogViewer({
setSelectedRequestId(null)}
logEntry={selectedLog}
accessToken={accessToken}
allLogs={selectedLog ? [selectedLog] : []}
diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/useLogViewerState.ts b/ui/litellm-dashboard/src/components/GuardrailsMonitor/useLogViewerState.ts
new file mode 100644
index 00000000000..f6a51dc1c61
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/useLogViewerState.ts
@@ -0,0 +1,22 @@
+import { useState } from "react";
+
+export const LOG_FILTERS = ["all", "blocked", "flagged", "passed"] as const;
+export type LogFilter = (typeof LOG_FILTERS)[number];
+export const LOG_SAMPLE_SIZES = [10, 50, 100] as const;
+export type LogSampleSize = (typeof LOG_SAMPLE_SIZES)[number];
+
+export interface LogViewerState {
+ filter: LogFilter;
+ setFilter: (filter: LogFilter) => void;
+ sampleSize: LogSampleSize;
+ setSampleSize: (size: LogSampleSize) => void;
+ requestId: string | null;
+ setRequestId: (requestId: string | null) => void;
+}
+
+export function useLocalLogViewerState(initialFilter: LogFilter): LogViewerState {
+ const [filter, setFilter] = useState(initialFilter);
+ const [sampleSize, setSampleSize] = useState(10);
+ const [requestId, setRequestId] = useState(null);
+ return { filter, setFilter, sampleSize, setSampleSize, requestId, setRequestId };
+}