first commit

This commit is contained in:
Beyhan Oğur
2026-04-26 21:52:23 +03:00
commit 880f412e2c
2662 changed files with 866266 additions and 0 deletions

View File

@@ -0,0 +1,188 @@
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { TokenHistogramResponse } from "@/lib/types/logs";
import { Info } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";
import { ChartErrorBoundary } from "./chartErrorBoundary";
interface CacheTokenMeterChartProps {
data: TokenHistogramResponse | null;
}
const METER_COLORS = {
cached: "#06b6d4",
input: "#3b82f6",
};
const formatTokenCount = (count: number): string => {
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`;
if (count >= 1000) return `${(count / 1000).toFixed(1)}K`;
return count.toLocaleString();
};
interface GaugeGeometry {
cx: number;
cy: number;
innerRadius: number;
outerRadius: number;
}
function Needle({ percentage, geometry }: { percentage: number; geometry: GaugeGeometry }) {
const normalizedPercentage = Math.max(0, Math.min(percentage, 100));
const { cx, cy, outerRadius } = geometry;
const angle = 180 - (normalizedPercentage / 100) * 180;
const rad = (Math.PI * angle) / 180;
const needleLen = outerRadius * 0.94;
const tipX = cx + needleLen * Math.cos(rad);
const tipY = cy - needleLen * Math.sin(rad);
const perpRad = rad + Math.PI / 2;
const hw = 3.5;
const bx1 = cx + hw * Math.cos(perpRad);
const by1 = cy - hw * Math.sin(perpRad);
const bx2 = cx - hw * Math.cos(perpRad);
const by2 = cy + hw * Math.sin(perpRad);
return (
<g>
<path d={`M ${bx1} ${by1} L ${tipX} ${tipY} L ${bx2} ${by2} Z`} fill="#71717a" />
<circle cx={cx} cy={cy} r={5} fill="#71717a" />
</g>
);
}
export default function CacheTokenMeterChart({ data }: CacheTokenMeterChartProps) {
const chartContainerRef = useRef<HTMLDivElement | null>(null);
const [{ width, height }, setChartSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const node = chartContainerRef.current;
if (!node) return;
const updateSize = () => {
const nextWidth = node.clientWidth;
const nextHeight = node.clientHeight;
setChartSize((current) =>
current.width === nextWidth && current.height === nextHeight ? current : { width: nextWidth, height: nextHeight },
);
};
updateSize();
const resizeObserver = new ResizeObserver(updateSize);
resizeObserver.observe(node);
return () => resizeObserver.disconnect();
}, []);
const { percentage, totalCachedRead, totalPromptTokens } = useMemo(() => {
if (!data?.buckets || data.buckets.length === 0) {
return { percentage: 0, totalCachedRead: 0, totalPromptTokens: 0 };
}
let cachedRead = 0;
let promptTokens = 0;
for (const bucket of data.buckets) {
cachedRead += bucket.cached_read_tokens;
promptTokens += bucket.prompt_tokens;
}
if (promptTokens === 0) {
return { percentage: 0, totalCachedRead: cachedRead, totalPromptTokens: promptTokens };
}
return {
percentage: Math.max(0, Math.min(100, (cachedRead / promptTokens) * 100)),
totalCachedRead: cachedRead,
totalPromptTokens: promptTokens,
};
}, [data]);
const gaugeGeometry = useMemo<GaugeGeometry | null>(() => {
if (width <= 0 || height <= 0) return null;
const horizontalRadius = width * 0.4;
const verticalRadius = Math.max(24, height - 10);
const outerRadius = Math.min(horizontalRadius, verticalRadius);
const innerRadius = outerRadius * 0.58;
const cx = width / 2;
const cy = Math.min(height - 4, outerRadius + 4);
return { cx, cy, innerRadius, outerRadius };
}, [width, height]);
if (!data?.buckets || data.buckets.length === 0 || totalPromptTokens === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const valueData = [
{ name: "cached", value: percentage },
{ name: "remaining", value: 100 - percentage },
];
return (
<ChartErrorBoundary resetKey={`${data?.buckets?.length ?? 0}-${totalCachedRead}-${totalPromptTokens}`}>
<div className="grid h-full grid-rows-[104px_auto_auto] items-start overflow-hidden">
<div ref={chartContainerRef} className="relative h-[104px] w-full">
{gaugeGeometry && (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={valueData}
cx={gaugeGeometry.cx}
cy={gaugeGeometry.cy}
startAngle={180}
endAngle={0}
innerRadius={gaugeGeometry.innerRadius}
outerRadius={gaugeGeometry.outerRadius}
dataKey="value"
stroke="none"
isAnimationActive={false}
>
<Cell fill={METER_COLORS.cached} />
<Cell fill={METER_COLORS.input} opacity={0.22} />
</Pie>
</PieChart>
</ResponsiveContainer>
)}
{gaugeGeometry && (
<svg className="pointer-events-none absolute inset-0" viewBox={`0 0 ${width} ${height}`} aria-hidden="true">
<Needle percentage={percentage} geometry={gaugeGeometry} />
</svg>
)}
</div>
<div className="flex flex-col items-center pt-1 leading-none">
<div className="text-muted-foreground text-3xl font-semibold tracking-tight">{percentage.toFixed(1)}%</div>
<div className="mt-1 flex items-center gap-1 text-[11px] text-zinc-400">
<span>of input tokens cached</span>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
data-testid="cache-meter-info-btn"
className="text-zinc-500 transition-colors hover:text-zinc-300"
aria-label="More information about cache hit rate"
>
<Info className="h-3 w-3" />
</button>
</TooltipTrigger>
<TooltipContent side="top">This reflects provider-level caching, not Bifrost semantic cache hits.</TooltipContent>
</Tooltip>
</div>
</div>
<div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 pt-2 text-[11px] leading-none">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: METER_COLORS.cached }} />
<span className="text-primary">Cached: {formatTokenCount(totalCachedRead)}</span>
</span>
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: METER_COLORS.input }} />
<span className="text-muted-foreground">Input: {formatTokenCount(totalPromptTokens)}</span>
</span>
</div>
</div>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,71 @@
import { Card } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { ReactNode } from "react";
interface ChartCardProps {
title: string;
children: ReactNode;
headerActions?: ReactNode;
loading?: boolean;
testId?: string;
height?: string;
className?: string;
}
export function ChartCard({
title,
children,
headerActions,
loading,
testId,
height = "200px",
className,
}: ChartCardProps) {
if (loading) {
return (
<Card
className={cn("min-w-0 rounded-sm p-2 shadow-none", className)}
data-testid={testId}
>
<div className="mb-2 space-y-2">
<span className="text-primary pl-2 text-sm font-medium">{title}</span>
{headerActions && (
<div
className="w-full min-w-0"
data-testid={testId ? `${testId}-actions` : undefined}
>
{headerActions}
</div>
)}
</div>
<div
style={{ height }}
data-testid={testId ? `${testId}-chart-skeleton` : undefined}
>
<Skeleton className="h-full w-full" />
</div>
</Card>
);
}
return (
<Card
className={cn("min-w-0 rounded-sm p-2 shadow-none", className)}
data-testid={testId}
>
<div className="mb-2 space-y-2">
<span className="text-primary pl-2 text-sm font-medium">{title}</span>
{headerActions && (
<div
className="w-full min-w-0"
data-testid={testId ? `${testId}-actions` : undefined}
>
{headerActions}
</div>
)}
</div>
<div style={{ height }}>{children}</div>
</Card>
);
}

View File

@@ -0,0 +1,60 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { BarChart, CartesianGrid, ResponsiveContainer, XAxis, YAxis } from "recharts";
// Empty chart placeholder when data fails to render
function EmptyChart() {
return (
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={[
{ name: "", value: 0 },
{ name: " ", value: 0 },
]}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis dataKey="name" tick={{ fontSize: 13, className: "fill-zinc-500", dy: 5 }} tickLine={false} axisLine={false} />
<YAxis tick={{ fontSize: 13, className: "fill-zinc-500" }} tickLine={false} axisLine={false} width={40} domain={[0, 1]} />
</BarChart>
</ResponsiveContainer>
);
}
interface ChartErrorBoundaryProps {
children: ReactNode;
resetKey?: string;
}
interface ChartErrorBoundaryState {
hasError: boolean;
prevResetKey?: string;
}
export class ChartErrorBoundary extends Component<ChartErrorBoundaryProps, ChartErrorBoundaryState> {
constructor(props: ChartErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(_: Error) {
return { hasError: true };
}
static getDerivedStateFromProps(props: ChartErrorBoundaryProps, state: ChartErrorBoundaryState) {
// Reset error state when resetKey changes
if (props.resetKey !== state.prevResetKey) {
return { hasError: false, prevResetKey: props.resetKey };
}
return null;
}
componentDidCatch(error: Error, _errorInfo: ErrorInfo) {
console.warn("Chart rendering error:", error.message);
}
render() {
if (this.state.hasError) {
return <EmptyChart />;
}
return this.props.children;
}
}

View File

@@ -0,0 +1,35 @@
import { Button } from "@/components/ui/button";
import { BarChart3, LineChart } from "lucide-react";
export type ChartType = "bar" | "line";
interface ChartTypeToggleProps {
chartType: ChartType;
onToggle: (type: ChartType) => void;
"data-testid"?: string;
}
export function ChartTypeToggle({ chartType, onToggle, "data-testid": testId }: ChartTypeToggleProps) {
return (
<div className="flex items-center gap-1" data-testid={testId}>
<Button
variant={chartType === "bar" ? "secondary" : "ghost"}
size="sm"
className="h-7 w-7 p-0"
onClick={() => onToggle("bar")}
data-testid={testId ? `${testId}-bar-btn` : undefined}
>
<BarChart3 className="h-3.5 w-3.5" />
</Button>
<Button
variant={chartType === "line" ? "secondary" : "ghost"}
size="sm"
className="h-7 w-7 p-0"
onClick={() => onToggle("line")}
data-testid={testId ? `${testId}-line-btn` : undefined}
>
<LineChart className="h-3.5 w-3.5" />
</Button>
</div>
);
}

View File

@@ -0,0 +1,175 @@
import type { CostHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatCost, formatFullTimestamp, formatTimestamp, getModelColor } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface CostChartProps {
data: CostHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
selectedModel: string;
}
function CustomTooltip({ active, payload, selectedModel, models }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
{selectedModel === "all" ? (
<>
{models.map((model: string, idx: number) => {
const cost = data.by_model?.[model] || 0;
if (cost === 0) return null;
return (
<div key={model} className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(idx) }} />
<span className="max-w-[120px] truncate text-zinc-600 dark:text-zinc-400">{model}</span>
</span>
<span className="font-medium">{formatCost(cost)}</span>
</div>
);
})}
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Total</span>
<span className="font-medium">{formatCost(data.total_cost)}</span>
</div>
</>
) : (
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
<span className="text-zinc-600 dark:text-zinc-400">{selectedModel}</span>
</span>
<span className="font-medium">{formatCost(data.by_model?.[selectedModel] || 0)}</span>
</div>
)}
</div>
</div>
);
}
export function CostChart({ data, chartType, startTime, endTime, selectedModel }: CostChartProps) {
const { chartData, displayModels } = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return { chartData: [], displayModels: [] };
}
const models = selectedModel === "all" ? data.models : [selectedModel];
const processed = data.buckets.map((bucket, index) => {
const item: any = {
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
};
// Flatten by_model for easier chart access
models.forEach((model, idx) => {
item[`model_${idx}`] = bucket.by_model?.[model] || 0;
});
return item;
});
return { chartData: processed, displayModels: models };
}, [data, selectedModel]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${selectedModel}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip
content={<CustomTooltip selectedModel={selectedModel} models={data.models} />}
cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }}
/>
{displayModels.map((model, idx) => (
<Bar
isAnimationActive={false}
key={model}
dataKey={`model_${idx}`}
stackId="cost"
fill={getModelColor(idx)}
fillOpacity={0.9}
barSize={30}
radius={idx === displayModels.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
/>
))}
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip selectedModel={selectedModel} models={data.models} />} />
{displayModels.map((model, idx) => (
<Area
isAnimationActive={false}
key={model}
type="monotone"
dataKey={`model_${idx}`}
stackId="1"
stroke={getModelColor(idx)}
fill={getModelColor(idx)}
fillOpacity={0.7}
/>
))}
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,204 @@
import type { LatencyHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatFullTimestamp, formatLatency, formatTimestamp, LATENCY_COLORS } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface LatencyChartProps {
data: LatencyHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
}
function CustomTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.avg }} />
<span className="text-zinc-600 dark:text-zinc-400">Avg</span>
</span>
<span className="font-medium">{formatLatency(data.avg_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p90 }} />
<span className="text-zinc-600 dark:text-zinc-400">P90</span>
</span>
<span className="font-medium">{formatLatency(data.p90_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p95 }} />
<span className="text-zinc-600 dark:text-zinc-400">P95</span>
</span>
<span className="font-medium">{formatLatency(data.p95_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p99 }} />
<span className="text-zinc-600 dark:text-zinc-400">P99</span>
</span>
<span className="font-medium">{formatLatency(data.p99_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Requests</span>
<span className="font-medium">{data.total_requests.toLocaleString()}</span>
</div>
</div>
</div>
);
}
export function LatencyChart({ data, chartType, startTime, endTime }: LatencyChartProps) {
const chartData = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return [];
}
return data.buckets.map((bucket, index) => ({
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
}));
}, [data]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={55}
tickFormatter={formatLatency}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="avg_latency"
fill={LATENCY_COLORS.avg}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p90_latency"
fill={LATENCY_COLORS.p90}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p95_latency"
fill={LATENCY_COLORS.p95}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p99_latency"
fill={LATENCY_COLORS.p99}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={55}
tickFormatter={formatLatency}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} />
{/* Render P99 first (behind), then overlay in descending order so Avg is in front */}
<Area
isAnimationActive={false}
type="monotone"
dataKey="p99_latency"
stroke={LATENCY_COLORS.p99}
fill={LATENCY_COLORS.p99}
fillOpacity={0.15}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="p95_latency"
stroke={LATENCY_COLORS.p95}
fill={LATENCY_COLORS.p95}
fillOpacity={0.2}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="p90_latency"
stroke={LATENCY_COLORS.p90}
fill={LATENCY_COLORS.p90}
fillOpacity={0.25}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="avg_latency"
stroke={LATENCY_COLORS.avg}
fill={LATENCY_COLORS.avg}
fillOpacity={0.4}
/>
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,219 @@
import type { LogsHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import {
CHART_COLORS,
formatFullTimestamp,
formatTimestamp,
} from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface LogVolumeChartProps {
data: LogsHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
}
type LogVolumeDataPoint = {
timestamp: string;
count: number;
success: number;
error: number;
index: number;
formattedTime: string;
};
interface CustomTooltipProps {
active?: boolean;
payload?: Array<{ payload?: LogVolumeDataPoint }>;
}
function CustomTooltip({ active, payload }: CustomTooltipProps) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">
{formatFullTimestamp(data.timestamp)}
</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-emerald-500" />
<span className="text-zinc-600 dark:text-zinc-400">Success</span>
</span>
<span className="font-medium text-emerald-600 dark:text-emerald-400">
{data.success.toLocaleString()}
</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-red-500" />
<span className="text-zinc-600 dark:text-zinc-400">Error</span>
</span>
<span className="font-medium text-red-600 dark:text-red-400">
{data.error.toLocaleString()}
</span>
</div>
</div>
</div>
);
}
export function LogVolumeChart({
data,
chartType,
startTime,
endTime,
}: LogVolumeChartProps) {
const chartData = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return [];
}
return data.buckets.map((bucket, index) => ({
...bucket,
index,
formattedTime: formatTimestamp(
bucket.timestamp,
data.bucket_size_seconds,
),
}));
}, [data]);
if (!data?.buckets || chartData.length === 0) {
return (
<div className="text-muted-foreground flex h-full items-center justify-center text-sm">
No data available
</div>
);
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 12, bottom: 0 },
};
return (
<ChartErrorBoundary
resetKey={`${startTime}-${endTime}-${chartData.length}`}
>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid
strokeDasharray="3 3"
vertical={false}
className="stroke-zinc-200 dark:stroke-zinc-700"
/>
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) =>
chartData[Math.round(idx)]?.formattedTime || ""
}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={56}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip
content={<CustomTooltip />}
cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }}
/>
<Bar
isAnimationActive={false}
dataKey="success"
stackId="requests"
fill={CHART_COLORS.success}
fillOpacity={0.9}
radius={[0, 0, 0, 0]}
barSize={30}
/>
<Bar
isAnimationActive={false}
dataKey="error"
stackId="requests"
fill={CHART_COLORS.error}
fillOpacity={0.9}
radius={[2, 2, 0, 0]}
barSize={30}
/>
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid
strokeDasharray="3 3"
vertical={false}
className="stroke-zinc-200 dark:stroke-zinc-700"
/>
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) =>
chartData[Math.round(idx)]?.formattedTime || ""
}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={56}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} />
<Area
type="monotone"
dataKey="success"
stackId="1"
stroke={CHART_COLORS.success}
fill={CHART_COLORS.success}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="error"
stackId="1"
stroke={CHART_COLORS.error}
fill={CHART_COLORS.error}
fillOpacity={0.7}
/>
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,130 @@
import type { MCPCostHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { CHART_COLORS, formatCost, formatFullTimestamp, formatTimestamp } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface MCPCostChartProps {
data: MCPCostHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
}
function CustomTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.cost }} />
<span className="text-zinc-600 dark:text-zinc-400">Cost</span>
</span>
<span className="font-medium">{formatCost(data.total_cost)}</span>
</div>
</div>
</div>
);
}
export function MCPCostChart({ data, chartType, startTime, endTime }: MCPCostChartProps) {
const chartData = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return [];
}
return data.buckets.map((bucket, index) => ({
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
}));
}, [data]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${chartType}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="total_cost"
fill={CHART_COLORS.cost}
fillOpacity={0.9}
radius={[2, 2, 0, 0]}
barSize={30}
/>
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} />
<Area
isAnimationActive={false}
type="monotone"
dataKey="total_cost"
stroke={CHART_COLORS.cost}
fill={CHART_COLORS.cost}
fillOpacity={0.7}
/>
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,80 @@
import type { MCPTopToolsResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatCost, getModelColor } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
interface MCPTopToolsChartProps {
data: MCPTopToolsResponse | null;
}
function CustomTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs font-medium text-zinc-700 dark:text-zinc-300">{data.tool_name}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="text-zinc-600 dark:text-zinc-400">Count</span>
<span className="font-medium">{data.count.toLocaleString()}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="text-zinc-600 dark:text-zinc-400">Cost</span>
<span className="font-medium">{formatCost(data.cost)}</span>
</div>
</div>
</div>
);
}
export function MCPTopToolsChart({ data }: MCPTopToolsChartProps) {
const chartData = useMemo(() => {
if (!data?.tools || data.tools.length === 0) {
return [];
}
return data.tools.slice(0, 10);
}, [data]);
if (!data?.tools || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
return (
<ChartErrorBoundary resetKey={JSON.stringify(chartData.map(({ tool_name, count, cost }) => [tool_name, count, cost]))}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} layout="vertical" margin={{ top: 6, right: 4, left: 4, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" horizontal={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
type="number"
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<YAxis
type="category"
dataKey="tool_name"
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={120}
interval={0}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar isAnimationActive={false} dataKey="count" radius={[0, 2, 2, 0]} barSize={20}>
{chartData.map((_, index) => (
<Cell key={`cell-${index}`} fill={getModelColor(index)} fillOpacity={0.9} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,161 @@
import type { MCPHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { CHART_COLORS, formatFullTimestamp, formatTimestamp } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface MCPVolumeChartProps {
data: MCPHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
}
function CustomTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-emerald-500" />
<span className="text-zinc-600 dark:text-zinc-400">Success</span>
</span>
<span className="font-medium text-emerald-600 dark:text-emerald-400">{data.success.toLocaleString()}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-red-500" />
<span className="text-zinc-600 dark:text-zinc-400">Error</span>
</span>
<span className="font-medium text-red-600 dark:text-red-400">{data.error.toLocaleString()}</span>
</div>
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Total</span>
<span className="font-medium">{data.count.toLocaleString()}</span>
</div>
</div>
</div>
);
}
export function MCPVolumeChart({ data, chartType, startTime, endTime }: MCPVolumeChartProps) {
const chartData = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return [];
}
return data.buckets.map((bucket, index) => ({
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
}));
}, [data]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${chartType}-${startTime}-${endTime}-${chartData.length}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={40}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="success"
stackId="requests"
fill={CHART_COLORS.success}
fillOpacity={0.9}
radius={[0, 0, 0, 0]}
barSize={30}
/>
<Bar
isAnimationActive={false}
dataKey="error"
stackId="requests"
fill={CHART_COLORS.error}
fillOpacity={0.9}
radius={[2, 2, 0, 0]}
barSize={30}
/>
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={40}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} />
<Area
isAnimationActive={false}
type="monotone"
dataKey="success"
stackId="1"
stroke={CHART_COLORS.success}
fill={CHART_COLORS.success}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="error"
stackId="1"
stroke={CHART_COLORS.error}
fill={CHART_COLORS.error}
fillOpacity={0.7}
/>
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,33 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
interface ModelFilterSelectProps {
models: string[];
selectedModel: string;
onModelChange: (model: string) => void;
placeholder?: string;
"data-testid"?: string;
}
export function ModelFilterSelect({
models,
selectedModel,
onModelChange,
placeholder = "All Models",
"data-testid": testId,
}: ModelFilterSelectProps) {
return (
<Select value={selectedModel} onValueChange={onModelChange}>
<SelectTrigger className="!h-7.5 w-[110px] text-xs sm:w-[130px]" data-testid={testId} size="sm">
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{placeholder}</SelectItem>
{models.filter(Boolean).map((model) => (
<SelectItem key={model} value={model} className="text-xs">
{model}
</SelectItem>
))}
</SelectContent>
</Select>
);
}

View File

@@ -0,0 +1,244 @@
import type { ModelHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { CHART_COLORS, formatFullTimestamp, formatTimestamp, getModelColor } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
// Sanitize model names to avoid Recharts interpreting dots/brackets as path separators
function sanitizeModelKey(model: string): string {
return model.replace(/[.\[\]]/g, "_");
}
interface ModelUsageChartProps {
data: ModelHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
selectedModel: string;
}
function CustomTooltip({ active, payload, selectedModel, models }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
{selectedModel === "all" ? (
<>
{models.map((model: string, idx: number) => {
const stats = data.by_model?.[model];
if (!stats || stats.total === 0) return null;
return (
<div key={model} className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(idx) }} />
<span className="max-w-[120px] truncate text-zinc-600 dark:text-zinc-400">{model}</span>
</span>
<span className="font-medium">{stats.total.toLocaleString()}</span>
</div>
);
})}
</>
) : (
<>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-emerald-500" />
<span className="text-zinc-600 dark:text-zinc-400">Success</span>
</span>
<span className="font-medium text-emerald-600 dark:text-emerald-400">
{(data.by_model?.[selectedModel]?.success || 0).toLocaleString()}
</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-red-500" />
<span className="text-zinc-600 dark:text-zinc-400">Error</span>
</span>
<span className="font-medium text-red-600 dark:text-red-400">
{(data.by_model?.[selectedModel]?.error || 0).toLocaleString()}
</span>
</div>
</>
)}
</div>
</div>
);
}
export function ModelUsageChart({ data, chartType, startTime, endTime, selectedModel }: ModelUsageChartProps) {
const { chartData, displayModels } = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return { chartData: [], displayModels: [] };
}
const models = data.models;
const processed = data.buckets.map((bucket, index) => {
const item: any = {
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
};
if (selectedModel === "all") {
// For "all", show total per model
models.forEach((model) => {
const safeKey = sanitizeModelKey(model);
item[`model_${safeKey}`] = bucket.by_model?.[model]?.total || 0;
});
} else {
// For specific model, show success/error breakdown
const stats = bucket.by_model?.[selectedModel];
item.success = stats?.success || 0;
item.error = stats?.error || 0;
}
return item;
});
return { chartData: processed, displayModels: models };
}, [data, selectedModel]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${selectedModel}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={40}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip
content={<CustomTooltip selectedModel={selectedModel} models={displayModels} />}
cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }}
/>
{selectedModel === "all" ? (
displayModels.map((model, idx) => (
<Bar
isAnimationActive={false}
key={model}
dataKey={`model_${sanitizeModelKey(model)}`}
stackId="models"
fill={getModelColor(idx)}
fillOpacity={0.9}
barSize={30}
radius={idx === displayModels.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
/>
))
) : (
<>
<Bar
isAnimationActive={false}
dataKey="success"
stackId="status"
fill={CHART_COLORS.success}
fillOpacity={0.9}
radius={[0, 0, 0, 0]}
barSize={30}
/>
<Bar
isAnimationActive={false}
dataKey="error"
stackId="status"
fill={CHART_COLORS.error}
fillOpacity={0.9}
radius={[2, 2, 0, 0]}
barSize={30}
/>
</>
)}
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={40}
tickFormatter={(v) => v.toLocaleString()}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip selectedModel={selectedModel} models={displayModels} />} />
{selectedModel === "all" ? (
displayModels.map((model, idx) => (
<Area
isAnimationActive={false}
key={model}
type="monotone"
dataKey={`model_${sanitizeModelKey(model)}`}
stackId="1"
stroke={getModelColor(idx)}
fill={getModelColor(idx)}
fillOpacity={0.7}
/>
))
) : (
<>
<Area
isAnimationActive={false}
type="monotone"
dataKey="success"
stackId="1"
stroke={CHART_COLORS.success}
fill={CHART_COLORS.success}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="error"
stackId="1"
stroke={CHART_COLORS.error}
fill={CHART_COLORS.error}
fillOpacity={0.7}
/>
</>
)}
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,174 @@
import type { ProviderCostHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatCost, formatFullTimestamp, formatTimestamp, getModelColor } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface ProviderCostChartProps {
data: ProviderCostHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
selectedProvider: string;
}
function CustomTooltip({ active, payload, selectedProvider, providers }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
{selectedProvider === "all" ? (
<>
{providers.map((provider: string, idx: number) => {
const cost = data.by_provider?.[provider] || 0;
if (cost === 0) return null;
return (
<div key={provider} className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(idx) }} />
<span className="max-w-[120px] truncate text-zinc-600 dark:text-zinc-400">{provider}</span>
</span>
<span className="font-medium">{formatCost(cost)}</span>
</div>
);
})}
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Total</span>
<span className="font-medium">{formatCost(data.total_cost)}</span>
</div>
</>
) : (
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
<span className="text-zinc-600 dark:text-zinc-400">{selectedProvider}</span>
</span>
<span className="font-medium">{formatCost(data.by_provider?.[selectedProvider] || 0)}</span>
</div>
)}
</div>
</div>
);
}
export function ProviderCostChart({ data, chartType, startTime, endTime, selectedProvider }: ProviderCostChartProps) {
const { chartData, displayProviders } = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return { chartData: [], displayProviders: [] };
}
const providers = selectedProvider === "all" ? data.providers : [selectedProvider];
const processed = data.buckets.map((bucket, index) => {
const item: any = {
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
};
providers.forEach((provider, idx) => {
item[`provider_${idx}`] = bucket.by_provider?.[provider] || 0;
});
return item;
});
return { chartData: processed, displayProviders: providers };
}, [data, selectedProvider]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${selectedProvider}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip
content={<CustomTooltip selectedProvider={selectedProvider} providers={data.providers} />}
cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }}
/>
{displayProviders.map((provider, idx) => (
<Bar
isAnimationActive={false}
key={provider}
dataKey={`provider_${idx}`}
stackId="cost"
fill={getModelColor(idx)}
fillOpacity={0.9}
barSize={30}
radius={idx === displayProviders.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
/>
))}
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={(v) => formatCost(v)}
domain={[0, (dataMax: number) => Math.max(dataMax, 0.01)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip selectedProvider={selectedProvider} providers={data.providers} />} />
{displayProviders.map((provider, idx) => (
<Area
isAnimationActive={false}
key={provider}
type="monotone"
dataKey={`provider_${idx}`}
stackId="1"
stroke={getModelColor(idx)}
fill={getModelColor(idx)}
fillOpacity={0.7}
/>
))}
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,26 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
interface ProviderFilterSelectProps {
providers: string[];
selectedProvider: string;
onProviderChange: (provider: string) => void;
"data-testid"?: string;
}
export function ProviderFilterSelect({ providers, selectedProvider, onProviderChange, "data-testid": testId }: ProviderFilterSelectProps) {
return (
<Select value={selectedProvider} onValueChange={onProviderChange}>
<SelectTrigger className="!h-7.5 w-[110px] text-xs sm:w-[130px]" data-testid={testId} size="sm">
<SelectValue placeholder="All Providers" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Providers</SelectItem>
{providers.filter(Boolean).map((provider) => (
<SelectItem key={provider} value={provider} className="text-xs">
{provider}
</SelectItem>
))}
</SelectContent>
</Select>
);
}

View File

@@ -0,0 +1,292 @@
import type { ProviderLatencyHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { formatFullTimestamp, formatLatency, formatTimestamp, getModelColor, LATENCY_COLORS } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface ProviderLatencyChartProps {
data: ProviderLatencyHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
selectedProvider: string;
}
function AllProvidersTooltip({ active, payload, providers }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
{providers.map((provider: string, idx: number) => {
const stats = data.by_provider?.[provider];
if (!stats || stats.avg_latency === 0) return null;
return (
<div key={provider} className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(idx) }} />
<span className="max-w-[120px] truncate text-zinc-600 dark:text-zinc-400">{provider}</span>
</span>
<span className="font-medium">{formatLatency(stats.avg_latency)}</span>
</div>
);
})}
</div>
</div>
);
}
function SingleProviderTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.avg }} />
<span className="text-zinc-600 dark:text-zinc-400">Avg</span>
</span>
<span className="font-medium">{formatLatency(data.avg_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p90 }} />
<span className="text-zinc-600 dark:text-zinc-400">P90</span>
</span>
<span className="font-medium">{formatLatency(data.p90_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p95 }} />
<span className="text-zinc-600 dark:text-zinc-400">P95</span>
</span>
<span className="font-medium">{formatLatency(data.p95_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p99 }} />
<span className="text-zinc-600 dark:text-zinc-400">P99</span>
</span>
<span className="font-medium">{formatLatency(data.p99_latency)}</span>
</div>
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Requests</span>
<span className="font-medium">{data.total_requests?.toLocaleString() || 0}</span>
</div>
</div>
</div>
);
}
export function ProviderLatencyChart({ data, chartType, startTime, endTime, selectedProvider }: ProviderLatencyChartProps) {
const { chartData, mode, displayProviders } = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return { chartData: [], mode: "all" as const, displayProviders: [] };
}
const isSingleProvider = selectedProvider !== "all";
const providers = isSingleProvider ? [selectedProvider] : data.providers;
const processed = data.buckets.map((bucket, index) => {
const item: any = {
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
};
if (isSingleProvider) {
const stats = bucket.by_provider?.[selectedProvider];
item.avg_latency = stats?.avg_latency || 0;
item.p90_latency = stats?.p90_latency || 0;
item.p95_latency = stats?.p95_latency || 0;
item.p99_latency = stats?.p99_latency || 0;
item.total_requests = stats?.total_requests || 0;
} else {
providers.forEach((provider, idx) => {
item[`provider_${idx}`] = bucket.by_provider?.[provider]?.avg_latency || 0;
});
}
return item;
});
return { chartData: processed, mode: isSingleProvider ? ("single" as const) : ("all" as const), displayProviders: providers };
}, [data, selectedProvider]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${selectedProvider}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={55}
tickFormatter={formatLatency}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
{mode === "single" ? (
<>
<Tooltip content={<SingleProviderTooltip provider={selectedProvider} />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="avg_latency"
fill={LATENCY_COLORS.avg}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p90_latency"
fill={LATENCY_COLORS.p90}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p95_latency"
fill={LATENCY_COLORS.p95}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="p99_latency"
fill={LATENCY_COLORS.p99}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
</>
) : (
<>
<Tooltip content={<AllProvidersTooltip providers={data.providers} />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
{displayProviders.map((provider, idx) => (
<Bar
key={provider}
dataKey={`provider_${idx}`}
fill={getModelColor(idx)}
isAnimationActive={false}
fillOpacity={0.9}
barSize={8}
radius={[2, 2, 0, 0]}
/>
))}
</>
)}
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={55}
tickFormatter={formatLatency}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
{mode === "single" ? (
<>
<Tooltip content={<SingleProviderTooltip provider={selectedProvider} />} />
<Area
isAnimationActive={false}
type="monotone"
dataKey="p99_latency"
stroke={LATENCY_COLORS.p99}
fill={LATENCY_COLORS.p99}
fillOpacity={0.15}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="p95_latency"
stroke={LATENCY_COLORS.p95}
fill={LATENCY_COLORS.p95}
fillOpacity={0.2}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="p90_latency"
stroke={LATENCY_COLORS.p90}
fill={LATENCY_COLORS.p90}
fillOpacity={0.25}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="avg_latency"
stroke={LATENCY_COLORS.avg}
fill={LATENCY_COLORS.avg}
fillOpacity={0.4}
/>
</>
) : (
<>
<Tooltip content={<AllProvidersTooltip providers={data.providers} />} />
{displayProviders.map((provider, idx) => (
<Area
key={provider}
type="monotone"
isAnimationActive={false}
dataKey={`provider_${idx}`}
stroke={getModelColor(idx)}
fill={getModelColor(idx)}
fillOpacity={0.3}
/>
))}
</>
)}
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,252 @@
import type { ProviderTokenHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { CHART_COLORS, formatFullTimestamp, formatTimestamp, formatTokens, getModelColor } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface ProviderTokenChartProps {
data: ProviderTokenHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
selectedProvider: string;
}
function AllProvidersTooltip({ active, payload, providers }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
{providers.map((provider: string, idx: number) => {
const tokens = data.by_provider?.[provider]?.total_tokens || 0;
if (tokens === 0) return null;
return (
<div key={provider} className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: getModelColor(idx) }} />
<span className="max-w-[120px] truncate text-zinc-600 dark:text-zinc-400">{provider}</span>
</span>
<span className="font-medium">{formatTokens(tokens)}</span>
</div>
);
})}
</div>
</div>
);
}
function SingleProviderTooltip({ active, payload, provider }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
const stats = data.by_provider?.[provider];
if (!stats) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.promptTokens }} />
<span className="text-zinc-600 dark:text-zinc-400">Input</span>
</span>
<span className="font-medium">{formatTokens(stats.prompt_tokens || 0)}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.completionTokens }} />
<span className="text-zinc-600 dark:text-zinc-400">Output</span>
</span>
<span className="font-medium">{formatTokens(stats.completion_tokens || 0)}</span>
</div>
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Total</span>
<span className="font-medium">{formatTokens(stats.total_tokens || 0)}</span>
</div>
</div>
</div>
);
}
export function ProviderTokenChart({ data, chartType, startTime, endTime, selectedProvider }: ProviderTokenChartProps) {
const { chartData, mode, displayProviders } = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return { chartData: [], mode: "all" as const, displayProviders: [] };
}
const isSingleProvider = selectedProvider !== "all";
const providers = isSingleProvider ? [selectedProvider] : data.providers;
const processed = data.buckets.map((bucket, index) => {
const item: any = {
...bucket,
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
};
if (isSingleProvider) {
const stats = bucket.by_provider?.[selectedProvider];
item.prompt_tokens = stats?.prompt_tokens || 0;
item.completion_tokens = stats?.completion_tokens || 0;
} else {
providers.forEach((provider, idx) => {
item[`provider_${idx}`] = bucket.by_provider?.[provider]?.total_tokens || 0;
});
}
return item;
});
return { chartData: processed, mode: isSingleProvider ? ("single" as const) : ("all" as const), displayProviders: providers };
}, [data, selectedProvider]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}-${selectedProvider}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={formatTokens}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
{mode === "single" ? (
<>
<Tooltip content={<SingleProviderTooltip provider={selectedProvider} />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="prompt_tokens"
stackId="tokens"
fill={CHART_COLORS.promptTokens}
fillOpacity={0.9}
barSize={30}
radius={[0, 0, 0, 0]}
/>
<Bar
isAnimationActive={false}
dataKey="completion_tokens"
stackId="tokens"
fill={CHART_COLORS.completionTokens}
fillOpacity={0.9}
barSize={30}
radius={[2, 2, 0, 0]}
/>
</>
) : (
<>
<Tooltip content={<AllProvidersTooltip providers={data.providers} />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
{displayProviders.map((provider, idx) => (
<Bar
isAnimationActive={false}
key={provider}
dataKey={`provider_${idx}`}
stackId="tokens"
fill={getModelColor(idx)}
fillOpacity={0.9}
barSize={30}
radius={idx === displayProviders.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
/>
))}
</>
)}
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={formatTokens}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
{mode === "single" ? (
<>
<Tooltip content={<SingleProviderTooltip provider={selectedProvider} />} />
<Area
isAnimationActive={false}
type="monotone"
dataKey="completion_tokens"
stackId="1"
stroke={CHART_COLORS.completionTokens}
fill={CHART_COLORS.completionTokens}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="prompt_tokens"
stackId="1"
stroke={CHART_COLORS.promptTokens}
fill={CHART_COLORS.promptTokens}
fillOpacity={0.7}
/>
</>
) : (
<>
<Tooltip content={<AllProvidersTooltip providers={data.providers} />} />
{displayProviders.map((provider, idx) => (
<Area
isAnimationActive={false}
key={provider}
type="monotone"
dataKey={`provider_${idx}`}
stackId="1"
stroke={getModelColor(idx)}
fill={getModelColor(idx)}
fillOpacity={0.7}
/>
))}
</>
)}
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}

View File

@@ -0,0 +1,189 @@
import type { TokenHistogramResponse } from "@/lib/types/logs";
import { useMemo } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { CHART_COLORS, formatFullTimestamp, formatTimestamp, formatTokens } from "../../utils/chartUtils";
import { ChartErrorBoundary } from "./chartErrorBoundary";
import type { ChartType } from "./chartTypeToggle";
interface TokenUsageChartProps {
data: TokenHistogramResponse | null;
chartType: ChartType;
startTime: number;
endTime: number;
}
function CustomTooltip({ active, payload }: any) {
if (!active || !payload || !payload.length) return null;
const data = payload[0]?.payload;
if (!data) return null;
return (
<div className="rounded-sm border border-zinc-200 bg-white px-3 py-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<div className="mb-1 text-xs text-zinc-500">{formatFullTimestamp(data.timestamp)}</div>
<div className="space-y-1 text-sm">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-blue-500" />
<span className="text-zinc-600 dark:text-zinc-400">Input</span>
</span>
<span className="font-medium">{data.prompt_tokens.toLocaleString()}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full bg-emerald-500" />
<span className="text-zinc-600 dark:text-zinc-400">Output</span>
</span>
<span className="font-medium">{data.completion_tokens.toLocaleString()}</span>
</div>
{data.cached_read_tokens > 0 && (
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-1.5">
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.cachedReadTokens }} />
<span className="text-zinc-600 dark:text-zinc-400">Cached</span>
</span>
<span className="font-medium">{data.cached_read_tokens.toLocaleString()}</span>
</div>
)}
<div className="flex items-center justify-between gap-4 border-t border-zinc-200 pt-1 dark:border-zinc-700">
<span className="text-zinc-600 dark:text-zinc-400">Total</span>
<span className="font-medium">{data.total_tokens.toLocaleString()}</span>
</div>
</div>
</div>
);
}
export function TokenUsageChart({ data, chartType, startTime, endTime }: TokenUsageChartProps) {
const chartData = useMemo(() => {
if (!data?.buckets || !data.bucket_size_seconds) {
return [];
}
return data.buckets.map((bucket, index) => ({
...bucket,
uncached_prompt_tokens: Math.max(bucket.prompt_tokens - bucket.cached_read_tokens, 0),
index,
formattedTime: formatTimestamp(bucket.timestamp, data.bucket_size_seconds),
}));
}, [data]);
if (!data?.buckets || chartData.length === 0) {
return <div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>;
}
const commonProps = {
data: chartData,
margin: { top: 6, right: 4, left: 4, bottom: 0 },
};
return (
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}`}>
<ResponsiveContainer width="100%" height="100%">
{chartType === "bar" ? (
<BarChart {...commonProps} barCategoryGap={1}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500", dy: 5 }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={formatTokens}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
<Bar
isAnimationActive={false}
dataKey="uncached_prompt_tokens"
stackId="tokens"
fill={CHART_COLORS.promptTokens}
fillOpacity={0.9}
radius={[0, 0, 0, 0]}
barSize={30}
/>
<Bar
isAnimationActive={false}
dataKey="completion_tokens"
stackId="tokens"
fill={CHART_COLORS.completionTokens}
fillOpacity={0.9}
radius={[0, 0, 0, 0]}
barSize={30}
/>
<Bar
isAnimationActive={false}
dataKey="cached_read_tokens"
stackId="tokens"
fill={CHART_COLORS.cachedReadTokens}
fillOpacity={0.9}
radius={[2, 2, 0, 0]}
barSize={30}
/>
</BarChart>
) : (
<AreaChart {...commonProps}>
<CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-zinc-200 dark:stroke-zinc-700" />
<XAxis
dataKey="index"
type="number"
domain={[-0.5, chartData.length - 0.5]}
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
tickFormatter={(idx) => chartData[Math.round(idx)]?.formattedTime || ""}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, className: "fill-zinc-500" }}
tickLine={false}
axisLine={false}
width={50}
tickFormatter={formatTokens}
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
allowDataOverflow={false}
/>
<Tooltip content={<CustomTooltip />} />
<Area
isAnimationActive={false}
type="monotone"
dataKey="uncached_prompt_tokens"
stackId="1"
stroke={CHART_COLORS.promptTokens}
fill={CHART_COLORS.promptTokens}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="completion_tokens"
stackId="1"
stroke={CHART_COLORS.completionTokens}
fill={CHART_COLORS.completionTokens}
fillOpacity={0.7}
/>
<Area
isAnimationActive={false}
type="monotone"
dataKey="cached_read_tokens"
stackId="1"
stroke={CHART_COLORS.cachedReadTokens}
fill={CHART_COLORS.cachedReadTokens}
fillOpacity={0.7}
/>
</AreaChart>
)}
</ResponsiveContainer>
</ChartErrorBoundary>
);
}