first commit
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
71
ui/app/workspace/dashboard/components/charts/chartCard.tsx
Normal file
71
ui/app/workspace/dashboard/components/charts/chartCard.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
175
ui/app/workspace/dashboard/components/charts/costChart.tsx
Normal file
175
ui/app/workspace/dashboard/components/charts/costChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
204
ui/app/workspace/dashboard/components/charts/latencyChart.tsx
Normal file
204
ui/app/workspace/dashboard/components/charts/latencyChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
219
ui/app/workspace/dashboard/components/charts/logVolumeChart.tsx
Normal file
219
ui/app/workspace/dashboard/components/charts/logVolumeChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
130
ui/app/workspace/dashboard/components/charts/mcpCostChart.tsx
Normal file
130
ui/app/workspace/dashboard/components/charts/mcpCostChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
161
ui/app/workspace/dashboard/components/charts/mcpVolumeChart.tsx
Normal file
161
ui/app/workspace/dashboard/components/charts/mcpVolumeChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
244
ui/app/workspace/dashboard/components/charts/modelUsageChart.tsx
Normal file
244
ui/app/workspace/dashboard/components/charts/modelUsageChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
189
ui/app/workspace/dashboard/components/charts/tokenUsageChart.tsx
Normal file
189
ui/app/workspace/dashboard/components/charts/tokenUsageChart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
88
ui/app/workspace/dashboard/components/exportPopover.tsx
Normal file
88
ui/app/workspace/dashboard/components/exportPopover.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdownMenu";
|
||||
import { buildCSV, downloadCSV } from "@/lib/utils/csv";
|
||||
import { Download, FileSpreadsheet, FileText, Loader2 } from "lucide-react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { type DashboardData, getCSVSections } from "../utils/exportUtils";
|
||||
|
||||
const PDF_TAB_LABELS = ["Overview", "Provider Usage", "Model Rankings", "MCP Usage"];
|
||||
|
||||
interface ExportPopoverProps {
|
||||
getData: () => DashboardData;
|
||||
onPreloadData: () => Promise<void>;
|
||||
onPdfExport: () => Promise<HTMLElement[]>;
|
||||
onPdfExportDone: () => void;
|
||||
}
|
||||
|
||||
export function ExportPopover({ getData, onPreloadData, onPdfExport, onPdfExportDone }: ExportPopoverProps) {
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
const handleCsvExport = useCallback(async () => {
|
||||
setExporting(true);
|
||||
try {
|
||||
await onPreloadData();
|
||||
const sections = getCSVSections(getData(), "all");
|
||||
const parts: string[] = [];
|
||||
for (const section of sections) {
|
||||
if (section.csv.rows.length === 0) continue;
|
||||
parts.push(`# ${section.name}`);
|
||||
parts.push(buildCSV(section.csv.headers, section.csv.rows));
|
||||
parts.push("");
|
||||
}
|
||||
if (parts.length > 0) {
|
||||
downloadCSV(parts.join("\n"), "dashboard-export");
|
||||
}
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}, [getData, onPreloadData]);
|
||||
|
||||
const handlePdfExport = useCallback(async () => {
|
||||
setExporting(true);
|
||||
|
||||
// Yield a frame so the spinner renders before heavy work starts
|
||||
await new Promise((r) => requestAnimationFrame(r));
|
||||
|
||||
try {
|
||||
const { generatePdf } = await import("@/lib/utils/pdf");
|
||||
|
||||
const elements = await onPdfExport();
|
||||
|
||||
const sections = elements.map((element, i) => ({
|
||||
element,
|
||||
label: PDF_TAB_LABELS[i],
|
||||
}));
|
||||
|
||||
await generatePdf(sections, "dashboard-export", {
|
||||
branding: {
|
||||
logoSrc: "/bifrost-logo.webp",
|
||||
text: "Powered by",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
onPdfExportDone();
|
||||
setExporting(false);
|
||||
}
|
||||
}, [onPdfExport, onPdfExportDone]);
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="default" disabled={exporting} data-testid="dashboard-export-trigger">
|
||||
{exporting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
|
||||
{exporting ? "Exporting..." : "Export"}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleCsvExport} data-testid="export-csv-item">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
CSV
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handlePdfExport} data-testid="export-pdf-item">
|
||||
<FileText className="h-4 w-4" />
|
||||
PDF
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
107
ui/app/workspace/dashboard/components/mcpTab.tsx
Normal file
107
ui/app/workspace/dashboard/components/mcpTab.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { MCPCostHistogramResponse, MCPHistogramResponse, MCPTopToolsResponse } from "@/lib/types/logs";
|
||||
import { CHART_COLORS, CHART_HEADER_ACTIONS_CLASS, CHART_HEADER_CONTROLS_CLASS, CHART_HEADER_LEGEND_CLASS } from "../utils/chartUtils";
|
||||
import { ChartCard } from "./charts/chartCard";
|
||||
import { type ChartType, ChartTypeToggle } from "./charts/chartTypeToggle";
|
||||
import { MCPCostChart } from "./charts/mcpCostChart";
|
||||
import { MCPTopToolsChart } from "./charts/mcpTopToolsChart";
|
||||
import { MCPVolumeChart } from "./charts/mcpVolumeChart";
|
||||
|
||||
export interface MCPTabProps {
|
||||
// Data
|
||||
mcpHistogramData: MCPHistogramResponse | null;
|
||||
mcpCostData: MCPCostHistogramResponse | null;
|
||||
mcpTopToolsData: MCPTopToolsResponse | null;
|
||||
|
||||
// Loading states
|
||||
loadingMcpHistogram: boolean;
|
||||
loadingMcpCost: boolean;
|
||||
loadingMcpTopTools: boolean;
|
||||
|
||||
// Time range
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
|
||||
// Chart types
|
||||
mcpVolumeChartType: ChartType;
|
||||
mcpCostChartType: ChartType;
|
||||
|
||||
// Chart type toggle callbacks
|
||||
onMcpVolumeChartToggle: (type: ChartType) => void;
|
||||
onMcpCostChartToggle: (type: ChartType) => void;
|
||||
}
|
||||
|
||||
export function MCPTab({
|
||||
mcpHistogramData,
|
||||
mcpCostData,
|
||||
mcpTopToolsData,
|
||||
loadingMcpHistogram,
|
||||
loadingMcpCost,
|
||||
loadingMcpTopTools,
|
||||
startTime,
|
||||
endTime,
|
||||
mcpVolumeChartType,
|
||||
mcpCostChartType,
|
||||
onMcpVolumeChartToggle,
|
||||
onMcpCostChartToggle,
|
||||
}: MCPTabProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-2 lg:grid-cols-2 2xl:grid-cols-3">
|
||||
{/* MCP Tool Calls Volume */}
|
||||
<ChartCard
|
||||
title="MCP Tool Calls"
|
||||
loading={loadingMcpHistogram}
|
||||
testId="chart-mcp-volume"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.success }} />
|
||||
<span className="text-muted-foreground">Success</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.error }} />
|
||||
<span className="text-muted-foreground">Error</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ChartTypeToggle
|
||||
chartType={mcpVolumeChartType}
|
||||
onToggle={onMcpVolumeChartToggle}
|
||||
data-testid="dashboard-mcp-volume-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<MCPVolumeChart data={mcpHistogramData} chartType={mcpVolumeChartType} startTime={startTime} endTime={endTime} />
|
||||
</ChartCard>
|
||||
|
||||
{/* MCP Cost */}
|
||||
<ChartCard
|
||||
title="MCP Cost"
|
||||
loading={loadingMcpCost}
|
||||
testId="chart-mcp-cost"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: CHART_COLORS.cost }} />
|
||||
<span className="text-muted-foreground">Cost</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ChartTypeToggle chartType={mcpCostChartType} onToggle={onMcpCostChartToggle} data-testid="dashboard-mcp-cost-chart-toggle" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<MCPCostChart data={mcpCostData} chartType={mcpCostChartType} startTime={startTime} endTime={endTime} />
|
||||
</ChartCard>
|
||||
|
||||
{/* Top 10 MCP Tools */}
|
||||
<ChartCard title="Top 10 MCP Tools" loading={loadingMcpTopTools} testId="chart-mcp-top-tools">
|
||||
<MCPTopToolsChart data={mcpTopToolsData} />
|
||||
</ChartCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
409
ui/app/workspace/dashboard/components/modelRankingsTab.tsx
Normal file
409
ui/app/workspace/dashboard/components/modelRankingsTab.tsx
Normal file
@@ -0,0 +1,409 @@
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import ProviderIcons, { type ProviderIconType, RenderProviderIcon } from "@/lib/constants/icons";
|
||||
import type { ModelHistogramResponse, ModelRankingEntry, ModelRankingsResponse } from "@/lib/types/logs";
|
||||
import { formatCompactNumber as formatNumber } from "@/lib/utils/governance";
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown, Minus } from "lucide-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
import { formatFullTimestamp, formatTimestamp, getModelColor } from "../utils/chartUtils";
|
||||
import { ChartCard } from "./charts/chartCard";
|
||||
import { ChartErrorBoundary } from "./charts/chartErrorBoundary";
|
||||
|
||||
type SortField = "total_requests" | "success_rate" | "total_tokens" | "total_cost" | "avg_latency";
|
||||
type SortOrder = "asc" | "desc";
|
||||
|
||||
interface ModelRankingsTabProps {
|
||||
rankingsData: ModelRankingsResponse | null;
|
||||
loading: boolean;
|
||||
modelData: ModelHistogramResponse | null;
|
||||
loadingModels: boolean;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}
|
||||
|
||||
function formatCost(value: number): string {
|
||||
if (value >= 1) return `$${value.toFixed(2)}`;
|
||||
if (value >= 0.01) return `$${value.toFixed(3)}`;
|
||||
if (value > 0) return `$${value.toFixed(4)}`;
|
||||
return "$0.00";
|
||||
}
|
||||
|
||||
function formatLatency(ms: number): string {
|
||||
if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
|
||||
return `${ms.toFixed(0)}ms`;
|
||||
}
|
||||
|
||||
function TrendBadge({ value, positiveIsGood = true, isNew = false }: { value: number; positiveIsGood?: boolean; isNew?: boolean }) {
|
||||
if (isNew) {
|
||||
return <span className="inline-flex items-center gap-0.5 text-xs font-medium text-blue-600 dark:text-blue-400">new</span>;
|
||||
}
|
||||
|
||||
if (value === 0) {
|
||||
return (
|
||||
<span className="text-muted-foreground inline-flex items-center gap-0.5 text-xs">
|
||||
<Minus className="h-3 w-3" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const isPositive = value > 0;
|
||||
const isGood = positiveIsGood ? isPositive : !isPositive;
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center gap-0.5 text-xs font-medium ${isGood ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400"}`}
|
||||
>
|
||||
{isPositive ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />}
|
||||
{Math.abs(value).toFixed(1)}%
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SortableHeader({
|
||||
label,
|
||||
field,
|
||||
currentSort,
|
||||
currentOrder,
|
||||
onSort,
|
||||
}: {
|
||||
label: string;
|
||||
field: SortField;
|
||||
currentSort: SortField;
|
||||
currentOrder: SortOrder;
|
||||
onSort: (field: SortField) => void;
|
||||
}) {
|
||||
const isActive = currentSort === field;
|
||||
const ariaSort = isActive ? (currentOrder === "asc" ? "ascending" : "descending") : "none";
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`sort-${field}-btn`}
|
||||
aria-sort={ariaSort}
|
||||
className="hover:text-foreground inline-flex items-center gap-1 transition-colors"
|
||||
onClick={() => onSort(field)}
|
||||
>
|
||||
{label}
|
||||
{isActive ? (
|
||||
currentOrder === "desc" ? (
|
||||
<ArrowDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ArrowUp className="h-3 w-3" />
|
||||
)
|
||||
) : (
|
||||
<ArrowUpDown className="text-muted-foreground h-3 w-3" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Tooltip for the usage share chart
|
||||
function UsageShareTooltip({ active, payload, 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">
|
||||
{models.map((model: string, idx: number) => {
|
||||
const val = data[`model_${idx}`];
|
||||
if (!val || val === 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-[140px] truncate text-zinc-600 dark:text-zinc-400">{model}</span>
|
||||
</span>
|
||||
<span className="font-medium">{val.toLocaleString()}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Top Models usage share stacked area chart + ranked legend
|
||||
function TopModelsChart({
|
||||
modelData,
|
||||
loadingModels,
|
||||
rankingsData,
|
||||
startTime,
|
||||
endTime,
|
||||
}: {
|
||||
modelData: ModelHistogramResponse | null;
|
||||
loadingModels: boolean;
|
||||
rankingsData: ModelRankingsResponse | null;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}) {
|
||||
const { chartData, displayModels } = useMemo(() => {
|
||||
if (!modelData?.buckets || !modelData.bucket_size_seconds) {
|
||||
return { chartData: [], displayModels: [] };
|
||||
}
|
||||
|
||||
const models = [...(modelData.models || [])].sort((a, b) => a.localeCompare(b));
|
||||
const processed = modelData.buckets.map((bucket, index) => {
|
||||
const item: any = {
|
||||
...bucket,
|
||||
index,
|
||||
formattedTime: formatTimestamp(bucket.timestamp, modelData.bucket_size_seconds),
|
||||
};
|
||||
for (const [modelIdx, model] of models.entries()) {
|
||||
item[`model_${modelIdx}`] = bucket.by_model?.[model]?.total || 0;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
|
||||
return { chartData: processed, displayModels: models };
|
||||
}, [modelData]);
|
||||
|
||||
// Compute totals per model for the ranked legend (aggregate across providers)
|
||||
const modelTotals = useMemo(() => {
|
||||
if (!rankingsData?.rankings) return [];
|
||||
const byModel = new Map<string, number>();
|
||||
for (const r of rankingsData.rankings) {
|
||||
byModel.set(r.model, (byModel.get(r.model) || 0) + r.total_requests);
|
||||
}
|
||||
const totalRequests = [...byModel.values()].reduce((sum, v) => sum + v, 0);
|
||||
return [...byModel.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([model, total], idx) => ({
|
||||
model,
|
||||
total,
|
||||
pct: totalRequests > 0 ? (total / totalRequests) * 100 : 0,
|
||||
colorIdx: displayModels.indexOf(model) >= 0 ? displayModels.indexOf(model) : idx,
|
||||
}));
|
||||
}, [rankingsData, displayModels]);
|
||||
|
||||
return (
|
||||
<ChartCard title="Top Models" loading={loadingModels} testId="dashboard-rankings-top-models" height="100%" className="z-[1]">
|
||||
<div style={{ height: 200, marginBottom: 6 }}>
|
||||
{chartData.length > 0 ? (
|
||||
<ChartErrorBoundary resetKey={`${startTime}-${endTime}-${chartData.length}`}>
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={chartData} margin={{ top: 6, right: 4, left: 4, bottom: 0 }} 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={48}
|
||||
tickFormatter={(v) => formatNumber(v)}
|
||||
domain={[0, (dataMax: number) => Math.max(dataMax, 1)]}
|
||||
allowDataOverflow={false}
|
||||
/>
|
||||
<Tooltip content={<UsageShareTooltip models={displayModels} />} cursor={{ fill: "#8c8c8f", fillOpacity: 0.15 }} />
|
||||
{displayModels.map((model, idx) => (
|
||||
<Bar
|
||||
key={model}
|
||||
dataKey={`model_${idx}`}
|
||||
stackId="models"
|
||||
fill={getModelColor(idx)}
|
||||
fillOpacity={0.9}
|
||||
isAnimationActive={false}
|
||||
barSize={30}
|
||||
radius={idx === displayModels.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
|
||||
/>
|
||||
))}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</ChartErrorBoundary>
|
||||
) : (
|
||||
<div className="text-muted-foreground flex h-full items-center justify-center text-sm">No data available</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="py-2">
|
||||
{/* Ranked model legend */}
|
||||
{modelTotals.length > 0 && (
|
||||
<div className="mt-3 grid grid-cols-2 gap-x-8 gap-y-1.5 px-2 pb-1">
|
||||
{modelTotals.map((m, idx) => (
|
||||
<div key={m.model} className="flex items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground w-4 text-right text-xs">{idx + 1}.</span>
|
||||
<span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(m.colorIdx) }} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">{m.model}</span>
|
||||
<span className="shrink-0 text-right text-xs tabular-nums">
|
||||
<span className="font-medium">{formatNumber(m.total)}</span>
|
||||
<span className="text-muted-foreground ml-1">{m.pct.toFixed(1)}%</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ChartCard>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelRankingsTab({ rankingsData, loading, modelData, loadingModels, startTime, endTime }: ModelRankingsTabProps) {
|
||||
const [sortField, setSortField] = useState<SortField>("total_requests");
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
|
||||
|
||||
const handleSort = useCallback(
|
||||
(field: SortField) => {
|
||||
if (sortField === field) {
|
||||
setSortOrder((prev) => (prev === "desc" ? "asc" : "desc"));
|
||||
} else {
|
||||
setSortField(field);
|
||||
setSortOrder("desc");
|
||||
}
|
||||
},
|
||||
[sortField],
|
||||
);
|
||||
|
||||
const sortedRankings = useMemo(() => {
|
||||
if (!rankingsData?.rankings) return [];
|
||||
return [...rankingsData.rankings].sort((a, b) => {
|
||||
const aVal = a[sortField];
|
||||
const bVal = b[sortField];
|
||||
return sortOrder === "desc" ? (bVal as number) - (aVal as number) : (aVal as number) - (bVal as number);
|
||||
});
|
||||
}, [rankingsData, sortField, sortOrder]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Top Models chart */}
|
||||
<TopModelsChart
|
||||
modelData={modelData}
|
||||
loadingModels={loadingModels}
|
||||
rankingsData={rankingsData}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
/>
|
||||
|
||||
{/* Rankings table */}
|
||||
{loading ? (
|
||||
<Card className="rounded-sm p-4 shadow-none">
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-6 w-48" />
|
||||
<Skeleton className="h-[300px] w-full" />
|
||||
</div>
|
||||
</Card>
|
||||
) : !rankingsData?.rankings?.length ? (
|
||||
<Card className="rounded-sm p-4 shadow-none">
|
||||
<div className="text-muted-foreground flex h-[200px] items-center justify-center text-sm">
|
||||
No model usage data available for this time period.
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="rounded-sm p-2 shadow-none" data-testid="dashboard-model-rankings-table">
|
||||
<span className="text-primary pl-2 text-sm font-medium">Model Rankings</span>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>Model</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<SortableHeader
|
||||
label="Requests"
|
||||
field="total_requests"
|
||||
currentSort={sortField}
|
||||
currentOrder={sortOrder}
|
||||
onSort={handleSort}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<SortableHeader
|
||||
label="Success Rate"
|
||||
field="success_rate"
|
||||
currentSort={sortField}
|
||||
currentOrder={sortOrder}
|
||||
onSort={handleSort}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<SortableHeader
|
||||
label="Tokens"
|
||||
field="total_tokens"
|
||||
currentSort={sortField}
|
||||
currentOrder={sortOrder}
|
||||
onSort={handleSort}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<SortableHeader label="Cost" field="total_cost" currentSort={sortField} currentOrder={sortOrder} onSort={handleSort} />
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
<SortableHeader
|
||||
label="Avg Latency"
|
||||
field="avg_latency"
|
||||
currentSort={sortField}
|
||||
currentOrder={sortOrder}
|
||||
onSort={handleSort}
|
||||
/>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortedRankings.map((entry: ModelRankingEntry, index: number) => (
|
||||
<TableRow key={`${entry.provider}:${entry.model}`}>
|
||||
<TableCell className="text-muted-foreground font-mono text-xs">{index + 1}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
{entry.provider in ProviderIcons ? (
|
||||
<RenderProviderIcon provider={entry.provider as ProviderIconType} size="xs" className="h-4 w-4 shrink-0" />
|
||||
) : (
|
||||
<span className="text-muted-foreground shrink-0 text-xs">{entry.provider}</span>
|
||||
)}
|
||||
<span className="font-medium">{entry.model}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span>{formatNumber(entry.total_requests)}</span>
|
||||
<TrendBadge value={entry.trend.requests_trend} isNew={!entry.trend.has_previous_period} />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<span
|
||||
className={
|
||||
entry.success_rate >= 99
|
||||
? "text-emerald-600 dark:text-emerald-400"
|
||||
: entry.success_rate >= 95
|
||||
? "text-yellow-600 dark:text-yellow-400"
|
||||
: "text-red-600 dark:text-red-400"
|
||||
}
|
||||
>
|
||||
{entry.success_rate.toFixed(1)}%
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span>{formatNumber(entry.total_tokens)}</span>
|
||||
<TrendBadge value={entry.trend.tokens_trend} isNew={!entry.trend.has_previous_period} />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span>{formatCost(entry.total_cost)}</span>
|
||||
<TrendBadge value={entry.trend.cost_trend} positiveIsGood={false} isNew={!entry.trend.has_previous_period} />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span>{formatLatency(entry.avg_latency)}</span>
|
||||
<TrendBadge value={entry.trend.latency_trend} positiveIsGood={false} isNew={!entry.trend.has_previous_period} />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
482
ui/app/workspace/dashboard/components/overviewTab.tsx
Normal file
482
ui/app/workspace/dashboard/components/overviewTab.tsx
Normal file
@@ -0,0 +1,482 @@
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type {
|
||||
CostHistogramResponse,
|
||||
LatencyHistogramResponse,
|
||||
LogsHistogramResponse,
|
||||
ModelHistogramResponse,
|
||||
TokenHistogramResponse,
|
||||
} from "@/lib/types/logs";
|
||||
import {
|
||||
CHART_COLORS,
|
||||
CHART_HEADER_ACTIONS_CLASS,
|
||||
CHART_HEADER_CONTROLS_CLASS,
|
||||
CHART_HEADER_LEGEND_CLASS,
|
||||
LATENCY_COLORS,
|
||||
getModelColor,
|
||||
} from "../utils/chartUtils";
|
||||
import CacheTokenMeterChart from "./charts/cacheTokenMeterChart";
|
||||
import { ChartCard } from "./charts/chartCard";
|
||||
import { type ChartType, ChartTypeToggle } from "./charts/chartTypeToggle";
|
||||
import { CostChart } from "./charts/costChart";
|
||||
import { LatencyChart } from "./charts/latencyChart";
|
||||
import { LogVolumeChart } from "./charts/logVolumeChart";
|
||||
import { ModelFilterSelect } from "./charts/modelFilterSelect";
|
||||
import { ModelUsageChart } from "./charts/modelUsageChart";
|
||||
import { TokenUsageChart } from "./charts/tokenUsageChart";
|
||||
|
||||
export interface OverviewTabProps {
|
||||
// Data
|
||||
histogramData: LogsHistogramResponse | null;
|
||||
tokenData: TokenHistogramResponse | null;
|
||||
costData: CostHistogramResponse | null;
|
||||
modelData: ModelHistogramResponse | null;
|
||||
latencyData: LatencyHistogramResponse | null;
|
||||
|
||||
// Loading states
|
||||
loadingHistogram: boolean;
|
||||
loadingTokens: boolean;
|
||||
loadingCost: boolean;
|
||||
loadingModels: boolean;
|
||||
loadingLatency: boolean;
|
||||
|
||||
// Time range
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
|
||||
// Chart types
|
||||
volumeChartType: ChartType;
|
||||
tokenChartType: ChartType;
|
||||
costChartType: ChartType;
|
||||
modelChartType: ChartType;
|
||||
latencyChartType: ChartType;
|
||||
|
||||
// Model selections
|
||||
costModel: string;
|
||||
usageModel: string;
|
||||
|
||||
// Derived model lists
|
||||
costModels: string[];
|
||||
usageModels: string[];
|
||||
availableModels: string[];
|
||||
|
||||
// Chart type toggle callbacks
|
||||
onVolumeChartToggle: (type: ChartType) => void;
|
||||
onTokenChartToggle: (type: ChartType) => void;
|
||||
onCostChartToggle: (type: ChartType) => void;
|
||||
onModelChartToggle: (type: ChartType) => void;
|
||||
onLatencyChartToggle: (type: ChartType) => void;
|
||||
|
||||
// Filter callbacks
|
||||
onCostModelChange: (model: string) => void;
|
||||
onUsageModelChange: (model: string) => void;
|
||||
}
|
||||
|
||||
export function OverviewTab({
|
||||
histogramData,
|
||||
tokenData,
|
||||
costData,
|
||||
modelData,
|
||||
latencyData,
|
||||
loadingHistogram,
|
||||
loadingTokens,
|
||||
loadingCost,
|
||||
loadingModels,
|
||||
loadingLatency,
|
||||
startTime,
|
||||
endTime,
|
||||
volumeChartType,
|
||||
tokenChartType,
|
||||
costChartType,
|
||||
modelChartType,
|
||||
latencyChartType,
|
||||
costModel,
|
||||
usageModel,
|
||||
costModels,
|
||||
usageModels,
|
||||
availableModels,
|
||||
onVolumeChartToggle,
|
||||
onTokenChartToggle,
|
||||
onCostChartToggle,
|
||||
onModelChartToggle,
|
||||
onLatencyChartToggle,
|
||||
onCostModelChange,
|
||||
onUsageModelChange,
|
||||
}: OverviewTabProps) {
|
||||
return (
|
||||
<>
|
||||
{/* Charts Grid */}
|
||||
<div className="grid grid-cols-1 gap-2 lg:grid-cols-2 2xl:grid-cols-3">
|
||||
{/* Log Volume Chart */}
|
||||
<ChartCard
|
||||
title="Request Volume"
|
||||
loading={loadingHistogram}
|
||||
testId="chart-log-volume"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.success }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Success</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.error }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Error</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ChartTypeToggle
|
||||
chartType={volumeChartType}
|
||||
onToggle={onVolumeChartToggle}
|
||||
data-testid="dashboard-volume-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<LogVolumeChart
|
||||
data={histogramData}
|
||||
chartType={volumeChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Token Usage Chart */}
|
||||
<ChartCard
|
||||
title="Token Usage"
|
||||
loading={loadingTokens}
|
||||
testId="chart-token-usage"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.promptTokens }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Input</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.completionTokens }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Output</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.cachedReadTokens }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Cached</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ChartTypeToggle
|
||||
chartType={tokenChartType}
|
||||
onToggle={onTokenChartToggle}
|
||||
data-testid="dashboard-token-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<TokenUsageChart
|
||||
data={tokenData}
|
||||
chartType={tokenChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Cache Hit Rate Meter */}
|
||||
<ChartCard
|
||||
title="Cache Hit Rate"
|
||||
loading={loadingTokens}
|
||||
testId="chart-cache-meter"
|
||||
>
|
||||
<CacheTokenMeterChart data={tokenData} />
|
||||
</ChartCard>
|
||||
|
||||
{/* Cost Chart */}
|
||||
<ChartCard
|
||||
title="Cost"
|
||||
loading={loadingCost}
|
||||
testId="chart-cost-total"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
{costModel === "all" ? (
|
||||
costModels.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-testid="cost-legend-trigger"
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: getModelColor(0) }}
|
||||
/>
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">
|
||||
{costModels[0]}
|
||||
</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{costModels[0]}</TooltipContent>
|
||||
</Tooltip>
|
||||
{costModels.length > 1 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-testid="cost-legend-more-trigger"
|
||||
className="text-muted-foreground cursor-default"
|
||||
>
|
||||
+{costModels.length - 1} more
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
{costModels.slice(1).map((model, idx) => (
|
||||
<span
|
||||
key={model}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{
|
||||
backgroundColor: getModelColor(idx + 1),
|
||||
}}
|
||||
/>
|
||||
{model}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-testid="cost-legend-single-trigger"
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: getModelColor(0) }}
|
||||
/>
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">
|
||||
{costModel}
|
||||
</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{costModel}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ModelFilterSelect
|
||||
models={availableModels}
|
||||
selectedModel={costModel}
|
||||
onModelChange={onCostModelChange}
|
||||
data-testid="dashboard-cost-model-filter"
|
||||
/>
|
||||
<ChartTypeToggle
|
||||
chartType={costChartType}
|
||||
onToggle={onCostChartToggle}
|
||||
data-testid="dashboard-cost-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<CostChart
|
||||
data={costData}
|
||||
chartType={costChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
selectedModel={costModel}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Model Usage Chart */}
|
||||
<ChartCard
|
||||
title="Model Usage"
|
||||
loading={loadingModels}
|
||||
testId="chart-model-usage"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
{usageModel === "all" ? (
|
||||
usageModels.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-testid="usage-legend-trigger"
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: getModelColor(0) }}
|
||||
/>
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">
|
||||
{usageModels[0]}
|
||||
</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{usageModels[0]}</TooltipContent>
|
||||
</Tooltip>
|
||||
{usageModels.length > 1 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-testid="usage-legend-more-trigger"
|
||||
className="text-muted-foreground cursor-default"
|
||||
>
|
||||
+{usageModels.length - 1} more
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
{usageModels.slice(1).map((model, idx) => (
|
||||
<span
|
||||
key={model}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{
|
||||
backgroundColor: getModelColor(idx + 1),
|
||||
}}
|
||||
/>
|
||||
{model}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.success }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Success</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: CHART_COLORS.error }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Error</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ModelFilterSelect
|
||||
models={availableModels}
|
||||
selectedModel={usageModel}
|
||||
onModelChange={onUsageModelChange}
|
||||
data-testid="dashboard-usage-model-filter"
|
||||
/>
|
||||
<ChartTypeToggle
|
||||
chartType={modelChartType}
|
||||
onToggle={onModelChartToggle}
|
||||
data-testid="dashboard-usage-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ModelUsageChart
|
||||
data={modelData}
|
||||
chartType={modelChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
selectedModel={usageModel}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Latency Chart */}
|
||||
<ChartCard
|
||||
title="Latency"
|
||||
loading={loadingLatency}
|
||||
testId="chart-latency"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: LATENCY_COLORS.avg }}
|
||||
/>
|
||||
<span className="text-muted-foreground">Avg</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: LATENCY_COLORS.p90 }}
|
||||
/>
|
||||
<span className="text-muted-foreground">P90</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: LATENCY_COLORS.p95 }}
|
||||
/>
|
||||
<span className="text-muted-foreground">P95</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: LATENCY_COLORS.p99 }}
|
||||
/>
|
||||
<span className="text-muted-foreground">P99</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ChartTypeToggle
|
||||
chartType={latencyChartType}
|
||||
onToggle={onLatencyChartToggle}
|
||||
data-testid="dashboard-latency-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<LatencyChart
|
||||
data={latencyData}
|
||||
chartType={latencyChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
/>
|
||||
</ChartCard>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
345
ui/app/workspace/dashboard/components/providerUsageTab.tsx
Normal file
345
ui/app/workspace/dashboard/components/providerUsageTab.tsx
Normal file
@@ -0,0 +1,345 @@
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type { ProviderCostHistogramResponse, ProviderLatencyHistogramResponse, ProviderTokenHistogramResponse } from "@/lib/types/logs";
|
||||
import {
|
||||
CHART_COLORS,
|
||||
CHART_HEADER_ACTIONS_CLASS,
|
||||
CHART_HEADER_CONTROLS_CLASS,
|
||||
CHART_HEADER_LEGEND_CLASS,
|
||||
LATENCY_COLORS,
|
||||
getModelColor,
|
||||
} from "../utils/chartUtils";
|
||||
import { ChartCard } from "./charts/chartCard";
|
||||
import { type ChartType, ChartTypeToggle } from "./charts/chartTypeToggle";
|
||||
import { ProviderCostChart } from "./charts/providerCostChart";
|
||||
import { ProviderFilterSelect } from "./charts/providerFilterSelect";
|
||||
import { ProviderLatencyChart } from "./charts/providerLatencyChart";
|
||||
import { ProviderTokenChart } from "./charts/providerTokenChart";
|
||||
|
||||
export interface ProviderUsageTabProps {
|
||||
// Data
|
||||
providerCostData: ProviderCostHistogramResponse | null;
|
||||
providerTokenData: ProviderTokenHistogramResponse | null;
|
||||
providerLatencyData: ProviderLatencyHistogramResponse | null;
|
||||
|
||||
// Loading states
|
||||
loadingProviderCost: boolean;
|
||||
loadingProviderTokens: boolean;
|
||||
loadingProviderLatency: boolean;
|
||||
|
||||
// Time range
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
|
||||
// Chart types
|
||||
providerCostChartType: ChartType;
|
||||
providerTokenChartType: ChartType;
|
||||
providerLatencyChartType: ChartType;
|
||||
|
||||
// Provider selections
|
||||
providerCostProvider: string;
|
||||
providerTokenProvider: string;
|
||||
providerLatencyProvider: string;
|
||||
|
||||
// Derived provider lists
|
||||
availableProviders: string[];
|
||||
providerCostProviders: string[];
|
||||
providerTokenProviders: string[];
|
||||
providerLatencyProviders: string[];
|
||||
|
||||
// Chart type toggle callbacks
|
||||
onProviderCostChartToggle: (type: ChartType) => void;
|
||||
onProviderTokenChartToggle: (type: ChartType) => void;
|
||||
onProviderLatencyChartToggle: (type: ChartType) => void;
|
||||
|
||||
// Filter callbacks
|
||||
onProviderCostProviderChange: (provider: string) => void;
|
||||
onProviderTokenProviderChange: (provider: string) => void;
|
||||
onProviderLatencyProviderChange: (provider: string) => void;
|
||||
}
|
||||
|
||||
export function ProviderUsageTab({
|
||||
providerCostData,
|
||||
providerTokenData,
|
||||
providerLatencyData,
|
||||
loadingProviderCost,
|
||||
loadingProviderTokens,
|
||||
loadingProviderLatency,
|
||||
startTime,
|
||||
endTime,
|
||||
providerCostChartType,
|
||||
providerTokenChartType,
|
||||
providerLatencyChartType,
|
||||
providerCostProvider,
|
||||
providerTokenProvider,
|
||||
providerLatencyProvider,
|
||||
availableProviders,
|
||||
providerCostProviders,
|
||||
providerTokenProviders,
|
||||
providerLatencyProviders,
|
||||
onProviderCostChartToggle,
|
||||
onProviderTokenChartToggle,
|
||||
onProviderLatencyChartToggle,
|
||||
onProviderCostProviderChange,
|
||||
onProviderTokenProviderChange,
|
||||
onProviderLatencyProviderChange,
|
||||
}: ProviderUsageTabProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-2 lg:grid-cols-2 2xl:grid-cols-3">
|
||||
{/* Provider Cost Chart */}
|
||||
<ChartCard
|
||||
title="Provider Cost"
|
||||
loading={loadingProviderCost}
|
||||
testId="chart-provider-cost"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
{providerCostProvider === "all" ? (
|
||||
providerCostProviders.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span data-testid="provider-cost-legend-trigger" className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">{providerCostProviders[0]}</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{providerCostProviders[0]}</TooltipContent>
|
||||
</Tooltip>
|
||||
{providerCostProviders.length > 1 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="provider-cost-legend-more-trigger"
|
||||
className="text-muted-foreground cursor-default"
|
||||
>
|
||||
+{providerCostProviders.length - 1} more
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
{providerCostProviders.slice(1).map((provider, idx) => (
|
||||
<span key={provider} className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(idx + 1) }} />
|
||||
{provider}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span data-testid="provider-cost-legend-single-trigger" className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">{providerCostProvider}</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{providerCostProvider}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ProviderFilterSelect
|
||||
providers={availableProviders}
|
||||
selectedProvider={providerCostProvider}
|
||||
onProviderChange={onProviderCostProviderChange}
|
||||
data-testid="dashboard-provider-cost-filter"
|
||||
/>
|
||||
<ChartTypeToggle
|
||||
chartType={providerCostChartType}
|
||||
onToggle={onProviderCostChartToggle}
|
||||
data-testid="dashboard-provider-cost-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ProviderCostChart
|
||||
data={providerCostData}
|
||||
chartType={providerCostChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
selectedProvider={providerCostProvider}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Provider Token Usage Chart */}
|
||||
<ChartCard
|
||||
title="Provider Token Usage"
|
||||
loading={loadingProviderTokens}
|
||||
testId="chart-provider-tokens"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
{providerTokenProvider === "all" ? (
|
||||
providerTokenProviders.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span data-testid="provider-token-legend-trigger" className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">{providerTokenProviders[0]}</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{providerTokenProviders[0]}</TooltipContent>
|
||||
</Tooltip>
|
||||
{providerTokenProviders.length > 1 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="provider-token-legend-more-trigger"
|
||||
className="text-muted-foreground cursor-default"
|
||||
>
|
||||
+{providerTokenProviders.length - 1} more
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
{providerTokenProviders.slice(1).map((provider, idx) => (
|
||||
<span key={provider} className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(idx + 1) }} />
|
||||
{provider}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: CHART_COLORS.promptTokens }} />
|
||||
<span className="text-muted-foreground">Input</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: CHART_COLORS.completionTokens }} />
|
||||
<span className="text-muted-foreground">Output</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ProviderFilterSelect
|
||||
providers={availableProviders}
|
||||
selectedProvider={providerTokenProvider}
|
||||
onProviderChange={onProviderTokenProviderChange}
|
||||
data-testid="dashboard-provider-token-filter"
|
||||
/>
|
||||
<ChartTypeToggle
|
||||
chartType={providerTokenChartType}
|
||||
onToggle={onProviderTokenChartToggle}
|
||||
data-testid="dashboard-provider-token-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ProviderTokenChart
|
||||
data={providerTokenData}
|
||||
chartType={providerTokenChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
selectedProvider={providerTokenProvider}
|
||||
/>
|
||||
</ChartCard>
|
||||
|
||||
{/* Provider Latency Chart */}
|
||||
<ChartCard
|
||||
title="Provider Latency"
|
||||
loading={loadingProviderLatency}
|
||||
testId="chart-provider-latency"
|
||||
headerActions={
|
||||
<div className={CHART_HEADER_ACTIONS_CLASS}>
|
||||
<div className={CHART_HEADER_LEGEND_CLASS}>
|
||||
{providerLatencyProvider === "all" ? (
|
||||
providerLatencyProviders.length > 0 && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span data-testid="provider-latency-legend-trigger" className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(0) }} />
|
||||
<span className="text-muted-foreground max-w-[100px] truncate">{providerLatencyProviders[0]}</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{providerLatencyProviders[0]}</TooltipContent>
|
||||
</Tooltip>
|
||||
{providerLatencyProviders.length > 1 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="provider-latency-legend-more-trigger"
|
||||
className="text-muted-foreground cursor-default"
|
||||
>
|
||||
+{providerLatencyProviders.length - 1} more
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
{providerLatencyProviders.slice(1).map((provider, idx) => (
|
||||
<span key={provider} className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: getModelColor(idx + 1) }} />
|
||||
{provider}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.avg }} />
|
||||
<span className="text-muted-foreground">Avg</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p90 }} />
|
||||
<span className="text-muted-foreground">P90</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p95 }} />
|
||||
<span className="text-muted-foreground">P95</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: LATENCY_COLORS.p99 }} />
|
||||
<span className="text-muted-foreground">P99</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className={CHART_HEADER_CONTROLS_CLASS}>
|
||||
<ProviderFilterSelect
|
||||
providers={availableProviders}
|
||||
selectedProvider={providerLatencyProvider}
|
||||
onProviderChange={onProviderLatencyProviderChange}
|
||||
data-testid="dashboard-provider-latency-filter"
|
||||
/>
|
||||
<ChartTypeToggle
|
||||
chartType={providerLatencyChartType}
|
||||
onToggle={onProviderLatencyChartToggle}
|
||||
data-testid="dashboard-provider-latency-chart-toggle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ProviderLatencyChart
|
||||
data={providerLatencyData}
|
||||
chartType={providerLatencyChartType}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
selectedProvider={providerLatencyProvider}
|
||||
/>
|
||||
</ChartCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
16
ui/app/workspace/dashboard/layout.tsx
Normal file
16
ui/app/workspace/dashboard/layout.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { NoPermissionView } from "@/components/noPermissionView";
|
||||
import { RbacOperation, RbacResource, useRbac } from "@enterprise/lib";
|
||||
import DashboardPage from "./page";
|
||||
|
||||
function RouteComponent() {
|
||||
const hasObservabilityAccess = useRbac(RbacResource.Observability, RbacOperation.View);
|
||||
if (!hasObservabilityAccess) {
|
||||
return <NoPermissionView entity="dashboard" />;
|
||||
}
|
||||
return <DashboardPage />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/workspace/dashboard")({
|
||||
component: RouteComponent,
|
||||
});
|
||||
901
ui/app/workspace/dashboard/page.tsx
Normal file
901
ui/app/workspace/dashboard/page.tsx
Normal file
@@ -0,0 +1,901 @@
|
||||
import { LogsFilterSidebar } from "@/components/filters/logsFilterSidebar";
|
||||
import { DateTimePickerWithRange } from "@/components/ui/datePickerWithRange";
|
||||
import { ScrollArea } from "@/components/ui/scrollArea";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
useGetMCPAvailableFilterDataQuery,
|
||||
useLazyGetLogsCostHistogramQuery,
|
||||
useLazyGetLogsHistogramQuery,
|
||||
useLazyGetLogsLatencyHistogramQuery,
|
||||
useLazyGetLogsModelHistogramQuery,
|
||||
useLazyGetLogsProviderCostHistogramQuery,
|
||||
useLazyGetLogsProviderLatencyHistogramQuery,
|
||||
useLazyGetLogsProviderTokenHistogramQuery,
|
||||
useLazyGetLogsTokenHistogramQuery,
|
||||
useLazyGetMCPCostHistogramQuery,
|
||||
useLazyGetMCPHistogramQuery,
|
||||
useLazyGetMCPTopToolsQuery,
|
||||
useLazyGetModelRankingsQuery,
|
||||
} from "@/lib/store";
|
||||
import type {
|
||||
CostHistogramResponse,
|
||||
LatencyHistogramResponse,
|
||||
LogFilters,
|
||||
LogsHistogramResponse,
|
||||
MCPCostHistogramResponse,
|
||||
MCPHistogramResponse,
|
||||
MCPToolLogFilters,
|
||||
MCPTopToolsResponse,
|
||||
ModelHistogramResponse,
|
||||
ModelRankingsResponse,
|
||||
ProviderCostHistogramResponse,
|
||||
ProviderLatencyHistogramResponse,
|
||||
ProviderTokenHistogramResponse,
|
||||
TokenHistogramResponse,
|
||||
} from "@/lib/types/logs";
|
||||
import { dateUtils } from "@/lib/types/logs";
|
||||
import { getRangeForPeriod, TIME_PERIODS } from "@/lib/utils/timeRange";
|
||||
import UserRankingsTab from "@enterprise/components/user-rankings/userRankingsTab";
|
||||
import { useLocation } from "@tanstack/react-router";
|
||||
import { parseAsInteger, parseAsString, useQueryStates } from "nuqs";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { type ChartType } from "./components/charts/chartTypeToggle";
|
||||
import { ModelFilterSelect } from "./components/charts/modelFilterSelect";
|
||||
import { ExportPopover } from "./components/exportPopover";
|
||||
import { MCPTab } from "./components/mcpTab";
|
||||
import { ModelRankingsTab } from "./components/modelRankingsTab";
|
||||
import { OverviewTab } from "./components/overviewTab";
|
||||
import { ProviderUsageTab } from "./components/providerUsageTab";
|
||||
|
||||
// Type-safe parser for chart type URL state
|
||||
const toChartType = (value: string): ChartType => (value === "line" ? "line" : "bar");
|
||||
|
||||
const parseCsvParam = (value: string): string[] => (value ? value.split(",").filter(Boolean) : []);
|
||||
const sanitizeSeriesLabels = (values?: string[]): string[] => {
|
||||
if (!values) return [];
|
||||
const trimmedValues = values.map((value) => value.trim()).filter((value) => value.length > 0);
|
||||
|
||||
return [...new Set(trimmedValues)];
|
||||
};
|
||||
|
||||
export default function DashboardPage() {
|
||||
// Data states - Overview
|
||||
const [histogramData, setHistogramData] = useState<LogsHistogramResponse | null>(null);
|
||||
const [tokenData, setTokenData] = useState<TokenHistogramResponse | null>(null);
|
||||
const [costData, setCostData] = useState<CostHistogramResponse | null>(null);
|
||||
const [modelData, setModelData] = useState<ModelHistogramResponse | null>(null);
|
||||
const [latencyData, setLatencyData] = useState<LatencyHistogramResponse | null>(null);
|
||||
const [providerCostData, setProviderCostData] = useState<ProviderCostHistogramResponse | null>(null);
|
||||
const [providerTokenData, setProviderTokenData] = useState<ProviderTokenHistogramResponse | null>(null);
|
||||
const [providerLatencyData, setProviderLatencyData] = useState<ProviderLatencyHistogramResponse | null>(null);
|
||||
|
||||
// Data states - MCP
|
||||
const [mcpHistogramData, setMcpHistogramData] = useState<MCPHistogramResponse | null>(null);
|
||||
const [mcpCostData, setMcpCostData] = useState<MCPCostHistogramResponse | null>(null);
|
||||
const [mcpTopToolsData, setMcpTopToolsData] = useState<MCPTopToolsResponse | null>(null);
|
||||
|
||||
// Data states - Rankings
|
||||
const [rankingsData, setRankingsData] = useState<ModelRankingsResponse | null>(null);
|
||||
|
||||
// Loading states - Overview
|
||||
const [loadingHistogram, setLoadingHistogram] = useState(true);
|
||||
const [loadingTokens, setLoadingTokens] = useState(true);
|
||||
const [loadingCost, setLoadingCost] = useState(true);
|
||||
const [loadingModels, setLoadingModels] = useState(true);
|
||||
const [loadingLatency, setLoadingLatency] = useState(true);
|
||||
const [loadingProviderCost, setLoadingProviderCost] = useState(true);
|
||||
const [loadingProviderTokens, setLoadingProviderTokens] = useState(true);
|
||||
const [loadingProviderLatency, setLoadingProviderLatency] = useState(true);
|
||||
|
||||
// Loading states - MCP
|
||||
const [loadingMcpHistogram, setLoadingMcpHistogram] = useState(true);
|
||||
const [loadingMcpCost, setLoadingMcpCost] = useState(true);
|
||||
const [loadingMcpTopTools, setLoadingMcpTopTools] = useState(true);
|
||||
|
||||
// Loading states - Rankings
|
||||
const [loadingRankings, setLoadingRankings] = useState(true);
|
||||
|
||||
// RTK Query lazy hooks - Overview
|
||||
const [triggerHistogram] = useLazyGetLogsHistogramQuery({});
|
||||
const [triggerTokens] = useLazyGetLogsTokenHistogramQuery();
|
||||
const [triggerCost] = useLazyGetLogsCostHistogramQuery();
|
||||
const [triggerModels] = useLazyGetLogsModelHistogramQuery();
|
||||
const [triggerLatency] = useLazyGetLogsLatencyHistogramQuery();
|
||||
const [triggerProviderCost] = useLazyGetLogsProviderCostHistogramQuery();
|
||||
const [triggerProviderTokens] = useLazyGetLogsProviderTokenHistogramQuery();
|
||||
const [triggerProviderLatency] = useLazyGetLogsProviderLatencyHistogramQuery();
|
||||
|
||||
// RTK Query lazy hooks - MCP
|
||||
const [triggerMcpHistogram] = useLazyGetMCPHistogramQuery();
|
||||
const [triggerMcpCost] = useLazyGetMCPCostHistogramQuery();
|
||||
const [triggerMcpTopTools] = useLazyGetMCPTopToolsQuery();
|
||||
|
||||
// RTK Query lazy hooks - Rankings
|
||||
const [triggerRankings] = useLazyGetModelRankingsQuery();
|
||||
|
||||
// MCP filter data
|
||||
const { data: mcpFilterData } = useGetMCPAvailableFilterDataQuery();
|
||||
|
||||
// Memoize default time range to prevent recalculation on every render
|
||||
// This is crucial to avoid triggering refetches when the sheet opens/closes
|
||||
const defaultTimeRange = useMemo(() => dateUtils.getDefaultTimeRange(), []);
|
||||
|
||||
const { search } = useLocation();
|
||||
const hasExplicitTimeRange = (search as Record<string, unknown>)?.start_time && (search as Record<string, unknown>)?.end_time;
|
||||
// URL state management
|
||||
const [urlState, setUrlState] = useQueryStates(
|
||||
{
|
||||
period: parseAsString.withDefault(hasExplicitTimeRange ? "" : "1h").withOptions({ clearOnDefault: false }),
|
||||
start_time: parseAsInteger.withDefault(defaultTimeRange.startTime),
|
||||
end_time: parseAsInteger.withDefault(defaultTimeRange.endTime),
|
||||
tab: parseAsString.withDefault("overview"),
|
||||
virtual_key_ids: parseAsString.withDefault(""),
|
||||
providers: parseAsString.withDefault(""),
|
||||
models: parseAsString.withDefault(""),
|
||||
selected_key_ids: parseAsString.withDefault(""),
|
||||
objects: parseAsString.withDefault(""),
|
||||
status: parseAsString.withDefault(""),
|
||||
routing_rule_ids: parseAsString.withDefault(""),
|
||||
routing_engine_used: parseAsString.withDefault(""),
|
||||
missing_cost_only: parseAsString.withDefault("false"),
|
||||
metadata_filters: parseAsString.withDefault(""),
|
||||
volume_chart: parseAsString.withDefault("bar"),
|
||||
token_chart: parseAsString.withDefault("bar"),
|
||||
cost_chart: parseAsString.withDefault("bar"),
|
||||
model_chart: parseAsString.withDefault("bar"),
|
||||
latency_chart: parseAsString.withDefault("bar"),
|
||||
cost_model: parseAsString.withDefault("all"),
|
||||
usage_model: parseAsString.withDefault("all"),
|
||||
provider_cost_chart: parseAsString.withDefault("bar"),
|
||||
provider_token_chart: parseAsString.withDefault("bar"),
|
||||
provider_latency_chart: parseAsString.withDefault("bar"),
|
||||
provider_cost_provider: parseAsString.withDefault("all"),
|
||||
provider_token_provider: parseAsString.withDefault("all"),
|
||||
provider_latency_provider: parseAsString.withDefault("all"),
|
||||
mcp_volume_chart: parseAsString.withDefault("bar"),
|
||||
mcp_cost_chart: parseAsString.withDefault("bar"),
|
||||
mcp_tool_names: parseAsString.withDefault(""),
|
||||
mcp_server_labels: parseAsString.withDefault(""),
|
||||
},
|
||||
{
|
||||
history: "push",
|
||||
shallow: false,
|
||||
},
|
||||
);
|
||||
|
||||
// Parse filter arrays from URL state
|
||||
const selectedProviders = useMemo(() => parseCsvParam(urlState.providers), [urlState.providers]);
|
||||
const selectedModels = useMemo(() => parseCsvParam(urlState.models), [urlState.models]);
|
||||
const selectedKeyIds = useMemo(() => parseCsvParam(urlState.selected_key_ids), [urlState.selected_key_ids]);
|
||||
const selectedVirtualKeyIds = useMemo(() => parseCsvParam(urlState.virtual_key_ids), [urlState.virtual_key_ids]);
|
||||
const selectedTypes = useMemo(() => parseCsvParam(urlState.objects), [urlState.objects]);
|
||||
const selectedStatuses = useMemo(() => parseCsvParam(urlState.status), [urlState.status]);
|
||||
const selectedRoutingRuleIds = useMemo(() => parseCsvParam(urlState.routing_rule_ids), [urlState.routing_rule_ids]);
|
||||
const selectedRoutingEngines = useMemo(() => parseCsvParam(urlState.routing_engine_used), [urlState.routing_engine_used]);
|
||||
const missingCostOnly = useMemo(() => urlState.missing_cost_only === "true", [urlState.missing_cost_only]);
|
||||
const metadataFilters = useMemo(() => {
|
||||
if (!urlState.metadata_filters) return undefined;
|
||||
try {
|
||||
return JSON.parse(urlState.metadata_filters) as Record<string, string>;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, [urlState.metadata_filters]);
|
||||
|
||||
// MCP filter arrays
|
||||
const selectedMcpToolNames = useMemo(() => parseCsvParam(urlState.mcp_tool_names), [urlState.mcp_tool_names]);
|
||||
const selectedMcpServerLabels = useMemo(() => parseCsvParam(urlState.mcp_server_labels), [urlState.mcp_server_labels]);
|
||||
|
||||
// Derived filter for API calls
|
||||
const filters: LogFilters = useMemo(
|
||||
() => ({
|
||||
start_time: dateUtils.toISOString(urlState.start_time),
|
||||
end_time: dateUtils.toISOString(urlState.end_time),
|
||||
...(selectedProviders.length > 0 && { providers: selectedProviders }),
|
||||
...(selectedModels.length > 0 && { models: selectedModels }),
|
||||
...(selectedKeyIds.length > 0 && { selected_key_ids: selectedKeyIds }),
|
||||
...(selectedVirtualKeyIds.length > 0 && {
|
||||
virtual_key_ids: selectedVirtualKeyIds,
|
||||
}),
|
||||
...(selectedTypes.length > 0 && { objects: selectedTypes }),
|
||||
...(selectedStatuses.length > 0 && { status: selectedStatuses }),
|
||||
...(selectedRoutingRuleIds.length > 0 && {
|
||||
routing_rule_ids: selectedRoutingRuleIds,
|
||||
}),
|
||||
...(selectedRoutingEngines.length > 0 && {
|
||||
routing_engine_used: selectedRoutingEngines,
|
||||
}),
|
||||
...(missingCostOnly && { missing_cost_only: true }),
|
||||
...(metadataFilters &&
|
||||
Object.keys(metadataFilters).length > 0 && {
|
||||
metadata_filters: metadataFilters,
|
||||
}),
|
||||
}),
|
||||
[
|
||||
urlState.start_time,
|
||||
urlState.end_time,
|
||||
selectedProviders,
|
||||
selectedModels,
|
||||
selectedKeyIds,
|
||||
selectedVirtualKeyIds,
|
||||
selectedTypes,
|
||||
selectedStatuses,
|
||||
selectedRoutingRuleIds,
|
||||
selectedRoutingEngines,
|
||||
missingCostOnly,
|
||||
metadataFilters,
|
||||
],
|
||||
);
|
||||
|
||||
// MCP filters
|
||||
const mcpFilters: MCPToolLogFilters = useMemo(
|
||||
() => ({
|
||||
start_time: dateUtils.toISOString(urlState.start_time),
|
||||
end_time: dateUtils.toISOString(urlState.end_time),
|
||||
...(selectedMcpToolNames.length > 0 && {
|
||||
tool_names: selectedMcpToolNames,
|
||||
}),
|
||||
...(selectedMcpServerLabels.length > 0 && {
|
||||
server_labels: selectedMcpServerLabels,
|
||||
}),
|
||||
}),
|
||||
[urlState.start_time, urlState.end_time, selectedMcpToolNames, selectedMcpServerLabels],
|
||||
);
|
||||
|
||||
// Model lists for each chart's legend (must match what the chart component actually renders)
|
||||
const costModels = useMemo(() => sanitizeSeriesLabels(costData?.models), [costData?.models]);
|
||||
const usageModels = useMemo(() => sanitizeSeriesLabels(modelData?.models), [modelData?.models]);
|
||||
|
||||
// Available models for filter dropdowns (union of both sources)
|
||||
const availableModels = useMemo(() => {
|
||||
return sanitizeSeriesLabels([...(costData?.models ?? []), ...(modelData?.models ?? [])]);
|
||||
}, [costData?.models, modelData?.models]);
|
||||
|
||||
// Available providers for provider chart filter dropdowns
|
||||
const availableProviders = useMemo(() => {
|
||||
return sanitizeSeriesLabels([
|
||||
...(providerCostData?.providers ?? []),
|
||||
...(providerTokenData?.providers ?? []),
|
||||
...(providerLatencyData?.providers ?? []),
|
||||
]);
|
||||
}, [providerCostData?.providers, providerTokenData?.providers, providerLatencyData?.providers]);
|
||||
|
||||
// Provider lists for each chart's legend
|
||||
const providerCostProviders = useMemo(() => sanitizeSeriesLabels(providerCostData?.providers), [providerCostData?.providers]);
|
||||
const providerTokenProviders = useMemo(() => sanitizeSeriesLabels(providerTokenData?.providers), [providerTokenData?.providers]);
|
||||
const providerLatencyProviders = useMemo(() => sanitizeSeriesLabels(providerLatencyData?.providers), [providerLatencyData?.providers]);
|
||||
|
||||
// Fetch Overview tab data (5 calls)
|
||||
const fetchOverviewData = useCallback(async () => {
|
||||
setLoadingHistogram(true);
|
||||
setLoadingTokens(true);
|
||||
setLoadingCost(true);
|
||||
setLoadingModels(true);
|
||||
setLoadingLatency(true);
|
||||
|
||||
const fetchFilters = { filters };
|
||||
|
||||
const [histogramResult, tokenResult, costResult, modelResult, latencyResult] = await Promise.all([
|
||||
triggerHistogram(fetchFilters, false),
|
||||
triggerTokens(fetchFilters, false),
|
||||
triggerCost(fetchFilters, false),
|
||||
triggerModels(fetchFilters, false),
|
||||
triggerLatency(fetchFilters, false),
|
||||
]);
|
||||
|
||||
setHistogramData(histogramResult.data ?? null);
|
||||
setLoadingHistogram(false);
|
||||
setTokenData(tokenResult.data ?? null);
|
||||
setLoadingTokens(false);
|
||||
setCostData(costResult.data ?? null);
|
||||
setLoadingCost(false);
|
||||
setModelData(modelResult.data ?? null);
|
||||
setLoadingModels(false);
|
||||
setLatencyData(latencyResult.data ?? null);
|
||||
setLoadingLatency(false);
|
||||
}, [filters, triggerHistogram, triggerTokens, triggerCost, triggerModels, triggerLatency]);
|
||||
|
||||
// Fetch Provider Usage tab data (3 calls)
|
||||
const fetchProviderData = useCallback(async () => {
|
||||
setLoadingProviderCost(true);
|
||||
setLoadingProviderTokens(true);
|
||||
setLoadingProviderLatency(true);
|
||||
|
||||
const fetchFilters = { filters };
|
||||
|
||||
const [providerCostResult, providerTokenResult, providerLatencyResult] = await Promise.all([
|
||||
triggerProviderCost(fetchFilters, false),
|
||||
triggerProviderTokens(fetchFilters, false),
|
||||
triggerProviderLatency(fetchFilters, false),
|
||||
]);
|
||||
|
||||
setProviderCostData(providerCostResult.data ?? null);
|
||||
setLoadingProviderCost(false);
|
||||
setProviderTokenData(providerTokenResult.data ?? null);
|
||||
setLoadingProviderTokens(false);
|
||||
setProviderLatencyData(providerLatencyResult.data ?? null);
|
||||
setLoadingProviderLatency(false);
|
||||
}, [filters, triggerProviderCost, triggerProviderTokens, triggerProviderLatency]);
|
||||
|
||||
// Fetch MCP data
|
||||
const fetchMcpData = useCallback(async () => {
|
||||
setLoadingMcpHistogram(true);
|
||||
setLoadingMcpCost(true);
|
||||
setLoadingMcpTopTools(true);
|
||||
|
||||
const fetchFilters = { filters: mcpFilters };
|
||||
|
||||
const [mcpHistResult, mcpCostResult, mcpTopToolsResult] = await Promise.all([
|
||||
triggerMcpHistogram(fetchFilters, false),
|
||||
triggerMcpCost(fetchFilters, false),
|
||||
triggerMcpTopTools(fetchFilters, false),
|
||||
]);
|
||||
|
||||
setMcpHistogramData(mcpHistResult.data ?? null);
|
||||
setLoadingMcpHistogram(false);
|
||||
setMcpCostData(mcpCostResult.data ?? null);
|
||||
setLoadingMcpCost(false);
|
||||
setMcpTopToolsData(mcpTopToolsResult.data ?? null);
|
||||
setLoadingMcpTopTools(false);
|
||||
}, [mcpFilters, triggerMcpHistogram, triggerMcpCost, triggerMcpTopTools]);
|
||||
|
||||
// Fetch Rankings data
|
||||
const fetchRankingsData = useCallback(async () => {
|
||||
setLoadingRankings(true);
|
||||
const result = await triggerRankings({ filters }, false);
|
||||
setRankingsData(result.data ?? null);
|
||||
setLoadingRankings(false);
|
||||
}, [filters, triggerRankings]);
|
||||
|
||||
// --- Lazy-load refs: each tab fetches only once per filter change ---
|
||||
const overviewFetchedRef = useRef(false);
|
||||
const overviewLoadingRef = useRef(false);
|
||||
const overviewGenRef = useRef(0);
|
||||
const overviewPromiseRef = useRef<Promise<void> | null>(null);
|
||||
|
||||
const providerFetchedRef = useRef(false);
|
||||
const providerLoadingRef = useRef(false);
|
||||
const providerGenRef = useRef(0);
|
||||
const providerPromiseRef = useRef<Promise<void> | null>(null);
|
||||
|
||||
const mcpFetchedRef = useRef(false);
|
||||
const mcpLoadingRef = useRef(false);
|
||||
const mcpGenRef = useRef(0);
|
||||
const mcpPromiseRef = useRef<Promise<void> | null>(null);
|
||||
|
||||
const rankingsFetchedRef = useRef(false);
|
||||
const rankingsLoadingRef = useRef(false);
|
||||
const rankingsGenRef = useRef(0);
|
||||
const rankingsPromiseRef = useRef<Promise<void> | null>(null);
|
||||
|
||||
const ensureOverviewDataLoaded = useCallback(async () => {
|
||||
if (overviewFetchedRef.current) return;
|
||||
if (overviewLoadingRef.current) return overviewPromiseRef.current ?? undefined;
|
||||
const gen = overviewGenRef.current;
|
||||
overviewLoadingRef.current = true;
|
||||
const promise = fetchOverviewData()
|
||||
.then(() => {
|
||||
if (gen === overviewGenRef.current) overviewFetchedRef.current = true;
|
||||
})
|
||||
.finally(() => {
|
||||
if (gen === overviewGenRef.current) {
|
||||
overviewLoadingRef.current = false;
|
||||
overviewPromiseRef.current = null;
|
||||
}
|
||||
});
|
||||
overviewPromiseRef.current = promise;
|
||||
return promise;
|
||||
}, [fetchOverviewData]);
|
||||
|
||||
const ensureProviderDataLoaded = useCallback(async () => {
|
||||
if (providerFetchedRef.current) return;
|
||||
if (providerLoadingRef.current) return providerPromiseRef.current ?? undefined;
|
||||
const gen = providerGenRef.current;
|
||||
providerLoadingRef.current = true;
|
||||
const promise = fetchProviderData()
|
||||
.then(() => {
|
||||
if (gen === providerGenRef.current) providerFetchedRef.current = true;
|
||||
})
|
||||
.finally(() => {
|
||||
if (gen === providerGenRef.current) {
|
||||
providerLoadingRef.current = false;
|
||||
providerPromiseRef.current = null;
|
||||
}
|
||||
});
|
||||
providerPromiseRef.current = promise;
|
||||
return promise;
|
||||
}, [fetchProviderData]);
|
||||
|
||||
const ensureMcpDataLoaded = useCallback(async () => {
|
||||
if (mcpFetchedRef.current) return;
|
||||
if (mcpLoadingRef.current) return mcpPromiseRef.current ?? undefined;
|
||||
const gen = mcpGenRef.current;
|
||||
mcpLoadingRef.current = true;
|
||||
const promise = fetchMcpData()
|
||||
.then(() => {
|
||||
if (gen === mcpGenRef.current) mcpFetchedRef.current = true;
|
||||
})
|
||||
.finally(() => {
|
||||
if (gen === mcpGenRef.current) {
|
||||
mcpLoadingRef.current = false;
|
||||
mcpPromiseRef.current = null;
|
||||
}
|
||||
});
|
||||
mcpPromiseRef.current = promise;
|
||||
return promise;
|
||||
}, [fetchMcpData]);
|
||||
|
||||
const ensureRankingsDataLoaded = useCallback(async () => {
|
||||
if (rankingsFetchedRef.current) return;
|
||||
if (rankingsLoadingRef.current) return rankingsPromiseRef.current ?? undefined;
|
||||
const gen = rankingsGenRef.current;
|
||||
rankingsLoadingRef.current = true;
|
||||
const promise = fetchRankingsData()
|
||||
.then(() => {
|
||||
if (gen === rankingsGenRef.current) rankingsFetchedRef.current = true;
|
||||
})
|
||||
.finally(() => {
|
||||
if (gen === rankingsGenRef.current) {
|
||||
rankingsLoadingRef.current = false;
|
||||
rankingsPromiseRef.current = null;
|
||||
}
|
||||
});
|
||||
rankingsPromiseRef.current = promise;
|
||||
return promise;
|
||||
}, [fetchRankingsData]);
|
||||
|
||||
// Reset all lazy-load flags when filters change (not on tab switch)
|
||||
useEffect(() => {
|
||||
overviewFetchedRef.current = false;
|
||||
overviewLoadingRef.current = false;
|
||||
overviewGenRef.current += 1;
|
||||
providerFetchedRef.current = false;
|
||||
providerLoadingRef.current = false;
|
||||
providerGenRef.current += 1;
|
||||
rankingsFetchedRef.current = false;
|
||||
rankingsLoadingRef.current = false;
|
||||
rankingsGenRef.current += 1;
|
||||
}, [filters]);
|
||||
|
||||
useEffect(() => {
|
||||
mcpFetchedRef.current = false;
|
||||
mcpLoadingRef.current = false;
|
||||
mcpGenRef.current += 1;
|
||||
}, [mcpFilters]);
|
||||
|
||||
// Fetch current tab's data when filters change or tab switches
|
||||
// The ensure* functions are no-ops if data is already loaded for the current filters
|
||||
useEffect(() => {
|
||||
const tab = urlState.tab || "overview";
|
||||
if (tab === "overview") void ensureOverviewDataLoaded();
|
||||
else if (tab === "provider-usage") void ensureProviderDataLoaded();
|
||||
else if (tab === "rankings") void ensureRankingsDataLoaded();
|
||||
else if (tab === "mcp") void ensureMcpDataLoaded();
|
||||
}, [urlState.tab, ensureOverviewDataLoaded, ensureProviderDataLoaded, ensureRankingsDataLoaded, ensureMcpDataLoaded]);
|
||||
|
||||
// Warm other tabs in the background after 150ms
|
||||
useEffect(() => {
|
||||
const tab = urlState.tab || "overview";
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
if (tab !== "overview") void ensureOverviewDataLoaded();
|
||||
if (tab !== "provider-usage") void ensureProviderDataLoaded();
|
||||
if (tab !== "mcp") void ensureMcpDataLoaded();
|
||||
if (tab !== "rankings") void ensureRankingsDataLoaded();
|
||||
}, 150);
|
||||
return () => window.clearTimeout(timeoutId);
|
||||
}, [urlState.tab, ensureOverviewDataLoaded, ensureProviderDataLoaded, ensureMcpDataLoaded, ensureRankingsDataLoaded]);
|
||||
|
||||
// Tab change handler
|
||||
const handleTabChange = useCallback(
|
||||
(tab: string) => {
|
||||
setUrlState({ tab });
|
||||
},
|
||||
[setUrlState],
|
||||
);
|
||||
|
||||
// Chart type toggles
|
||||
const handleVolumeChartToggle = useCallback((type: ChartType) => setUrlState({ volume_chart: type }), [setUrlState]);
|
||||
const handleTokenChartToggle = useCallback((type: ChartType) => setUrlState({ token_chart: type }), [setUrlState]);
|
||||
const handleCostChartToggle = useCallback((type: ChartType) => setUrlState({ cost_chart: type }), [setUrlState]);
|
||||
const handleModelChartToggle = useCallback((type: ChartType) => setUrlState({ model_chart: type }), [setUrlState]);
|
||||
const handleLatencyChartToggle = useCallback((type: ChartType) => setUrlState({ latency_chart: type }), [setUrlState]);
|
||||
|
||||
// Adapter: converts a full LogFilters object to dashboard's CSV-based URL state
|
||||
const setFilters = useCallback(
|
||||
(newFilters: LogFilters) => {
|
||||
const newStartTime = newFilters.start_time ? dateUtils.toUnixTimestamp(new Date(newFilters.start_time)) : undefined;
|
||||
const newEndTime = newFilters.end_time ? dateUtils.toUnixTimestamp(new Date(newFilters.end_time)) : undefined;
|
||||
const timeChanged = newStartTime !== urlState.start_time || newEndTime !== urlState.end_time;
|
||||
setUrlState({
|
||||
...(timeChanged && { period: "" }),
|
||||
start_time: newStartTime,
|
||||
end_time: newEndTime,
|
||||
providers: (newFilters.providers || []).join(","),
|
||||
models: (newFilters.models || []).join(","),
|
||||
selected_key_ids: (newFilters.selected_key_ids || []).join(","),
|
||||
virtual_key_ids: (newFilters.virtual_key_ids || []).join(","),
|
||||
objects: (newFilters.objects || []).join(","),
|
||||
status: (newFilters.status || []).join(","),
|
||||
routing_rule_ids: (newFilters.routing_rule_ids || []).join(","),
|
||||
routing_engine_used: (newFilters.routing_engine_used || []).join(","),
|
||||
missing_cost_only: String(newFilters.missing_cost_only ?? false),
|
||||
metadata_filters:
|
||||
newFilters.metadata_filters && Object.keys(newFilters.metadata_filters).length > 0
|
||||
? JSON.stringify(newFilters.metadata_filters)
|
||||
: "",
|
||||
});
|
||||
},
|
||||
[setUrlState, urlState.start_time, urlState.end_time],
|
||||
);
|
||||
|
||||
// Date range for picker
|
||||
const dateRange = useMemo(
|
||||
() => ({
|
||||
from: dateUtils.fromUnixTimestamp(urlState.start_time),
|
||||
to: dateUtils.fromUnixTimestamp(urlState.end_time),
|
||||
}),
|
||||
[urlState.start_time, urlState.end_time],
|
||||
);
|
||||
|
||||
const handlePeriodChange = useCallback(
|
||||
(period: string | undefined) => {
|
||||
if (!period) return;
|
||||
const { from, to } = getRangeForPeriod(period);
|
||||
setUrlState({
|
||||
period,
|
||||
start_time: Math.floor(from.getTime() / 1000),
|
||||
end_time: Math.floor(to.getTime() / 1000),
|
||||
});
|
||||
},
|
||||
[setUrlState],
|
||||
);
|
||||
|
||||
const handleDateRangeChange = useCallback(
|
||||
(range: { from?: Date; to?: Date }) => {
|
||||
if (!range.from || !range.to) return;
|
||||
setUrlState({
|
||||
period: "",
|
||||
start_time: dateUtils.toUnixTimestamp(range.from),
|
||||
end_time: dateUtils.toUnixTimestamp(range.to),
|
||||
});
|
||||
},
|
||||
[setUrlState],
|
||||
);
|
||||
|
||||
const handleProviderCostChartToggle = useCallback((type: ChartType) => setUrlState({ provider_cost_chart: type }), [setUrlState]);
|
||||
const handleProviderTokenChartToggle = useCallback((type: ChartType) => setUrlState({ provider_token_chart: type }), [setUrlState]);
|
||||
const handleProviderLatencyChartToggle = useCallback((type: ChartType) => setUrlState({ provider_latency_chart: type }), [setUrlState]);
|
||||
|
||||
// MCP chart type toggles
|
||||
const handleMcpVolumeChartToggle = useCallback((type: ChartType) => setUrlState({ mcp_volume_chart: type }), [setUrlState]);
|
||||
const handleMcpCostChartToggle = useCallback((type: ChartType) => setUrlState({ mcp_cost_chart: type }), [setUrlState]);
|
||||
|
||||
// Model filter changes
|
||||
const handleCostModelChange = useCallback((model: string) => setUrlState({ cost_model: model }), [setUrlState]);
|
||||
const handleUsageModelChange = useCallback((model: string) => setUrlState({ usage_model: model }), [setUrlState]);
|
||||
|
||||
// Provider filter changes
|
||||
const handleProviderCostProviderChange = useCallback(
|
||||
(provider: string) => setUrlState({ provider_cost_provider: provider }),
|
||||
[setUrlState],
|
||||
);
|
||||
const handleProviderTokenProviderChange = useCallback(
|
||||
(provider: string) => setUrlState({ provider_token_provider: provider }),
|
||||
[setUrlState],
|
||||
);
|
||||
const handleProviderLatencyProviderChange = useCallback(
|
||||
(provider: string) => setUrlState({ provider_latency_provider: provider }),
|
||||
[setUrlState],
|
||||
);
|
||||
|
||||
// Aggregate data object for export
|
||||
const dashboardData = useMemo(
|
||||
() => ({
|
||||
histogramData,
|
||||
tokenData,
|
||||
costData,
|
||||
modelData,
|
||||
latencyData,
|
||||
providerCostData,
|
||||
providerTokenData,
|
||||
providerLatencyData,
|
||||
rankingsData,
|
||||
mcpHistogramData,
|
||||
mcpCostData,
|
||||
mcpTopToolsData,
|
||||
}),
|
||||
[
|
||||
histogramData,
|
||||
tokenData,
|
||||
costData,
|
||||
modelData,
|
||||
latencyData,
|
||||
providerCostData,
|
||||
providerTokenData,
|
||||
providerLatencyData,
|
||||
rankingsData,
|
||||
mcpHistogramData,
|
||||
mcpCostData,
|
||||
mcpTopToolsData,
|
||||
],
|
||||
);
|
||||
|
||||
// Keep a ref in sync so export callbacks always read the latest data
|
||||
const dashboardDataRef = useRef(dashboardData);
|
||||
dashboardDataRef.current = dashboardData;
|
||||
const getDashboardData = useCallback(() => dashboardDataRef.current, []);
|
||||
|
||||
// Preload all tab data (used by CSV and PDF export)
|
||||
const handlePreloadData = useCallback(async () => {
|
||||
await Promise.all([ensureOverviewDataLoaded(), ensureProviderDataLoaded(), ensureRankingsDataLoaded(), ensureMcpDataLoaded()]);
|
||||
}, [ensureOverviewDataLoaded, ensureProviderDataLoaded, ensureRankingsDataLoaded, ensureMcpDataLoaded]);
|
||||
|
||||
// PDF export mode — when true, all TabsContent are force-mounted so
|
||||
// html2canvas can capture every tab.
|
||||
const [pdfMode, setPdfMode] = useState(false);
|
||||
const dashboardMinHeightRef = useRef<string>("");
|
||||
const hiddenTabsRef = useRef<HTMLElement[]>([]);
|
||||
|
||||
// Called by ExportPopover. Loads all data, force-mounts all tabs,
|
||||
// unhides inactive tabs so html2canvas can capture them, then returns
|
||||
// the 4 section DOM elements. Caller must invoke the returned cleanup
|
||||
// function when done capturing.
|
||||
const handlePdfExport = useCallback(async (): Promise<HTMLElement[]> => {
|
||||
// Ensure every tab's data is loaded
|
||||
await handlePreloadData();
|
||||
|
||||
setPdfMode(true);
|
||||
|
||||
// Wait for React to render the force-mounted tabs
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
});
|
||||
});
|
||||
|
||||
// Radix sets `hidden` on inactive force-mounted TabsContent.
|
||||
// Temporarily remove it so html2canvas can capture them.
|
||||
const hiddenTabs = document.querySelectorAll<HTMLElement>('[data-slot="tabs-content"][hidden]');
|
||||
hiddenTabsRef.current = Array.from(hiddenTabs);
|
||||
for (const tab of hiddenTabs) {
|
||||
tab.removeAttribute("hidden");
|
||||
tab.style.display = "block";
|
||||
}
|
||||
|
||||
// Collapse min-height on the dashboard container so captured
|
||||
// sections wrap tightly around their content (no extra whitespace).
|
||||
const dashboardEl = document.getElementById("dashboard-root");
|
||||
if (dashboardEl) {
|
||||
dashboardMinHeightRef.current = dashboardEl.style.minHeight;
|
||||
dashboardEl.style.minHeight = "0";
|
||||
}
|
||||
|
||||
// Let ResizeObserver-based charts (meter gauge) re-measure
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
});
|
||||
});
|
||||
|
||||
const ids = ["dashboard-section-overview", "dashboard-section-provider-usage", "dashboard-section-rankings", "dashboard-section-mcp"];
|
||||
return ids.map((id) => document.getElementById(id)).filter(Boolean) as HTMLElement[];
|
||||
}, [handlePreloadData]);
|
||||
|
||||
// Cleanup after PDF capture is complete
|
||||
const handlePdfExportDone = useCallback(() => {
|
||||
// Restore minHeight on dashboard container
|
||||
const dashboardEl = document.getElementById("dashboard-root");
|
||||
if (dashboardEl) {
|
||||
dashboardEl.style.minHeight = dashboardMinHeightRef.current;
|
||||
}
|
||||
|
||||
// Re-hide tabs that were temporarily shown for capture
|
||||
for (const tab of hiddenTabsRef.current) {
|
||||
tab.setAttribute("hidden", "");
|
||||
tab.style.display = "";
|
||||
}
|
||||
hiddenTabsRef.current = [];
|
||||
|
||||
setPdfMode(false);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div id="dashboard-root" className="no-padding-parent no-border-parent bg-background flex h-[calc(100vh_-_16px)] w-full gap-3">
|
||||
{/* Sidebar Filters */}
|
||||
<LogsFilterSidebar filters={filters} onFiltersChange={setFilters} />
|
||||
|
||||
{/* Main Content */}
|
||||
<ScrollArea className="bg-card flex min-w-0 flex-1 flex-col gap-4 rounded-l-md">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="text-lg font-semibold">Dashboard</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExportPopover
|
||||
getData={getDashboardData}
|
||||
onPreloadData={handlePreloadData}
|
||||
onPdfExport={handlePdfExport}
|
||||
onPdfExportDone={handlePdfExportDone}
|
||||
/>
|
||||
{urlState.tab === "mcp" && mcpFilterData && (
|
||||
<div className="flex items-center gap-1">
|
||||
{mcpFilterData.tool_names?.length > 0 && (
|
||||
<ModelFilterSelect
|
||||
models={mcpFilterData.tool_names}
|
||||
selectedModel={selectedMcpToolNames.length === 1 ? selectedMcpToolNames[0] : "all"}
|
||||
onModelChange={(value) => {
|
||||
if (value === "all") {
|
||||
setUrlState({ mcp_tool_names: "" });
|
||||
} else {
|
||||
setUrlState({ mcp_tool_names: value });
|
||||
}
|
||||
}}
|
||||
placeholder="All Tools"
|
||||
data-testid="dashboard-mcp-tool-filter"
|
||||
/>
|
||||
)}
|
||||
{mcpFilterData.server_labels?.length > 0 && (
|
||||
<ModelFilterSelect
|
||||
models={mcpFilterData.server_labels}
|
||||
selectedModel={selectedMcpServerLabels.length === 1 ? selectedMcpServerLabels[0] : "all"}
|
||||
onModelChange={(value) => {
|
||||
if (value === "all") {
|
||||
setUrlState({ mcp_server_labels: "" });
|
||||
} else {
|
||||
setUrlState({ mcp_server_labels: value });
|
||||
}
|
||||
}}
|
||||
placeholder="All Servers"
|
||||
data-testid="dashboard-mcp-server-filter"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<DateTimePickerWithRange
|
||||
dateTime={dateRange}
|
||||
onDateTimeUpdate={handleDateRangeChange}
|
||||
preDefinedPeriods={TIME_PERIODS}
|
||||
predefinedPeriod={urlState.period || undefined}
|
||||
onPredefinedPeriodChange={handlePeriodChange}
|
||||
triggerTestId="dashboard-filter-daterange"
|
||||
popupAlignment="end"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
{/* Tabs */}
|
||||
<Tabs value={urlState.tab} onValueChange={handleTabChange}>
|
||||
<TabsList className="mb-2">
|
||||
<TabsTrigger value="overview" data-testid="dashboard-tab-overview">
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="provider-usage" data-testid="dashboard-tab-provider-usage">
|
||||
Provider Usage
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="rankings" data-testid="dashboard-tab-rankings">
|
||||
Model Rankings
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="mcp" data-testid="dashboard-tab-mcp">
|
||||
MCP usage
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="user-rankings" data-testid="dashboard-tab-user-rankings">
|
||||
User Rankings
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Overview Tab */}
|
||||
<TabsContent value="overview" {...(pdfMode && { forceMount: true })}>
|
||||
<div id="dashboard-section-overview">
|
||||
<OverviewTab
|
||||
histogramData={histogramData}
|
||||
tokenData={tokenData}
|
||||
costData={costData}
|
||||
modelData={modelData}
|
||||
latencyData={latencyData}
|
||||
loadingHistogram={loadingHistogram}
|
||||
loadingTokens={loadingTokens}
|
||||
loadingCost={loadingCost}
|
||||
loadingModels={loadingModels}
|
||||
loadingLatency={loadingLatency}
|
||||
startTime={urlState.start_time}
|
||||
endTime={urlState.end_time}
|
||||
volumeChartType={toChartType(urlState.volume_chart)}
|
||||
tokenChartType={toChartType(urlState.token_chart)}
|
||||
costChartType={toChartType(urlState.cost_chart)}
|
||||
modelChartType={toChartType(urlState.model_chart)}
|
||||
latencyChartType={toChartType(urlState.latency_chart)}
|
||||
costModel={urlState.cost_model}
|
||||
usageModel={urlState.usage_model}
|
||||
costModels={costModels}
|
||||
usageModels={usageModels}
|
||||
availableModels={availableModels}
|
||||
onVolumeChartToggle={handleVolumeChartToggle}
|
||||
onTokenChartToggle={handleTokenChartToggle}
|
||||
onCostChartToggle={handleCostChartToggle}
|
||||
onModelChartToggle={handleModelChartToggle}
|
||||
onLatencyChartToggle={handleLatencyChartToggle}
|
||||
onCostModelChange={handleCostModelChange}
|
||||
onUsageModelChange={handleUsageModelChange}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* Provider Usage Tab */}
|
||||
<TabsContent value="provider-usage" {...(pdfMode && { forceMount: true })}>
|
||||
<div id="dashboard-section-provider-usage">
|
||||
<ProviderUsageTab
|
||||
providerCostData={providerCostData}
|
||||
providerTokenData={providerTokenData}
|
||||
providerLatencyData={providerLatencyData}
|
||||
loadingProviderCost={loadingProviderCost}
|
||||
loadingProviderTokens={loadingProviderTokens}
|
||||
loadingProviderLatency={loadingProviderLatency}
|
||||
startTime={urlState.start_time}
|
||||
endTime={urlState.end_time}
|
||||
providerCostChartType={toChartType(urlState.provider_cost_chart)}
|
||||
providerTokenChartType={toChartType(urlState.provider_token_chart)}
|
||||
providerLatencyChartType={toChartType(urlState.provider_latency_chart)}
|
||||
providerCostProvider={urlState.provider_cost_provider}
|
||||
providerTokenProvider={urlState.provider_token_provider}
|
||||
providerLatencyProvider={urlState.provider_latency_provider}
|
||||
availableProviders={availableProviders}
|
||||
providerCostProviders={providerCostProviders}
|
||||
providerTokenProviders={providerTokenProviders}
|
||||
providerLatencyProviders={providerLatencyProviders}
|
||||
onProviderCostChartToggle={handleProviderCostChartToggle}
|
||||
onProviderTokenChartToggle={handleProviderTokenChartToggle}
|
||||
onProviderLatencyChartToggle={handleProviderLatencyChartToggle}
|
||||
onProviderCostProviderChange={handleProviderCostProviderChange}
|
||||
onProviderTokenProviderChange={handleProviderTokenProviderChange}
|
||||
onProviderLatencyProviderChange={handleProviderLatencyProviderChange}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* Model Rankings Tab */}
|
||||
<TabsContent value="rankings" {...(pdfMode && { forceMount: true })}>
|
||||
<div id="dashboard-section-rankings">
|
||||
<ModelRankingsTab
|
||||
rankingsData={rankingsData}
|
||||
loading={loadingRankings}
|
||||
modelData={modelData}
|
||||
loadingModels={loadingModels}
|
||||
startTime={urlState.start_time}
|
||||
endTime={urlState.end_time}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* MCP Tab */}
|
||||
<TabsContent value="mcp" {...(pdfMode && { forceMount: true })}>
|
||||
<div id="dashboard-section-mcp">
|
||||
<MCPTab
|
||||
mcpHistogramData={mcpHistogramData}
|
||||
mcpCostData={mcpCostData}
|
||||
mcpTopToolsData={mcpTopToolsData}
|
||||
loadingMcpHistogram={loadingMcpHistogram}
|
||||
loadingMcpCost={loadingMcpCost}
|
||||
loadingMcpTopTools={loadingMcpTopTools}
|
||||
startTime={urlState.start_time}
|
||||
endTime={urlState.end_time}
|
||||
mcpVolumeChartType={toChartType(urlState.mcp_volume_chart)}
|
||||
mcpCostChartType={toChartType(urlState.mcp_cost_chart)}
|
||||
onMcpVolumeChartToggle={handleMcpVolumeChartToggle}
|
||||
onMcpCostChartToggle={handleMcpCostChartToggle}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* User Rankings Tab (Enterprise) */}
|
||||
<TabsContent value="user-rankings">
|
||||
<UserRankingsTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
95
ui/app/workspace/dashboard/utils/chartUtils.ts
Normal file
95
ui/app/workspace/dashboard/utils/chartUtils.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
// Chart utility functions for the dashboard
|
||||
|
||||
// Format timestamp based on bucket size
|
||||
export function formatTimestamp(timestamp: string, bucketSizeSeconds: number): string {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
if (bucketSizeSeconds >= 86400) {
|
||||
// Daily buckets: "Jan 20"
|
||||
return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
||||
} else if (bucketSizeSeconds >= 3600) {
|
||||
// Hourly buckets: "10:00"
|
||||
return date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
} else {
|
||||
// Sub-hourly: "10:15"
|
||||
return date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
}
|
||||
}
|
||||
|
||||
// Format full timestamp for tooltip
|
||||
export function formatFullTimestamp(timestamp: string): string {
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Format cost values
|
||||
export function formatCost(cost: number): string {
|
||||
if (cost < 0.01) {
|
||||
return `$${cost.toFixed(4)}`;
|
||||
}
|
||||
return `$${cost.toFixed(2)}`;
|
||||
}
|
||||
|
||||
// Format token values
|
||||
export function formatTokens(tokens: number): string {
|
||||
if (tokens >= 1000000) {
|
||||
return `${(tokens / 1000000).toFixed(1)}M`;
|
||||
}
|
||||
if (tokens >= 1000) {
|
||||
return `${(tokens / 1000).toFixed(1)}K`;
|
||||
}
|
||||
return tokens.toLocaleString();
|
||||
}
|
||||
|
||||
// Color palette for models
|
||||
export const MODEL_COLORS = [
|
||||
"#10b981", // emerald-500
|
||||
"#3b82f6", // blue-500
|
||||
"#f59e0b", // amber-500
|
||||
"#ef4444", // red-500
|
||||
"#8b5cf6", // violet-500
|
||||
"#ec4899", // pink-500
|
||||
"#06b6d4", // cyan-500
|
||||
"#84cc16", // lime-500
|
||||
];
|
||||
|
||||
// Get color for a model by index
|
||||
export function getModelColor(index: number): string {
|
||||
return MODEL_COLORS[index % MODEL_COLORS.length];
|
||||
}
|
||||
|
||||
// Format latency values
|
||||
export function formatLatency(ms: number): string {
|
||||
if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
|
||||
return `${ms.toFixed(0)}ms`;
|
||||
}
|
||||
|
||||
// Latency chart color palette
|
||||
export const LATENCY_COLORS = {
|
||||
avg: "#06b6d4", // cyan-500
|
||||
p90: "#3b82f6", // blue-500
|
||||
p95: "#f59e0b", // amber-500
|
||||
p99: "#ef4444", // red-500
|
||||
};
|
||||
|
||||
// Shared CSS class constants for chart card headers
|
||||
export const CHART_HEADER_ACTIONS_CLASS = "flex min-w-0 w-full flex-col-reverse gap-2";
|
||||
export const CHART_HEADER_LEGEND_CLASS = "flex min-h-5 min-w-0 flex-wrap items-center gap-2 pl-2 text-xs";
|
||||
export const CHART_HEADER_CONTROLS_CLASS = "flex items-center justify-end gap-2";
|
||||
|
||||
// Chart colors
|
||||
export const CHART_COLORS = {
|
||||
success: "#10b981", // emerald-500
|
||||
error: "#ef4444", // red-500
|
||||
promptTokens: "#3b82f6", // blue-500
|
||||
completionTokens: "#10b981", // emerald-500
|
||||
totalTokens: "#8b5cf6", // violet-500
|
||||
cost: "#f59e0b", // amber-500
|
||||
cachedReadTokens: "#06b6d4", // cyan-500
|
||||
};
|
||||
212
ui/app/workspace/dashboard/utils/exportUtils.ts
Normal file
212
ui/app/workspace/dashboard/utils/exportUtils.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Dashboard-specific CSV data converters.
|
||||
*
|
||||
* Each function takes the dashboard data and returns { headers, rows } ready
|
||||
* for `buildCSV()`.
|
||||
*/
|
||||
|
||||
import type {
|
||||
CostHistogramResponse,
|
||||
LatencyHistogramResponse,
|
||||
LogsHistogramResponse,
|
||||
MCPCostHistogramResponse,
|
||||
MCPHistogramResponse,
|
||||
MCPTopToolsResponse,
|
||||
ModelHistogramResponse,
|
||||
ModelRankingsResponse,
|
||||
ProviderCostHistogramResponse,
|
||||
ProviderLatencyHistogramResponse,
|
||||
ProviderTokenHistogramResponse,
|
||||
TokenHistogramResponse,
|
||||
} from "@/lib/types/logs";
|
||||
|
||||
type CSVData = { headers: string[]; rows: unknown[][] };
|
||||
|
||||
export function overviewVolumeToCSV(data: LogsHistogramResponse | null): CSVData {
|
||||
const headers = ["Timestamp", "Total Requests", "Success", "Error"];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.count, b.success, b.error]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function overviewTokensToCSV(data: TokenHistogramResponse | null): CSVData {
|
||||
const headers = ["Timestamp", "Prompt Tokens", "Completion Tokens", "Total Tokens", "Cached Read Tokens"];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.prompt_tokens, b.completion_tokens, b.total_tokens, b.cached_read_tokens]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function overviewCostToCSV(data: CostHistogramResponse | null): CSVData {
|
||||
const models = data?.models ?? [];
|
||||
const headers = ["Timestamp", "Total Cost", ...models];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.total_cost, ...models.map((m) => b.by_model?.[m] ?? 0)]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function overviewModelUsageToCSV(data: ModelHistogramResponse | null): CSVData {
|
||||
const models = data?.models ?? [];
|
||||
const modelHeaders = models.flatMap((m) => [`${m} Total`, `${m} Success`, `${m} Error`]);
|
||||
const headers = ["Timestamp", ...modelHeaders];
|
||||
const rows = (data?.buckets ?? []).map((b) => [
|
||||
b.timestamp,
|
||||
...models.flatMap((m) => {
|
||||
const stats = b.by_model?.[m];
|
||||
return [stats?.total ?? 0, stats?.success ?? 0, stats?.error ?? 0];
|
||||
}),
|
||||
]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function overviewLatencyToCSV(data: LatencyHistogramResponse | null): CSVData {
|
||||
const headers = ["Timestamp", "Avg Latency (ms)", "P90 (ms)", "P95 (ms)", "P99 (ms)", "Total Requests"];
|
||||
const rows = (data?.buckets ?? []).map((b) => [
|
||||
b.timestamp,
|
||||
b.avg_latency,
|
||||
b.p90_latency,
|
||||
b.p95_latency,
|
||||
b.p99_latency,
|
||||
b.total_requests,
|
||||
]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function providerCostToCSV(data: ProviderCostHistogramResponse | null): CSVData {
|
||||
const providers = data?.providers ?? [];
|
||||
const headers = ["Timestamp", "Total Cost", ...providers];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.total_cost, ...providers.map((p) => b.by_provider?.[p] ?? 0)]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function providerTokensToCSV(data: ProviderTokenHistogramResponse | null): CSVData {
|
||||
const providers = data?.providers ?? [];
|
||||
const provHeaders = providers.flatMap((p) => [`${p} Prompt`, `${p} Completion`, `${p} Total`]);
|
||||
const headers = ["Timestamp", ...provHeaders];
|
||||
const rows = (data?.buckets ?? []).map((b) => [
|
||||
b.timestamp,
|
||||
...providers.flatMap((p) => {
|
||||
const stats = b.by_provider?.[p];
|
||||
return [stats?.prompt_tokens ?? 0, stats?.completion_tokens ?? 0, stats?.total_tokens ?? 0];
|
||||
}),
|
||||
]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function providerLatencyToCSV(data: ProviderLatencyHistogramResponse | null): CSVData {
|
||||
const providers = data?.providers ?? [];
|
||||
const provHeaders = providers.flatMap((p) => [`${p} Avg (ms)`, `${p} P90 (ms)`, `${p} P95 (ms)`, `${p} P99 (ms)`]);
|
||||
const headers = ["Timestamp", ...provHeaders];
|
||||
const rows = (data?.buckets ?? []).map((b) => [
|
||||
b.timestamp,
|
||||
...providers.flatMap((p) => {
|
||||
const stats = b.by_provider?.[p];
|
||||
return [stats?.avg_latency ?? 0, stats?.p90_latency ?? 0, stats?.p95_latency ?? 0, stats?.p99_latency ?? 0];
|
||||
}),
|
||||
]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function modelRankingsToCSV(data: ModelRankingsResponse | null): CSVData {
|
||||
const headers = [
|
||||
"Model",
|
||||
"Provider",
|
||||
"Total Requests",
|
||||
"Success Count",
|
||||
"Success Rate (%)",
|
||||
"Total Tokens",
|
||||
"Total Cost ($)",
|
||||
"Avg Latency (ms)",
|
||||
"Requests Trend (%)",
|
||||
"Tokens Trend (%)",
|
||||
"Cost Trend (%)",
|
||||
"Latency Trend (%)",
|
||||
];
|
||||
const rows = (data?.rankings ?? []).map((r) => [
|
||||
r.model,
|
||||
r.provider,
|
||||
r.total_requests,
|
||||
r.success_count,
|
||||
r.success_rate,
|
||||
r.total_tokens,
|
||||
r.total_cost,
|
||||
r.avg_latency,
|
||||
r.trend.has_previous_period ? r.trend.requests_trend : "N/A",
|
||||
r.trend.has_previous_period ? r.trend.tokens_trend : "N/A",
|
||||
r.trend.has_previous_period ? r.trend.cost_trend : "N/A",
|
||||
r.trend.has_previous_period ? r.trend.latency_trend : "N/A",
|
||||
]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function mcpVolumeToCSV(data: MCPHistogramResponse | null): CSVData {
|
||||
const headers = ["Timestamp", "Total Executions", "Success", "Error"];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.count, b.success, b.error]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function mcpCostToCSV(data: MCPCostHistogramResponse | null): CSVData {
|
||||
const headers = ["Timestamp", "Total Cost ($)"];
|
||||
const rows = (data?.buckets ?? []).map((b) => [b.timestamp, b.total_cost]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export function mcpTopToolsToCSV(data: MCPTopToolsResponse | null): CSVData {
|
||||
const headers = ["Tool Name", "Execution Count", "Cost ($)"];
|
||||
const rows = (data?.tools ?? []).map((t) => [t.tool_name, t.count, t.cost]);
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export interface DashboardData {
|
||||
// Overview
|
||||
histogramData: LogsHistogramResponse | null;
|
||||
tokenData: TokenHistogramResponse | null;
|
||||
costData: CostHistogramResponse | null;
|
||||
modelData: ModelHistogramResponse | null;
|
||||
latencyData: LatencyHistogramResponse | null;
|
||||
// Provider Usage
|
||||
providerCostData: ProviderCostHistogramResponse | null;
|
||||
providerTokenData: ProviderTokenHistogramResponse | null;
|
||||
providerLatencyData: ProviderLatencyHistogramResponse | null;
|
||||
// Rankings
|
||||
rankingsData: ModelRankingsResponse | null;
|
||||
// MCP
|
||||
mcpHistogramData: MCPHistogramResponse | null;
|
||||
mcpCostData: MCPCostHistogramResponse | null;
|
||||
mcpTopToolsData: MCPTopToolsResponse | null;
|
||||
}
|
||||
|
||||
export type ExportTab = "all" | "overview" | "provider-usage" | "rankings" | "mcp";
|
||||
|
||||
/** Return all CSV sections for the selected scope. Each entry becomes its own sheet / file section. */
|
||||
export function getCSVSections(data: DashboardData, tab: ExportTab): { name: string; csv: CSVData }[] {
|
||||
const sections: { name: string; csv: CSVData }[] = [];
|
||||
|
||||
if (tab === "all" || tab === "overview") {
|
||||
sections.push(
|
||||
{ name: "overview-volume", csv: overviewVolumeToCSV(data.histogramData) },
|
||||
{ name: "overview-tokens", csv: overviewTokensToCSV(data.tokenData) },
|
||||
{ name: "overview-cost", csv: overviewCostToCSV(data.costData) },
|
||||
{ name: "overview-model-usage", csv: overviewModelUsageToCSV(data.modelData) },
|
||||
{ name: "overview-latency", csv: overviewLatencyToCSV(data.latencyData) },
|
||||
);
|
||||
}
|
||||
|
||||
if (tab === "all" || tab === "provider-usage") {
|
||||
sections.push(
|
||||
{ name: "provider-cost", csv: providerCostToCSV(data.providerCostData) },
|
||||
{ name: "provider-tokens", csv: providerTokensToCSV(data.providerTokenData) },
|
||||
{ name: "provider-latency", csv: providerLatencyToCSV(data.providerLatencyData) },
|
||||
);
|
||||
}
|
||||
|
||||
if (tab === "all" || tab === "rankings") {
|
||||
sections.push({ name: "model-rankings", csv: modelRankingsToCSV(data.rankingsData) });
|
||||
}
|
||||
|
||||
if (tab === "all" || tab === "mcp") {
|
||||
sections.push(
|
||||
{ name: "mcp-volume", csv: mcpVolumeToCSV(data.mcpHistogramData) },
|
||||
{ name: "mcp-cost", csv: mcpCostToCSV(data.mcpCostData) },
|
||||
{ name: "mcp-top-tools", csv: mcpTopToolsToCSV(data.mcpTopToolsData) },
|
||||
);
|
||||
}
|
||||
|
||||
return sections;
|
||||
}
|
||||
Reference in New Issue
Block a user