🪢 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(ui): add export status table to project settings (#4816)
Marc Klingen8f961925d54c
diff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsxindex 58bdadbc5a..1bb8ae5e9b 100644--- a/web/src/components/BatchExportTableButton.tsx+++ b/web/src/components/BatchExportTableButton.tsx@@ -37,12 +37,17 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (showSuccessToast({title: "Export queued",description: "You will receive an email when the export is ready.",+ duration: 10000,+ link: {+ href: `/project/${props.projectId}/settings/exports`,+ text: "View exports",+ },});},});const hasAccess = useHasProjectAccess({projectId: props.projectId,- scope: "batchExport:create",+ scope: "batchExports:create",});const handleExport = async (format: BatchExportFileFormat) => {diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsxindex dfd26fb1c5..197daa0413 100644--- a/web/src/components/layouts/status-badge.tsx+++ b/web/src/components/layouts/status-badge.tsx@@ -27,19 +27,18 @@ export const StatusBadge = ({let dotPingColor = "bg-muted-foreground";let showDot = isLive;- if (statusCategories.active.includes(type)) {+ if (statusCategories.active.includes(type.toLowerCase())) {badgeColor = "bg-light-green text-dark-green";dotColor = "animate-ping bg-dark-green";dotPingColor = "bg-dark-green";- } else if (statusCategories.pending.includes(type)) {+ } else if (statusCategories.pending.includes(type.toLowerCase())) {badgeColor = "bg-light-yellow text-dark-yellow";dotColor = "animate-ping bg-dark-yellow";dotPingColor = "bg-dark-yellow";- } else if (statusCategories.error.includes(type)) {+ } else if (statusCategories.error.includes(type.toLowerCase())) {badgeColor = "bg-light-red text-dark-red";- dotColor = "animate-ping bg-dark-red";- dotPingColor = "bg-dark-red";- } else if (statusCategories.completed.includes(type)) {+ showDot = false;+ } else if (statusCategories.completed.includes(type.toLowerCase())) {badgeColor = "bg-light-green text-dark-green";showDot = false;}diff --git a/web/src/features/batch-exports/README.md b/web/src/features/batch-exports/README.mdnew file mode 100644index 0000000000..80f34b2cc0--- /dev/null+++ b/web/src/features/batch-exports/README.md@@ -0,0 +1,4 @@+# Batch Exports++- Find types in shared+- Actual export logic in workerdiff --git a/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx b/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsxnew file mode 100644index 0000000000..4cbec53fb6--- /dev/null+++ b/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx@@ -0,0 +1,33 @@+import Header from "@/src/components/layouts/header";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import { BatchExportsTable } from "@/src/features/batch-exports/components/BatchExportsTable";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++export function BatchExportsSettingsPage(props: { projectId: string }) {+ const hasAccess = useHasProjectAccess({+ projectId: props.projectId,+ scope: "batchExports:read",+ });++ return (+ <>+ <Header title="Exports" level="h3" />+ <p className="mb-4 text-sm">+ Export large datasets in your preferred format via the export buttons+ across Langfuse. Exports are processed asynchronously and remain+ available for download for one hour. You will receive an email+ notification once your export is ready.+ </p>+ {hasAccess ? (+ <BatchExportsTable projectId={props.projectId} />+ ) : (+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view batch exports.+ </AlertDescription>+ </Alert>+ )}+ </>+ );+}diff --git a/web/src/features/batch-exports/components/BatchExportsTable.tsx b/web/src/features/batch-exports/components/BatchExportsTable.tsxnew file mode 100644index 0000000000..5ebd3c338c--- /dev/null+++ b/web/src/features/batch-exports/components/BatchExportsTable.tsx@@ -0,0 +1,161 @@+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { api } from "@/src/utils/api";+import { type BatchExport } from "@langfuse/shared";+import { StatusBadge } from "@/src/components/layouts/status-badge";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { ActionButton } from "@/src/components/ActionButton";+import { DownloadIcon, InfoIcon } from "lucide-react";+import { Avatar, AvatarImage } from "@/src/components/ui/avatar";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";++export function BatchExportsTable(props: { projectId: string }) {+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 10),+ });++ const batchExports = api.batchExport.all.useQuery({+ projectId: props.projectId,+ limit: paginationState.pageSize,+ page: paginationState.pageIndex,+ });++ const columns = [+ {+ accessorKey: "name",+ id: "name",+ header: "Name",+ size: 200,+ cell: ({ row }) => {+ const name = row.getValue("name") as string;+ const { createdAt, finishedAt } = row.original;+ return (+ <div className="flex items-center gap-2">+ <span className="whitespace-break-spaces">{name}</span>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger>+ <InfoIcon className="size-3 text-muted-foreground" />+ </TooltipTrigger>+ <TooltipContent>+ <div className="space-y-1">+ <div>Created: {new Date(createdAt).toLocaleString()}</div>+ <div>+ Finished:{" "}+ {finishedAt ? new Date(finishedAt).toLocaleString() : "-"}+ </div>+ </div>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ );+ },+ },+ {+ accessorKey: "status",+ id: "status",+ header: "Status",+ size: 90,+ cell: (row) => {+ const status = row.getValue() as string;+ return (+ <StatusBadge type={status.toLowerCase()} className="capitalize" />+ );+ },+ },+ {+ accessorKey: "url",+ id: "url",+ header: "Download URL",+ size: 130,+ cell: (info) => {+ const url = info.getValue() as string | null;+ if (!url) {+ return null;+ }+ if (url === "expired") {+ return <span className="text-muted-foreground">Expired</span>;+ }+ return (+ <ActionButton href={url} icon={<DownloadIcon size={16} />} size="sm">+ Download+ </ActionButton>+ );+ },+ },+ {+ accessorKey: "format",+ id: "format",+ header: "Format",+ size: 70,+ },+ {+ accessorKey: "user",+ id: "user",+ header: "Created By",+ size: 150,+ cell: ({ row }) => {+ const user = row.getValue("user") as {+ name: string | null;+ image: string | null;+ } | null;+ return (+ <div className="flex items-center space-x-2">+ <Avatar className="h-7 w-7">+ <AvatarImage+ src={user?.image ?? undefined}+ alt={user?.name ?? "User Avatar"}+ />+ </Avatar>+ <span>{user?.name ?? "Unknown"}</span>+ </div>+ );+ },+ },+ {+ accessorKey: "log",+ id: "log",+ header: "Log",+ size: 300,+ cell: (row) => {+ const log = row.getValue() as string | null;+ return log ?? null;+ },+ },+ ] as LangfuseColumnDef<BatchExport>[];++ return (+ <>+ <DataTable+ columns={columns}+ data={+ batchExports.isLoading+ ? { isLoading: true, isError: false }+ : batchExports.isError+ ? {+ isLoading: false,+ isError: true,+ error: batchExports.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: batchExports.data.exports,+ }+ }+ pagination={{+ totalCount: batchExports.data?.totalCount ?? null,+ onChange: setPaginationState,+ state: paginationState,+ }}+ />+ </>+ );+}diff --git a/web/src/features/batch-exports/server/batchExport.ts b/web/src/features/batch-exports/server/batchExport.tsnew file mode 100644index 0000000000..75f08ad8df--- /dev/null+++ b/web/src/features/batch-exports/server/batchExport.ts@@ -0,0 +1,166 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import {+ BatchExportStatus,+ CreateBatchExportSchema,+ paginationZod,+} from "@langfuse/shared";+import {+ BatchExportQueue,+ logger,+ QueueJobs,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import { z } from "zod";++export const batchExportRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateBatchExportSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ // Check permissions, esp. projectId+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "batchExports:create",+ });++ const { projectId, query, format, name } = input;+ console.log(+ "[TRPC] Creating export job",+ JSON.stringify(input, null, 2),+ );+ const userId = ctx.session.user.id;++ // Create export job+ const exportJob = await ctx.prisma.batchExport.create({+ data: {+ projectId,+ userId,+ status: BatchExportStatus.QUEUED,+ name,+ format,+ query,+ },+ });++ // Create audit log+ await auditLog({+ session: ctx.session,+ resourceType: "batchExport",+ resourceId: exportJob.id,+ projectId,+ action: "create",+ after: exportJob,+ });++ // Notify worker+ await BatchExportQueue.getInstance()?.add(QueueJobs.BatchExportJob, {+ id: exportJob.id, // Use the batchExportId to deduplicate when the same job is sent multiple times+ name: QueueJobs.BatchExportJob,+ timestamp: new Date(),+ payload: {+ batchExportId: exportJob.id,+ projectId,+ },+ });+ } catch (e) {+ logger.error(e);+ if (e instanceof TRPCError) {+ throw e;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Creating export job failed.",+ });+ }+ }),+ all: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ ...paginationZod,+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "batchExports:read",+ });++ const [exports, totalCount] = await Promise.all([+ ctx.prisma.batchExport.findMany({+ where: {+ projectId: input.projectId,+ },+ take: input.limit,+ skip: input.page * input.limit,+ orderBy: {+ createdAt: "desc",+ },+ }),+ ctx.prisma.batchExport.count({+ where: {+ projectId: input.projectId,+ },+ }),+ ]);++ // Look up users for each export+ const userIds = [...new Set(exports.map((e) => e.userId))];+ const users = await ctx.prisma.user.findMany({+ where: {+ id: {+ in: userIds,+ },+ organizationMemberships: {+ some: {+ organization: {+ projects: {+ some: {+ id: input.projectId,+ },+ },+ },+ },+ },+ },+ select: {+ id: true,+ name: true,+ image: true,+ },+ });++ const userMap = new Map(users.map((u) => [u.id, u]));++ const exportsWithExpiration = exports.map((e) => {+ const { finishedAt, url, ...rest } = e;++ let isExpired = false;+ if (finishedAt) {+ const finishTime = new Date(finishedAt).getTime();+ const now = new Date().getTime();+ const oneHourInMs = 60 * 60 * 1000;+ isExpired = now - finishTime > oneHourInMs;+ }++ return {+ ...rest,+ finishedAt,+ url: isExpired ? "expired" : url,+ user: userMap.get(e.userId) ?? null,+ };+ });++ return {+ exports: exportsWithExpiration,+ totalCount,+ };+ }),+});diff --git a/web/src/features/notifications/SuccessNotification.tsx b/web/src/features/notifications/SuccessNotification.tsxindex a52ebdc361..24a6a4105b 100644--- a/web/src/features/notifications/SuccessNotification.tsx+++ b/web/src/features/notifications/SuccessNotification.tsx@@ -1,5 +1,5 @@+import { ActionButton } from "@/src/components/ActionButton";import { BadgeCheck, X } from "lucide-react";-import Link from "next/link";export type SuccessNotificationProps = {title: string;@@ -28,14 +28,19 @@ export const SuccessNotification: React.FC<SuccessNotificationProps> = ({</div>{description && (<div className="text-sm leading-tight text-primary-foreground">- {description}{" "}- {!!link && (- <Link href={link.href}>- <span className="hover:underline">{link.text}</span>- </Link>- )}+ {description}</div>)}+ {link && (+ <ActionButton+ href={link.href}+ size="sm"+ variant="secondary"+ className="self-start"+ >+ {link.text}+ </ActionButton>+ )}</div><buttonclassName="flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 text-primary-foreground transition-colors duration-200"diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 6e129a59a1..1ef0be27b7 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -34,7 +34,8 @@ const projectScopes = ["models:CUD",- "batchExport:create",+ "batchExports:create",+ "batchExports:read","evalTemplate:create","evalTemplate:read",@@ -85,7 +86,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",- "batchExport:create",+ "batchExports:create",+ "batchExports:read","comments:CUD","comments:read","annotationQueues:read",@@ -120,7 +122,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",- "batchExport:create",+ "batchExports:create",+ "batchExports:read","comments:CUD","comments:read","annotationQueues:read",@@ -147,7 +150,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"evalJob:CUD","evalJobExecution:read","llmApiKeys:read",- "batchExport:create",+ "batchExports:create",+ "batchExports:read","comments:CUD","comments:read","annotationQueues:read",diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxindex e747e43fd1..88a6775037 100644--- a/web/src/pages/project/[projectId]/settings/index.tsx+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -20,6 +20,7 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { useRouter } from "next/router";import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";import { ActionButton } from "@/src/components/ActionButton";+import { BatchExportsSettingsPage } from "@/src/features/batch-exports/components/BatchExportsSettingsPage";export default function SettingsPage() {const { project, organization } = useQueryProject();@@ -109,6 +110,11 @@ export default function SettingsPage() {slug: "integrations",content: <Integrations projectId={project.id} />,},+ {+ title: "Exports",+ slug: "exports",+ content: <BatchExportsSettingsPage projectId={project.id} />,+ },{title: "Billing",slug: "billing",diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 93a7420155..f06a0ac0c3 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -20,7 +20,7 @@ import { organizationsRouter } from "@/src/features/organizations/server/organizimport { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";import { publicRouter } from "@/src/server/api/routers/public";import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";-import { batchExportRouter } from "@/src/server/api/routers/batchExport";+import { batchExportRouter } from "@/src/features/batch-exports/server/batchExport";import { utilsRouter } from "@/src/server/api/routers/utilities";import { uiCustomizationRouter } from "@/src/ee/features/ui-customization/uiCustomizationRouter";import { commentsRouter } from "@/src/server/api/routers/comments";diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.tsdeleted file mode 100644index 1a626fed05..0000000000--- a/web/src/server/api/routers/batchExport.ts+++ /dev/null@@ -1,77 +0,0 @@-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import {- createTRPCRouter,- protectedProjectProcedure,-} from "@/src/server/api/trpc";-import { BatchExportStatus, CreateBatchExportSchema } from "@langfuse/shared";-import {- BatchExportQueue,- logger,- QueueJobs,-} from "@langfuse/shared/src/server";-import { TRPCError } from "@trpc/server";--export const batchExportRouter = createTRPCRouter({- create: protectedProjectProcedure- .input(CreateBatchExportSchema)- .mutation(async ({ input, ctx }) => {- try {- // Check permissions, esp. projectId- throwIfNoProjectAccess({- session: ctx.session,- projectId: input.projectId,- scope: "batchExport:create",- });-- const { projectId, query, format, name } = input;- console.log(- "[TRPC] Creating export job",- JSON.stringify(input, null, 2),- );- const userId = ctx.session.user.id;-- // Create export job- const exportJob = await ctx.prisma.batchExport.create({- data: {- projectId,- userId,- status: BatchExportStatus.QUEUED,- name,- format,- query,- },- });-- // Create audit log- await auditLog({- session: ctx.session,- resourceType: "batchExport",- resourceId: exportJob.id,- projectId,- action: "create",- after: exportJob,- });-- // Notify worker- await BatchExportQueue.getInstance()?.add(QueueJobs.BatchExportJob, {- id: exportJob.id, // Use the batchExportId to deduplicate when the same job is sent multiple times- name: QueueJobs.BatchExportJob,- timestamp: new Date(),- payload: {- batchExportId: exportJob.id,- projectId,- },- });- } catch (e) {- logger.error(e);- if (e instanceof TRPCError) {- throw e;- }- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Creating export job failed.",- });- }- }),-});