🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(dashboard): add csv download from ui and loading state (#7364)
Marc Klingen9fd03082eaf2
diff --git a/web/src/features/widgets/chart-library/BigNumber.tsx b/web/src/features/widgets/chart-library/BigNumber.tsxindex 7dad68f59a..c3c4bd8bfe 100644--- a/web/src/features/widgets/chart-library/BigNumber.tsx+++ b/web/src/features/widgets/chart-library/BigNumber.tsx@@ -1,5 +1,6 @@+import React, { useEffect, useRef, useState, useMemo } from "react";import { cn } from "@/src/utils/tailwind";-import { useEffect, useRef, useState } from "react";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";// Format large numbers with appropriate units and dynamic decimal placesconst formatBigNumber = (@@ -96,28 +97,35 @@ const formatBigNumber = (}};-export const BigNumber = ({+export const BigNumber: React.FC<ChartProps> = ({+ data,className,- metric,-}: {- className?: string;- metric: React.ReactNode;-}) => {+}: ChartProps & { className?: string }) => {const containerRef = useRef<HTMLDivElement>(null);const textRef = useRef<HTMLSpanElement>(null);const [fontSize, setFontSize] = useState("text-6xl");const [maxCharacters, setMaxCharacters] = useState<number>();- // Convert metric to number if it's a string or number, otherwise use original- const numericValue =- typeof metric === "string" || typeof metric === "number"- ? parseFloat(String(metric))- : null;+ // Calculate metric value from data - show loading if no data+ const isLoading = !data || data.length === 0;- const displayValue =- numericValue !== null && !isNaN(numericValue)- ? formatBigNumber(numericValue, maxCharacters)- : { formatted: String(metric), unit: "" };+ const calculatedMetric = useMemo(() => {+ if (isLoading) return 0;++ // Show the sum of all metrics, or just the first metric if only one+ if (data.length === 1) {+ return typeof data[0].metric === "number" ? data[0].metric : 0;+ }++ return data.reduce((acc, d) => {+ const metric = typeof d.metric === "number" ? d.metric : 0;+ return acc + metric;+ }, 0);+ }, [data, isLoading]);++ const displayValue = !isLoading+ ? formatBigNumber(calculatedMetric, maxCharacters)+ : { formatted: "0", unit: "" };useEffect(() => {const resizeObserver = new ResizeObserver(() => {@@ -156,10 +164,9 @@ export const BigNumber = ({const maxChars = Math.floor(availableWidth / charWidth);// Quick test with current display value- const testDisplayValue =- numericValue !== null && !isNaN(numericValue)- ? formatBigNumber(numericValue, maxChars)- : { formatted: String(metric), unit: "" };+ const testDisplayValue = !isLoading+ ? formatBigNumber(calculatedMetric, maxChars)+ : { formatted: "0", unit: "" };const textLength = (testDisplayValue.formatted + testDisplayValue.unit).length;@@ -185,7 +192,11 @@ export const BigNumber = ({}return () => resizeObserver.disconnect();- }, [numericValue, metric]);+ }, [calculatedMetric, isLoading]);++ if (isLoading) {+ return null;+ }return (<div@@ -199,11 +210,7 @@ export const BigNumber = ({<spanref={textRef}className={cn("text-center font-extrabold tracking-tight", fontSize)}- title={- numericValue !== null && !isNaN(numericValue)- ? numericValue.toString()- : String(metric)- }+ title={calculatedMetric.toString()}>{displayValue.formatted}</span>diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex 581e2215d1..24913fa07f 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -56,15 +56,7 @@ export const Chart = ({case "HISTOGRAM":return <HistogramChart data={renderedData} />;case "NUMBER": {- // Show the sum of all metrics, or just the first metric if only one- const value =- renderedData.length === 1- ? renderedData[0].metric- : renderedData.reduce(- (acc, d) => acc + ((d.metric as number) || 0),- 0,- );- return <BigNumber metric={value} />;+ return <BigNumber data={renderedData} />;}default:return <HorizontalBarChart data={renderedData.slice(0, rowLimit)} />;diff --git a/web/src/features/widgets/chart-library/DownloadButton.tsx b/web/src/features/widgets/chart-library/DownloadButton.tsxnew file mode 100644index 0000000000..b178c1b5e0--- /dev/null+++ b/web/src/features/widgets/chart-library/DownloadButton.tsx@@ -0,0 +1,79 @@+import { Download, Check } from "lucide-react";+import { useState } from "react";++export function DownloadButton({+ data,+ fileName = "chart-data",+ className,+}: {+ data: Record<string, any>[];+ fileName?: string;+ className?: string;+}) {+ const [isDownloaded, setIsDownloaded] = useState(false);++ const escapeCsvValue = (value: any): string => {+ const stringValue = String(value ?? "");+ if (+ stringValue.includes(",") ||+ stringValue.includes('"') ||+ stringValue.includes("\n")+ ) {+ return `"${stringValue.replace(/"/g, '""')}"`;+ }+ return stringValue;+ };++ const triggerDownload = (csvContent: string) => {+ const blob = new Blob([csvContent], { type: "text/csv" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `${fileName}.csv`;+ document.body.appendChild(a);+ a.click();+ a.remove();+ URL.revokeObjectURL(url);++ // Show checkmark for 1 second+ setIsDownloaded(true);+ setTimeout(() => {+ setIsDownloaded(false);+ }, 1000);+ };++ const downloadCsv = () => {+ if (data.length === 0) {+ triggerDownload("");+ return;+ }++ const headers = Object.keys(data[0]);+ const csvRows = [+ headers.join(","),+ ...data.map((row) =>+ headers.map((h) => escapeCsvValue(row[h])).join(","),+ ),+ ];++ const csvContent = csvRows.join("\n");+ triggerDownload(csvContent);+ };++ return (+ <button+ onClick={() => {+ if (isDownloaded) {+ return;+ }+ downloadCsv();+ }}+ className={`text-muted-foreground hover:text-foreground ${className || ""}`}+ aria-label="Download chart data as CSV"+ title="Download CSV"+ disabled={isDownloaded}+ >+ {isDownloaded ? <Check size={16} /> : <Download size={16} />}+ </button>+ );+}diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex 3930b9b72e..bd7c748265 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -14,11 +14,13 @@ import {TrashIcon,CopyIcon,GripVerticalIcon,+ Loader2,} from "lucide-react";import { useRouter } from "next/router";import { startCase } from "lodash";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { DownloadButton } from "@/src/features/widgets/chart-library/DownloadButton";export interface WidgetPlacement {id: string;@@ -207,38 +209,56 @@ export function DashboardWidget({? " ( 🪢 )": null}</span>- {hasCUDAccess && (- <div className="flex space-x-2">- <GripVerticalIcon- size={16}- className="drag-handle hidden cursor-grab text-muted-foreground hover:text-foreground active:cursor-grabbing lg:group-hover:block"- />- {widget.data.owner === "PROJECT" ? (+ <div className="flex space-x-2">+ {hasCUDAccess && (+ <>+ <GripVerticalIcon+ size={16}+ className="drag-handle hidden cursor-grab text-muted-foreground hover:text-foreground active:cursor-grabbing lg:group-hover:block"+ />+ {widget.data.owner === "PROJECT" ? (+ <button+ onClick={handleEdit}+ className="hidden text-muted-foreground hover:text-foreground group-hover:block"+ aria-label="Edit widget"+ >+ <PencilIcon size={16} />+ </button>+ ) : widget.data.owner === "LANGFUSE" ? (+ <button+ onClick={handleCopy}+ className="hidden text-muted-foreground hover:text-foreground group-hover:block"+ aria-label="Copy widget"+ >+ <CopyIcon size={16} />+ </button>+ ) : null}<button- onClick={handleEdit}- className="hidden text-muted-foreground hover:text-foreground group-hover:block"- aria-label="Edit widget"+ onClick={handleDelete}+ className="hidden text-muted-foreground hover:text-destructive group-hover:block"+ aria-label="Delete widget">- <PencilIcon size={16} />+ <TrashIcon size={16} /></button>- ) : widget.data.owner === "LANGFUSE" ? (- <button- onClick={handleCopy}- className="hidden text-muted-foreground hover:text-foreground group-hover:block"- aria-label="Copy widget"- >- <CopyIcon size={16} />- </button>- ) : null}- <button- onClick={handleDelete}- className="hidden text-muted-foreground hover:text-destructive group-hover:block"- aria-label="Delete widget"+ </>+ )}+ {/* Download button or loading indicator - always available */}+ {queryResult.isLoading ? (+ <div+ className="text-muted-foreground"+ aria-label="Loading chart data"+ title="Loading...">- <TrashIcon size={16} />- </button>- </div>- )}+ <Loader2 size={16} className="animate-spin" />+ </div>+ ) : (+ <DownloadButton+ data={transformedData}+ fileName={widget.data.name}+ className="hidden group-hover:block"+ />+ )}+ </div></div><divclassName="mb-4 truncate text-sm text-muted-foreground"