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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(ui): keep the spend-by-tool legend from overlapping the charts
tin9dbf7c363b6e
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsxindex 125c8dff694..4d1f1c182db 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx@@ -23,8 +23,24 @@ vi.mock("@/components/shared/charts", () => ({DonutChart: ({ data, label }: { data: unknown; label: string }) => (<div data-testid="donut-chart" data-label={label} data-slices={JSON.stringify(data)} />),- BarChart: ({ data, categories }: { data: unknown; categories: string[] }) => (- <div data-testid="bar-chart" data-categories={categories.join(",")} data-series={JSON.stringify(data)} />+ BarChart: ({+ data,+ categories,+ colors,+ showLegend,+ }: {+ data: unknown;+ categories: string[];+ colors?: readonly string[];+ showLegend?: boolean;+ }) => (+ <div+ data-testid="bar-chart"+ data-categories={categories.join(",")}+ data-colors={(colors ?? []).join(",")}+ data-show-legend={String(showLegend ?? true)}+ data-series={JSON.stringify(data)}+ />),CustomLegend: ({ categories }: { categories: readonly string[] }) => (<div data-testid="chart-legend">{categories.join(",")}</div>@@ -225,4 +241,25 @@ describe("UsageTab", () => {const series = JSON.parse(bars[0].getAttribute("data-series") ?? "[]");expect(series[0]).toMatchObject({ tool_name: "search", spend: 4.0 });});++ it("renders the tool legend once outside the charts, with both charts sharing the tool colors", async () => {+ const toolSpend = {+ by_tool: [+ { tool_name: "search", spend: 4.0, call_count: 3, total_tokens: 150 },+ { tool_name: "read_file", spend: 1.0, call_count: 2, total_tokens: 50 },+ ],+ daily: [{ date: "2026-07-12", tool_name: "search", spend: 4.0, call_count: 3 }],+ start_date: "2026-07-12",+ end_date: "2026-07-12",+ };+ const { findAllByTestId, getAllByTestId } = renderWith([day("2026-07-12", {})], { toolSpend });++ const bars = await findAllByTestId("bar-chart");+ const [totalByTool, dailyByTool] = bars.slice(-2);+ expect(dailyByTool.getAttribute("data-show-legend")).toBe("false");+ expect(totalByTool.getAttribute("data-colors")).toBe(dailyByTool.getAttribute("data-colors"));++ const toolLegends = getAllByTestId("chart-legend").filter((legend) => legend.textContent === "search,read_file");+ expect(toolLegends).toHaveLength(1);+ });});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsxindex 508bc13496c..68f9c1d0ba4 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx@@ -278,7 +278,8 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {data={topToolsChart}index="tool_name"categories={["spend"]}- colors={["emerald"]}+ colors={toolColors}+ colorByDatumlayout="vertical"yAxisWidth={140}showLegend={false}@@ -287,6 +288,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {</div><div><p className="mb-2 text-sm font-medium text-muted-foreground">Daily spend by tool</p>+ <CustomLegend categories={topToolNames} colors={toolColors} /><BarChartdata={dailyToolSeries}index="date"@@ -294,6 +296,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {colors={toolColors}stackvalueFormatter={usd}+ showLegend={false}/></div></div>diff --git a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.test.tsx b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.test.tsxindex b30a252659f..cb0d5c603a4 100644--- a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.test.tsx+++ b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.test.tsx@@ -113,6 +113,40 @@ describe("BarChart", () => {expect(container.querySelector("style")).toBeNull();});+ it("colors each bar by its datum when colorByDatum is set, instead of one fill for the series", () => {+ const singleCategory = [+ { tool: "alpha", spend: 3 },+ { tool: "beta", spend: 2 },+ { tool: "gamma", spend: 1 },+ ];++ const { container, rerender } = render(+ <BarChart data={singleCategory} index="tool" categories={["spend"]} colors={["blue", "cyan", "violet"]} />,+ );+ const sharedFills = Array.from(container.querySelectorAll("path.recharts-rectangle")).map((rect) =>+ rect.getAttribute("fill"),+ );+ expect(new Set(sharedFills).size).toBe(1);++ rerender(+ <BarChart+ data={singleCategory}+ index="tool"+ categories={["spend"]}+ colors={["blue", "cyan", "violet"]}+ colorByDatum+ />,+ );+ const perDatumFills = Array.from(container.querySelectorAll("path.recharts-rectangle")).map((rect) =>+ rect.getAttribute("fill"),+ );+ expect(perDatumFills).toEqual([+ "var(--color-blue-500, #3b82f6)",+ "var(--color-cyan-500, #06b6d4)",+ "var(--color-violet-500, #8b5cf6)",+ ]);+ });+it("stacks bars into a single column per index when stack is set", () => {const { container } = render(<BarChart data={data} index="date" categories={["passed", "blocked"]} colors={["green", "red"]} stack={true} />,diff --git a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsxindex 7069ececb70..6bfcf14c2a0 100644--- a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx+++ b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx@@ -1,17 +1,20 @@"use client";import * as React from "react";-import { Bar, BarChart as RechartsBarChart, CartesianGrid, XAxis, YAxis } from "recharts";+import { Bar, BarChart as RechartsBarChart, CartesianGrid, Cell, XAxis, YAxis } from "recharts";import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, type ChartConfig } from "@/components/ui/chart";import { cn } from "@/lib/cva.config";import { ValueTooltip, type ChartTooltipComponent } from "./chart_tooltip";import { categoryFills, type ChartColor } from "./colors";+const MAX_BAR_SIZE = 64;+export type BarChartProps<TDatum extends Record<string, unknown>> = {data: readonly TDatum[];index: string;categories: readonly string[];colors?: readonly ChartColor[];+ colorByDatum?: boolean;valueFormatter?: (value: number) => string;stack?: boolean;layout?: "horizontal" | "vertical";@@ -32,6 +35,7 @@ export function BarChart<TDatum extends Record<string, unknown>>({index,categories,colors,+ colorByDatum = false,valueFormatter,stack = false,layout = "horizontal",@@ -57,7 +61,7 @@ export function BarChart<TDatum extends Record<string, unknown>>({);}- const fills = categoryFills(categories.length, colors);+ const fills = categoryFills(colorByDatum ? data.length : categories.length, colors);const config: ChartConfig = Object.fromEntries(categories.map((category) => [category, { label: category }]));const vertical = layout === "vertical";const TooltipContent = customTooltip ?? ValueTooltip;@@ -115,6 +119,7 @@ export function BarChart<TDatum extends Record<string, unknown>>({fill={fills[i]}stackId={stack ? "stack" : undefined}isAnimationActive={false}+ maxBarSize={MAX_BAR_SIZE}onClick={onValueChange? (item: { payload?: TDatum }) => {@@ -122,7 +127,9 @@ export function BarChart<TDatum extends Record<string, unknown>>({}: undefined}- />+ >+ {colorByDatum && data.map((_, dataIndex) => <Cell key={dataIndex} fill={fills[dataIndex]} />)}+ </Bar>))}</RechartsBarChart></ChartContainer>diff --git a/ui/litellm-dashboard/src/components/shared/charts/chart_legend.test.tsx b/ui/litellm-dashboard/src/components/shared/charts/chart_legend.test.tsxindex 889927aca43..28afe5faf9c 100644--- a/ui/litellm-dashboard/src/components/shared/charts/chart_legend.test.tsx+++ b/ui/litellm-dashboard/src/components/shared/charts/chart_legend.test.tsx@@ -21,6 +21,14 @@ describe("CustomLegend", () => {expect(dots[1]?.getAttribute("style")).toContain("--color-green-500");});+ it("wraps onto multiple lines instead of overflowing when there are many categories", () => {+ const { container } = render(+ <CustomLegend categories={Array.from({ length: 8 }, (_, i) => `metrics.tool_${i}`)} colors={["blue", "green"]} />,+ );++ expect(container.firstElementChild?.className).toContain("flex-wrap");+ });+it("cycles colors when there are more categories than colors", () => {const { container } = render(<CustomLegend categories={["metrics.a", "metrics.b", "metrics.c"]} colors={["blue", "green"]} />,diff --git a/ui/litellm-dashboard/src/components/shared/charts/chart_legend.tsx b/ui/litellm-dashboard/src/components/shared/charts/chart_legend.tsxindex da252d8bf63..1551f3d0e39 100644--- a/ui/litellm-dashboard/src/components/shared/charts/chart_legend.tsx+++ b/ui/litellm-dashboard/src/components/shared/charts/chart_legend.tsx@@ -11,7 +11,7 @@ export const CustomLegend = ({categories: readonly string[];colors: readonly ChartColor[];}) => (- <div className="flex items-center justify-end space-x-4">+ <div className="flex flex-wrap items-center justify-end gap-x-4 gap-y-1">{categories.map((category, idx) => (<div key={category} className="flex items-center space-x-2"><spandiff --git a/ui/litellm-dashboard/src/components/ui/chart.tsx b/ui/litellm-dashboard/src/components/ui/chart.tsxindex 14e10b9f06f..f0310819097 100644--- a/ui/litellm-dashboard/src/components/ui/chart.tsx+++ b/ui/litellm-dashboard/src/components/ui/chart.tsx@@ -264,7 +264,11 @@ const ChartLegendContent = React.forwardRef<return (<divref={ref}- className={cn("flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", className)}+ className={cn(+ "flex flex-wrap items-center justify-center gap-x-4 gap-y-1",+ verticalAlign === "top" ? "pb-3" : "pt-3",+ className,+ )}>{payload.filter((item) => item.type !== "none")