From 0274a777170ec7bd2968eacac6aa52f4f3ff2089 Mon Sep 17 00:00:00 2001 From: mrinal Date: Thu, 10 Sep 2026 13:44:56 +0000 Subject: [PATCH] feat(ui): add "Since last budget reset" range to usage page picker Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../usage/_components/budgetWindow.test.ts | 35 +++++++ .../usage/_components/budgetWindow.ts | 48 ++++++++++ .../components/UsagePageView.test.tsx | 91 ++++++++++++++++++- .../_components/components/UsagePageView.tsx | 26 +++++- .../shared/advanced_date_picker.test.tsx | 40 ++++++++ .../shared/advanced_date_picker.tsx | 15 ++- 6 files changed, 246 insertions(+), 9 deletions(-) create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.test.ts create mode 100644 ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.ts diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.test.ts new file mode 100644 index 00000000000..870340e92cb --- /dev/null +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { lastBudgetResetAt } from "./budgetWindow"; + +describe("lastBudgetResetAt", () => { + it.each([ + [null, "30d"], + [undefined, "30d"], + ["2026-10-01T00:00:00Z", null], + ["2026-10-01T00:00:00Z", undefined], + ])("returns null for missing inputs", (budgetResetAt, budgetDuration) => { + expect(lastBudgetResetAt(budgetResetAt, budgetDuration)).toBeNull(); + }); + + it("returns null for an invalid reset date", () => { + expect(lastBudgetResetAt("not-a-date", "30d")).toBeNull(); + }); + + it("returns null for an unknown duration", () => { + expect(lastBudgetResetAt("2026-10-01T00:00:00Z", "abc")).toBeNull(); + }); + + it.each([ + ["30d", "2026-09-01T00:00:00.000Z"], + ["1mo", "2026-09-01T00:00:00.000Z"], + ["monthly", "2026-09-01T00:00:00.000Z"], + ["7d", "2026-09-24T00:00:00.000Z"], + ["weekly", "2026-09-24T00:00:00.000Z"], + ["1d", "2026-09-30T00:00:00.000Z"], + ["daily", "2026-09-30T00:00:00.000Z"], + ["12h", "2026-09-30T12:00:00.000Z"], + ["45m", "2026-09-30T23:15:00.000Z"], + ])("subtracts the current budget period for %s", (budgetDuration, expected) => { + expect(lastBudgetResetAt("2026-10-01T00:00:00Z", budgetDuration)?.toISOString()).toBe(expected); + }); +}); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.ts b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.ts new file mode 100644 index 00000000000..3736638db0e --- /dev/null +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/budgetWindow.ts @@ -0,0 +1,48 @@ +import moment from "moment"; + +const budgetDurationAliases: Readonly> = { + hourly: "1h", + daily: "24h", + weekly: "7d", + monthly: "30d", +}; + +export const lastBudgetResetAt = ( + budgetResetAt: string | null | undefined, + budgetDuration: string | null | undefined, +): Date | null => { + if (!budgetResetAt || !budgetDuration) return null; + + const resetAt = moment(budgetResetAt); + if (!resetAt.isValid()) return null; + + const normalizedDuration = budgetDuration.trim().toLowerCase(); + const duration = budgetDurationAliases[normalizedDuration] ?? normalizedDuration; + const match = /^(\d+)(mo|[smhdw])$/.exec(duration); + if (!match) return null; + + const value = Number(match[1]); + const unit = match[2]; + + if (unit === "mo" || (unit === "d" && value === 30)) { + return resetAt.subtract(1, "month").toDate(); + } + + if (unit === "w") { + return resetAt.subtract(value * 7, "days").toDate(); + } + + if (unit === "d") { + return resetAt.subtract(value, "days").toDate(); + } + + if (unit === "h") { + return resetAt.subtract(value, "hours").toDate(); + } + + if (unit === "m") { + return resetAt.subtract(value, "minutes").toDate(); + } + + return resetAt.subtract(value, "seconds").toDate(); +}; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx index 7702488f5bf..5fee527b768 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx @@ -77,6 +77,7 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => { "data-testid": "usage-view-select", }, React.createElement("option", { value: "global" }, "Global Usage"), + React.createElement("option", { value: "my-usage" }, "Your Usage"), React.createElement("option", { value: "team" }, "Team Usage"), React.createElement("option", { value: "organization" }, "Organization Usage"), React.createElement("option", { value: "customer" }, "Customer Usage"), @@ -92,9 +93,13 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => { vi.mock("@/components/shared/advanced_date_picker", async () => { const React = await import("react"); - // The button is how a test drives a range change; the real picker's own UI is - // not what any test here is asserting on. - const AdvancedDatePicker = ({ onValueChange }: { onValueChange?: (value: unknown) => void }) => + const AdvancedDatePicker = ({ + onValueChange, + additionalOptions = [], + }: { + onValueChange?: (value: unknown) => void; + additionalOptions?: readonly { label: string; getValue: () => unknown }[]; + }) => React.createElement( "div", { "data-testid": "advanced-date-picker" }, @@ -108,6 +113,17 @@ vi.mock("@/components/shared/advanced_date_picker", async () => { }, "pick", ), + ...additionalOptions.map((option) => + React.createElement( + "button", + { + key: option.label, + type: "button", + onClick: () => onValueChange?.(option.getValue()), + }, + option.label, + ), + ), ); AdvancedDatePicker.displayName = "AdvancedDatePicker"; return { default: AdvancedDatePicker }; @@ -369,6 +385,8 @@ describe("UsagePage", () => { data: { user_id: "user-123", max_budget: null, + budget_duration: null, + budget_reset_at: null, }, isLoading: false, error: null, @@ -586,6 +604,73 @@ describe("UsagePage", () => { }); }); + it("shows the last budget reset option in my usage view", async () => { + mockUseCurrentUser.mockReturnValue({ + data: { + user_id: "user-123", + max_budget: null, + budget_duration: "30d", + budget_reset_at: "2026-10-01T00:00:00Z", + }, + isLoading: false, + error: null, + } as any); + + renderWithProviders(); + + fireEvent.change(screen.getByTestId("usage-view-select"), { target: { value: "my-usage" } }); + + expect(await screen.findByRole("button", { name: "Since last budget reset" })).toBeInTheDocument(); + }); + + it("shows the last budget reset option for non-admin users", async () => { + mockUseAuthorized.mockReturnValue({ + isLoading: false, + isAuthorized: true, + token: "mock-token", + accessToken: "test-token", + userId: "user-123", + userEmail: "test@example.com", + userRole: "Internal User", + premiumUser: false, + disabledPersonalKeyCreation: false, + showSSOBanner: false, + } as any); + mockUseCurrentUser.mockReturnValue({ + data: { + user_id: "user-123", + max_budget: null, + budget_duration: "30d", + budget_reset_at: "2026-10-01T00:00:00Z", + }, + isLoading: false, + error: null, + } as any); + + renderWithProviders(); + + expect(await screen.findByRole("button", { name: "Since last budget reset" })).toBeInTheDocument(); + }); + + it("does not show the last budget reset option without a budget duration", async () => { + mockUseCurrentUser.mockReturnValue({ + data: { + user_id: "user-123", + max_budget: null, + budget_duration: null, + budget_reset_at: "2026-10-01T00:00:00Z", + }, + isLoading: false, + error: null, + } as any); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.queryByRole("button", { name: "Since last budget reset" })).not.toBeInTheDocument(); + }); + }); + it("should withhold the tag list until it resolves so no empty state is shown while loading", async () => { let resolveTagList: (tags: Record) => void = () => {}; mockTagListCall.mockReturnValue( diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx index a92d1209567..7e4e46b6fc9 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx @@ -7,6 +7,7 @@ */ import { ChevronDown, ChevronRight, Download, Info, Sparkles, X } from "lucide-react"; +import moment from "moment"; import type { DateRangePickerValue } from "@/components/shared/date_picker_types"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -39,6 +40,7 @@ import { userDailyActivityCall, } from "@/components/networking"; import AdvancedDatePicker from "@/components/shared/advanced_date_picker"; +import type { RelativeTimeOption } from "@/components/shared/advanced_date_picker"; import { ChartLoader } from "@/components/shared/chart_loader"; import { Tag } from "@/components/tag_management/types"; import UserAgentActivity from "@/components/user_agent_activity"; @@ -64,6 +66,7 @@ import { TOP_MODEL_LIMITS } from "./EntityUsage/TopModelView"; import TopKeyView from "@/components/UsagePage/components/EntityUsage/TopKeyView"; import UsageAIChatPanel from "./UsageAIChatPanel"; import { UsageOption, UsageViewSelect } from "./UsageViewSelect/UsageViewSelect"; +import { lastBudgetResetAt } from "../budgetWindow"; interface UsagePageProps { teams: Team[]; @@ -137,6 +140,23 @@ const UsagePage: React.FC = ({ teams, organizations }) => { // For non-admins or "my-usage" view, always pass their own user_id const effectiveUserId = usageView === "my-usage" || !isAdmin ? userID || null : selectedUserId; + const budgetWindowOptions = useMemo(() => { + if (!(usageView === "my-usage" || !isAdmin)) return []; + + const lastReset = lastBudgetResetAt(currentUser?.budget_reset_at, currentUser?.budget_duration); + if (!lastReset) return []; + + return [ + { + label: "Since last budget reset", + shortLabel: "budget", + getValue: () => ({ + from: lastReset, + to: moment().endOf("day").toDate(), + }), + }, + ]; + }, [currentUser?.budget_duration, currentUser?.budget_reset_at, isAdmin, usageView]); const startTime = useMemo(() => (dateValue.from ? new Date(dateValue.from) : null), [dateValue.from]); const endTime = useMemo(() => (dateValue.to ? new Date(dateValue.to) : null), [dateValue.to]); @@ -483,7 +503,11 @@ const UsagePage: React.FC = ({ teams, organizations }) => { canViewTagUsage={canViewTagUsage} isOrgAdmin={isOrgAdmin} /> - + { expect(screen.getByText("Year to date")).toBeInTheDocument(); }); + it("renders and applies additional options after the built-in presets", async () => { + const from = new Date("2025-02-01T00:00:00.000Z"); + const to = new Date("2025-02-28T23:59:59.999Z"); + const user = userEvent.setup(); + const { container } = render( + ({ from, to }), + }, + ]} + />, + ); + + openDropdown(container); + + const presets = container.querySelectorAll('[data-slot="advanced-date-picker-preset"]'); + expect(presets).toHaveLength(6); + expect(screen.getByText("Since last budget reset")).toBeInTheDocument(); + + await user.click(screen.getByText("Since last budget reset")); + await user.click(screen.getByRole("button", { name: "Apply" })); + + await waitFor(() => { + expect(mockOnValueChange).toHaveBeenCalledWith({ from, to }); + }); + }); + + it("renders only the built-in presets without additional options", () => { + const { container } = render(); + + openDropdown(container); + + expect(container.querySelectorAll('[data-slot="advanced-date-picker-preset"]')).toHaveLength(5); + }); + it("anchors the panel to the trigger edge named by align", () => { const { container, unmount } = render( , diff --git a/ui/litellm-dashboard/src/components/shared/advanced_date_picker.tsx b/ui/litellm-dashboard/src/components/shared/advanced_date_picker.tsx index 190e3de4a82..5cd60cd25e6 100644 --- a/ui/litellm-dashboard/src/components/shared/advanced_date_picker.tsx +++ b/ui/litellm-dashboard/src/components/shared/advanced_date_picker.tsx @@ -3,7 +3,9 @@ import { Button } from "@/components/ui/button"; import { cn } from "@/lib/cva.config"; import type { DateRangePickerValue } from "./date_picker_types"; import moment from "moment"; -import React, { useCallback, useEffect, useRef, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +const emptyAdditionalOptions: readonly RelativeTimeOption[] = []; interface AdvancedDatePickerProps { value: DateRangePickerValue; @@ -12,9 +14,10 @@ interface AdvancedDatePickerProps { className?: string; showTimeRange?: boolean; align?: "left" | "right"; + additionalOptions?: readonly RelativeTimeOption[]; } -interface RelativeTimeOption { +export interface RelativeTimeOption { label: string; shortLabel: string; getValue: () => { from: Date; to: Date }; @@ -73,10 +76,12 @@ const AdvancedDatePicker: React.FC = ({ className, showTimeRange = true, align = "right", + additionalOptions = emptyAdditionalOptions, }) => { const [isOpen, setIsOpen] = useState(false); const [tempValue, setTempValue] = useState(value); const [selectedOption, setSelectedOption] = useState(null); + const options = useMemo(() => [...relativeTimeOptions, ...additionalOptions], [additionalOptions]); // Custom date inputs only - removed time inputs const [startDate, setStartDate] = useState(""); @@ -88,7 +93,7 @@ const AdvancedDatePicker: React.FC = ({ const getMatchingOption = useCallback((currentValue: DateRangePickerValue): string | null => { if (!currentValue.from || !currentValue.to) return null; - for (const option of relativeTimeOptions) { + for (const option of options) { const optionRange = option.getValue(); // Compare dates with some tolerance (to account for time differences) @@ -101,7 +106,7 @@ const AdvancedDatePicker: React.FC = ({ } return null; - }, []); + }, [options]); // Update selected option when value changes useEffect(() => { @@ -322,7 +327,7 @@ const AdvancedDatePicker: React.FC = ({ Relative time
- {relativeTimeOptions.map((option) => { + {options.map((option) => { const isSelected = selectedOption === option.shortLabel; return (