🪢 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(datasets): multi-select delete + shared ConfirmDialog (#14517)
Tobias Wochingerc76cae2b878c
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.tsindex fa4890bd90..b80848be09 100644--- a/packages/shared/src/features/batchAction/types.ts+++ b/packages/shared/src/features/batchAction/types.ts@@ -19,6 +19,7 @@ export enum BatchActionStatus {export enum ActionId {ScoreDelete = "score-delete",+ DatasetDelete = "dataset-delete",TraceDelete = "trace-delete",TraceAddToAnnotationQueue = "trace-add-to-annotation-queue",SessionAddToAnnotationQueue = "session-add-to-annotation-queue",@@ -35,6 +36,7 @@ export const BatchActionQuerySchema = z.object({orderBy,searchQuery: z.string().optional(),searchType: z.array(TracingSearchType).optional(),+ pathPrefix: z.string().optional(),// Dispatch-time snapshot of the user's v4 beta flag; routes the sessions// read stream to the events table instead of the legacy traces path.useEventsTable: z.boolean().optional(),diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.tsindex d88cbcd279..3971a79600 100644--- a/packages/shared/src/features/batchExport/types.ts+++ b/packages/shared/src/features/batchExport/types.ts@@ -46,20 +46,33 @@ export const exportOptions: Record<},} as const;-export const BatchExportQuerySchema = z.object({- tableName: z.enum(BatchTableNames),- filter: z.array(singleFilter).nullable(),- searchQuery: z.string().optional(),- searchType: z.array(TracingSearchType).optional(),- orderBy,- limit: z.number().optional(),- page: z.number().optional(),- // Snapshotted at dispatch time from the user's v4 beta flag. When true, the- // sessions export reads from the ClickHouse events table instead of the- // legacy traces path. Persisted in the job's query column so the worker reads- // the snapshot, never the live user record.- useEventsTable: z.boolean().optional(),-});+export const BatchExportQuerySchema = z+ .object({+ tableName: z.enum(BatchTableNames),+ filter: z.array(singleFilter).nullable(),+ searchQuery: z.string().optional(),+ searchType: z.array(TracingSearchType).optional(),+ orderBy,+ limit: z.number().optional(),+ page: z.number().optional(),+ // Snapshotted at dispatch time from the user's v4 beta flag. When true, the+ // sessions export reads from the ClickHouse events table instead of the+ // legacy traces path. Persisted in the job's query column so the worker reads+ // the snapshot, never the live user record.+ useEventsTable: z.boolean().optional(),+ })+ // Reject `datasets` at runtime, not by narrowing the `tableName` enum:+ // BatchExportQueryType is shared with the batch-action read stream (which+ // handles every table), so a narrowed type breaks the worker typecheck.+ .superRefine((query, ctx) => {+ if (query.tableName === BatchTableNames.Datasets) {+ ctx.addIssue({+ code: "custom",+ path: ["tableName"],+ message: "datasets cannot be exported",+ });+ }+ });export type BatchExportQueryType = z.infer<typeof BatchExportQuerySchema>;diff --git a/packages/shared/src/interfaces/tableNames.ts b/packages/shared/src/interfaces/tableNames.tsindex d5a884cb0d..6f3829e5c3 100644--- a/packages/shared/src/interfaces/tableNames.ts+++ b/packages/shared/src/interfaces/tableNames.ts@@ -9,6 +9,7 @@ export enum BatchTableNames {Traces = "traces",Observations = "observations",Events = "events",+ Datasets = "datasets",DatasetRunItems = "dataset_run_items",DatasetItems = "dataset_items",AuditLogs = "audit_logs",diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 4785c05f3f..80d7e3f6f7 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -150,6 +150,15 @@ export const BatchActionProcessingEventSchema = z.discriminatedUnion(targetId: z.string().optional(),type: z.enum(BatchActionType),}),+ z.object({+ actionId: z.literal("dataset-delete"),+ projectId: z.string(),+ query: BatchActionQuerySchema,+ tableName: z.enum(BatchTableNames),+ cutoffCreatedAt: z.date(),+ targetId: z.string().optional(),+ type: z.enum(BatchActionType),+ }),z.object({actionId: z.literal("trace-delete"),projectId: z.string(),diff --git a/packages/shared/src/server/repositories/datasets.ts b/packages/shared/src/server/repositories/datasets.tsnew file mode 100644index 0000000000..8163fb2e64--- /dev/null+++ b/packages/shared/src/server/repositories/datasets.ts@@ -0,0 +1,109 @@+import { prisma, type Prisma } from "../../db";+import { type BatchActionQuery } from "../../features/batchAction/types";+import { escapeSqlLikePattern } from "../utils/sqlLike";++type PrismaClientOrTransaction = typeof prisma | Prisma.TransactionClient;++// A folder is strictly a name prefix. A standalone dataset whose name equals the+// folder path is rendered as its own row and must be deleted via its id only —+// matching `name = folderPath` here would silently delete that sibling dataset.+function buildDatasetFolderWhere(folderPath: string): Prisma.DatasetWhereInput {+ return { name: { startsWith: `${escapeSqlLikePattern(folderPath)}/` } };+}++export async function findDatasetsForDeletion({+ client = prisma,+ datasetIds,+ folderPaths,+ projectId,+}: {+ client?: PrismaClientOrTransaction;+ datasetIds: string[];+ folderPaths: string[];+ projectId: string;+}) {+ if (datasetIds.length === 0 && folderPaths.length === 0) return [];++ const explicitDeleteWhere: Prisma.DatasetWhereInput[] = [+ { id: { in: datasetIds } },+ ...folderPaths.map(buildDatasetFolderWhere),+ ];++ return client.dataset.findMany({+ where: {+ projectId,+ OR: explicitDeleteWhere,+ },+ });+}++export async function findDatasetIdsForBatchDeletion({+ cutoffCreatedAt,+ projectId,+ query,+}: {+ cutoffCreatedAt: Date;+ projectId: string;+ query: BatchActionQuery;+}): Promise<Array<{ id: string }>> {+ const where: Prisma.DatasetWhereInput = {+ projectId,+ createdAt: { lte: cutoffCreatedAt },+ };++ // Match the listing predicate (resolveSearchCondition) exactly: it ILIKEs the+ // raw query, only trimming to test emptiness. Trimming here too would delete a+ // broader set than the table shows for a whitespace-padded search.+ if (query.searchQuery && query.searchQuery.trim() !== "") {+ where.name = {+ contains: query.searchQuery,+ mode: "insensitive",+ };+ }++ if (query.pathPrefix) {+ where.AND = [buildDatasetFolderWhere(query.pathPrefix)];+ }++ return prisma.dataset.findMany({+ where,+ select: { id: true },+ });+}++export async function findDatasetIdsByIds({+ datasetIds,+ projectId,+}: {+ datasetIds: string[];+ projectId: string;+}): Promise<Array<{ id: string }>> {+ if (datasetIds.length === 0) return [];++ return prisma.dataset.findMany({+ where: {+ projectId,+ id: { in: datasetIds },+ },+ select: { id: true },+ });+}++export async function deleteDatasetsByIds({+ client = prisma,+ datasetIds,+ projectId,+}: {+ client?: PrismaClientOrTransaction;+ datasetIds: string[];+ projectId: string;+}) {+ if (datasetIds.length === 0) return;++ await client.dataset.deleteMany({+ where: {+ projectId,+ id: { in: datasetIds },+ },+ });+}diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 450a065949..2e527f176b 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -18,6 +18,7 @@ export * from "./dataset-run-items-converters";export * from "./dataset-run-items";export * from "./dataset-items-columns";export * from "./dataset-items";+export * from "./datasets";export * from "./dataset-item-media";export * from "./comments";export * from "./experiments";diff --git a/web/src/__tests__/server/datasets-trpc.servertest.ts b/web/src/__tests__/server/datasets-trpc.servertest.tsindex 196cead89f..6bac063eff 100644--- a/web/src/__tests__/server/datasets-trpc.servertest.ts+++ b/web/src/__tests__/server/datasets-trpc.servertest.ts@@ -127,6 +127,54 @@ describe("datasets trpc", () => {});});+ describe("datasets.deleteMany", () => {+ it("deletes explicitly selected datasets and folder subtrees", async () => {+ const { project, caller } = await prepare();+ const selectedDatasetId = v4();++ await prisma.dataset.createMany({+ data: [+ {+ id: selectedDatasetId,+ name: "selected",+ projectId: project.id,+ },+ {+ id: v4(),+ name: "folder/child",+ projectId: project.id,+ },+ {+ id: v4(),+ name: "folder/nested/child",+ projectId: project.id,+ },+ {+ id: v4(),+ name: "folder-sibling/child",+ projectId: project.id,+ },+ ],+ });++ await expect(+ caller.datasets.deleteMany({+ projectId: project.id,+ datasetIds: [selectedDatasetId],+ folderPaths: ["folder"],+ }),+ ).resolves.toEqual({ deletedCount: 3 });++ await expect(+ prisma.dataset.findMany({+ where: { projectId: project.id },+ select: { name: true },+ orderBy: { name: "asc" },+ }),+ ).resolves.toEqual([{ name: "folder-sibling/child" }]);+ });+ });+describe("datasets.triggerRemoteExperiment", () => {it("should execute remote experiments through the secure webhook fetch helper", async () => {const { project, caller } = await prepare();diff --git a/web/src/__tests__/server/repositories/datasets-repository.servertest.ts b/web/src/__tests__/server/repositories/datasets-repository.servertest.tsnew file mode 100644index 0000000000..4b03ba03b1--- /dev/null+++ b/web/src/__tests__/server/repositories/datasets-repository.servertest.ts@@ -0,0 +1,266 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ createOrgProjectAndApiKey,+ deleteDatasetsByIds,+ findDatasetIdsByIds,+ findDatasetIdsForBatchDeletion,+ findDatasetsForDeletion,+} from "@langfuse/shared/src/server";+import { v4 } from "uuid";+import { afterAll, describe, expect, it } from "vitest";++const orgIds: string[] = [];++async function createProject() {+ const { org, project } = await createOrgProjectAndApiKey();+ orgIds.push(org.id);++ return project;+}++async function createDataset({+ createdAt,+ name,+ projectId,+}: {+ createdAt?: Date;+ name: string;+ projectId: string;+}) {+ return prisma.dataset.create({+ data: {+ id: v4(),+ createdAt,+ name,+ projectId,+ },+ });+}++describe("datasets repository", () => {+ afterAll(async () => {+ await prisma.organization.deleteMany({+ where: {+ id: { in: orgIds },+ },+ });+ });++ it("finds datasets selected directly or via folder subtrees, without the same-named standalone dataset", async () => {+ const project = await createProject();+ const otherProject = await createProject();+ const selectedDataset = await createDataset({+ name: `selected-${v4()}`,+ projectId: project.id,+ });+ // Standalone dataset named exactly like the folder — its own row, must NOT+ // be deleted when only the "folder" subtree is targeted.+ const standaloneFolderNamedDataset = await createDataset({+ name: "folder",+ projectId: project.id,+ });+ const nestedFolderDataset = await createDataset({+ name: "folder/nested",+ projectId: project.id,+ });+ await createDataset({+ name: "folder-sibling/nested",+ projectId: project.id,+ });+ await createDataset({+ name: selectedDataset.name,+ projectId: otherProject.id,+ });++ const datasets = await findDatasetsForDeletion({+ projectId: project.id,+ datasetIds: [selectedDataset.id],+ folderPaths: ["folder"],+ });++ const ids = datasets.map((dataset) => dataset.id);+ expect(ids.sort()).toEqual(+ [nestedFolderDataset.id, selectedDataset.id].sort(),+ );+ expect(ids).not.toContain(standaloneFolderNamedDataset.id);+ });++ it("treats SQL LIKE wildcards in folder names literally, sparing unrelated siblings", async () => {+ const project = await createProject();+ // Folder names derive from dataset names and can contain `%` / `_`. Without+ // escaping, deleting folder "100%" or "a_b" would also wipe siblings whose+ // names happen to match the wildcard (e.g. "1000/x", "aXb/x").+ const percentChild = await createDataset({+ name: "100%/child",+ projectId: project.id,+ });+ const percentSibling = await createDataset({+ name: "1000/sibling",+ projectId: project.id,+ });+ const underscoreChild = await createDataset({+ name: "a_b/child",+ projectId: project.id,+ });+ const underscoreSibling = await createDataset({+ name: "aXb/sibling",+ projectId: project.id,+ });++ const deleted = await findDatasetsForDeletion({+ projectId: project.id,+ datasetIds: [],+ folderPaths: ["100%", "a_b"],+ });++ const deletedIds = deleted.map((dataset) => dataset.id);+ expect(deletedIds.sort()).toEqual(+ [percentChild.id, underscoreChild.id].sort(),+ );+ expect(deletedIds).not.toContain(percentSibling.id);+ expect(deletedIds).not.toContain(underscoreSibling.id);+ });++ it("returns no deletion candidates without explicit dataset or folder inputs", async () => {+ const project = await createProject();+ await createDataset({+ name: `unselected-${v4()}`,+ projectId: project.id,+ });++ await expect(+ findDatasetsForDeletion({+ projectId: project.id,+ datasetIds: [],+ folderPaths: [],+ }),+ ).resolves.toEqual([]);+ });++ it("finds batch deletion dataset ids with cutoff, search query, and folder path", async () => {+ const project = await createProject();+ const otherProject = await createProject();+ const cutoffCreatedAt = new Date("2024-01-02T00:00:00.000Z");+ const matchingDataset = await createDataset({+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ name: "folder/target-dataset",+ projectId: project.id,+ });+ await createDataset({+ createdAt: new Date("2024-01-03T00:00:00.000Z"),+ name: "folder/target-too-new",+ projectId: project.id,+ });+ await createDataset({+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ name: "other/target-dataset",+ projectId: project.id,+ });+ await createDataset({+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ name: "folder/not-matching",+ projectId: project.id,+ });+ await createDataset({+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ name: "folder/target-dataset",+ projectId: otherProject.id,+ });++ const datasets = await findDatasetIdsForBatchDeletion({+ projectId: project.id,+ cutoffCreatedAt,+ query: {+ filter: null,+ orderBy: { column: "createdAt", order: "DESC" },+ searchQuery: "target",+ pathPrefix: "folder",+ },+ });++ expect(datasets).toEqual([{ id: matchingDataset.id }]);+ });++ it("finds selected dataset ids scoped to a project", async () => {+ const project = await createProject();+ const otherProject = await createProject();+ const selectedDataset = await createDataset({+ name: `selected-${v4()}`,+ projectId: project.id,+ });+ const otherDataset = await createDataset({+ name: `other-${v4()}`,+ projectId: otherProject.id,+ });++ const datasets = await findDatasetIdsByIds({+ projectId: project.id,+ datasetIds: [selectedDataset.id, otherDataset.id],+ });++ expect(datasets).toEqual([{ id: selectedDataset.id }]);+ });++ it("deletes datasets by ids scoped to a project", async () => {+ const project = await createProject();+ const otherProject = await createProject();+ const datasetToDelete = await createDataset({+ name: `delete-${v4()}`,+ projectId: project.id,+ });+ const datasetToKeep = await createDataset({+ name: `keep-${v4()}`,+ projectId: project.id,+ });+ const otherProjectDataset = await createDataset({+ name: `other-${v4()}`,+ projectId: otherProject.id,+ });++ await deleteDatasetsByIds({+ projectId: project.id,+ datasetIds: [datasetToDelete.id, otherProjectDataset.id],+ });++ await expect(+ prisma.dataset.findMany({+ where: { projectId: project.id },+ select: { id: true },+ }),+ ).resolves.toEqual([{ id: datasetToKeep.id }]);+ await expect(+ prisma.dataset.findUnique({+ where: {+ id_projectId: {+ id: otherProjectDataset.id,+ projectId: otherProject.id,+ },+ },+ }),+ ).resolves.toMatchObject({ id: otherProjectDataset.id });+ });++ it("skips deletion when no dataset ids are provided", async () => {+ const project = await createProject();+ const dataset = await createDataset({+ name: `keep-${v4()}`,+ projectId: project.id,+ });++ await deleteDatasetsByIds({+ projectId: project.id,+ datasetIds: [],+ });++ await expect(+ prisma.dataset.findUnique({+ where: {+ id_projectId: {+ id: dataset.id,+ projectId: project.id,+ },+ },+ }),+ ).resolves.toMatchObject({ id: dataset.id });+ });+});diff --git a/web/src/components/table/data-table-multi-select-actions/data-table-select-all-banner.tsx b/web/src/components/table/data-table-multi-select-actions/data-table-select-all-banner.tsxindex 9a8281576c..daacf4f7af 100644--- a/web/src/components/table/data-table-multi-select-actions/data-table-select-all-banner.tsx+++ b/web/src/components/table/data-table-multi-select-actions/data-table-select-all-banner.tsx@@ -8,8 +8,11 @@ export function DataTableSelectAllBanner({setRowSelection,pageSize,totalCount,+ approximateCount,}: MultiSelect) {const totalPages = totalCount ? Math.ceil(totalCount / pageSize) : null;+ // Hide the precise number when the row count is not the affected-entity count.+ const exactCount = approximateCount ? null : totalCount;return (<div className="bg-light-blue/40 dark:bg-light-blue/50 @container mb-2 flex flex-wrap items-center justify-center gap-2 rounded-sm p-2">@@ -17,7 +20,7 @@ export function DataTableSelectAllBanner({<span className="text-sm">All{" "}<span className="font-semibold">- {totalCount === null ? "matching" : numberFormatter(totalCount, 0)}+ {exactCount === null ? "matching" : numberFormatter(exactCount, 0)}</span>{" "}items are selected.{" "}<Button@@ -33,8 +36,9 @@ export function DataTableSelectAllBanner({</span>) : (<span className="text-sm">- All <span className="font-semibold">{pageSize}</span> items on this- page are selected.{" "}+ All{" "}+ <span className="font-semibold">{numberFormatter(pageSize, 0)}</span>{" "}+ items on this page are selected.{" "}<Buttonvariant="ghost"className="text-accent-dark-blue hover:text-accent-dark-blue/80 h-auto p-0 font-semibold"@@ -42,10 +46,10 @@ export function DataTableSelectAllBanner({setSelectAll(true);}}>- {totalCount === null || totalPages === null+ {exactCount === null || totalPages === null? "Select all matching items": `Select all ${numberFormatter(- totalCount,+ exactCount,0,)} items across ${numberFormatter(totalPages, 0)} pages`}</Button>diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex 59b633c5a6..6f3b87d8c7 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -66,6 +66,10 @@ export interface MultiSelect {pageSize: number;pageIndex: number;totalCount: number | null;+ // When the displayed row count does not equal the number of affected entities+ // (e.g. datasets where a folder row expands to many datasets on delete), the+ // select-all banner drops the precise number and says "matching" instead.+ approximateCount?: boolean;}interface SearchConfig {@@ -218,6 +222,16 @@ export function DataTableToolbar<TData, TValue>({const showSearchTypeSelector = Boolean(searchConfig?.setSearchType && searchConfig.tableAllowsFullTextSearch,);+ const allVisibleRowsSelected = Boolean(+ multiSelect &&+ multiSelect.totalCount !== null &&+ multiSelect.totalCount > multiSelect.pageSize &&+ multiSelect.pageIndex === 0 &&+ multiSelect.selectedRowIds.length > 0 &&+ multiSelect.selectedRowIds.length ===+ Math.min(multiSelect.pageSize, multiSelect.totalCount),+ );+const submitSearch = (query: string) => {if (searchConfig?.setSearchType &&@@ -455,11 +469,9 @@ export function DataTableToolbar<TData, TValue>({{actionButtons}</div></div>- {multiSelect &&- multiSelect.pageIndex === 0 &&- multiSelect.selectedRowIds.length === multiSelect.pageSize && (- <DataTableSelectAllBanner {...multiSelect} />- )}+ {multiSelect && allVisibleRowsSelected && (+ <DataTableSelectAllBanner {...multiSelect} />+ )}</div>);}diff --git a/web/src/components/ui/confirm-dialog.tsx b/web/src/components/ui/confirm-dialog.tsxnew file mode 100644index 0000000000..95a08b8a64--- /dev/null+++ b/web/src/components/ui/confirm-dialog.tsx@@ -0,0 +1,106 @@+import * as React from "react";+import { cva, type VariantProps } from "class-variance-authority";++import { Button, type ButtonProps } from "@/src/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";++// Constrained width tokens (no free-form className) — `lg` is for confirms whose+// body carries longer content, e.g. a type-to-confirm field with a long name.+const confirmDialogContentVariants = cva("", {+ variants: {+ size: {+ default: "sm:max-w-md",+ lg: "sm:max-w-2xl",+ },+ },+ defaultVariants: {+ size: "default",+ },+});++/**+ * Shared chrome for confirmation dialogs (delete/destructive actions). Owns the+ * borderless ("action") header/footer, description-in-body placement, and the+ * cancel/confirm footer so every confirm modal looks and behaves the same.+ * Callers keep their own access checks and mutation logic; pass extra content+ * (e.g. type-to-confirm input) via `children`.+ */+export function ConfirmDialog({+ open,+ onOpenChange,+ title,+ description,+ trigger,+ confirmLabel = "Confirm",+ confirmVariant = "destructive",+ cancelLabel = "Cancel",+ onConfirm,+ loading = false,+ confirmDisabled = false,+ size,+ children,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ title: React.ReactNode;+ description?: React.ReactNode;+ trigger?: React.ReactNode;+ confirmLabel?: string;+ confirmVariant?: ButtonProps["variant"];+ cancelLabel?: string;+ onConfirm: () => void | Promise<void>;+ loading?: boolean;+ confirmDisabled?: boolean;+ children?: React.ReactNode;+} & VariantProps<typeof confirmDialogContentVariants>) {+ return (+ <Dialog+ open={open}+ // Ignore close requests (Esc / X / outside click / Cancel) while the+ // action is in flight, so a confirm can't be dismissed mid-mutation.+ onOpenChange={(next) => {+ if (loading && !next) return;+ onOpenChange(next);+ }}+ >+ {trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}+ <DialogContent className={confirmDialogContentVariants({ size })}>+ <DialogHeader variant="action">+ <DialogTitle>{title}</DialogTitle>+ </DialogHeader>+ <DialogBody>+ {description ? (+ <DialogDescription>{description}</DialogDescription>+ ) : null}+ {children}+ </DialogBody>+ <DialogFooter variant="action">+ <Button+ variant="outline"+ disabled={loading}+ onClick={() => onOpenChange(false)}+ >+ {cancelLabel}+ </Button>+ <Button+ variant={confirmVariant}+ loading={loading}+ disabled={confirmDisabled}+ onClick={onConfirm}+ >+ {confirmLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsxindex 4fcb9465af..3e0747b780 100644--- a/web/src/components/ui/dialog.tsx+++ b/web/src/components/ui/dialog.tsx@@ -151,15 +151,34 @@ const DialogContent = React.forwardRef<);DialogContent.displayName = DialogPrimitive.Content.displayName;+const dialogHeaderVariants = cva(+ "bg-background sticky top-0 z-30 flex shrink-0 flex-col space-y-1.5 rounded-t-lg p-4",+ {+ variants: {+ variant: {+ default: "border-b",+ // Borderless confirm dialogs drop the divider, so trim the bottom+ // padding to keep title and body from drifting apart.+ action: "pb-2",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ },+);+const DialogHeader = ({className,children,+ variant,...props-}: React.HTMLAttributes<HTMLDivElement>) => (+}: React.HTMLAttributes<HTMLDivElement> &+ VariantProps<typeof dialogHeaderVariants>) => (<divclassName={cn(- "dialog-header bg-background sticky top-0 z-30 flex shrink-0 flex-col space-y-1.5 rounded-t-lg border-b p-4",- className,+ "dialog-header",+ dialogHeaderVariants({ variant, className }),)}{...props}>@@ -189,14 +208,33 @@ const DialogBody = React.forwardRef<));DialogBody.displayName = "DialogBody";+const dialogFooterVariants = cva(+ "bg-background sticky bottom-0 z-10 flex shrink-0 flex-col-reverse rounded-b-lg p-6 px-6 sm:flex-row sm:justify-end sm:space-x-2",+ {+ variants: {+ variant: {+ default: "border-t",+ // Borderless confirm dialogs drop the divider, so trim the top padding+ // to pull the buttons closer to the content.+ action: "pt-2",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ },+);+const DialogFooter = ({className,+ variant,...props-}: React.HTMLAttributes<HTMLDivElement>) => (+}: React.HTMLAttributes<HTMLDivElement> &+ VariantProps<typeof dialogFooterVariants>) => (<divclassName={cn(- "dialog-footer bg-background sticky bottom-0 z-10 flex shrink-0 flex-col-reverse rounded-b-lg border-t p-6 px-6 sm:flex-row sm:justify-end sm:space-x-2",- className,+ "dialog-footer",+ dialogFooterVariants({ variant, className }),)}{...props}/>diff --git a/web/src/features/datasets/components/DatasetActionButton.tsx b/web/src/features/datasets/components/DatasetActionButton.tsxindex c12c99439b..58396253fd 100644--- a/web/src/features/datasets/components/DatasetActionButton.tsx+++ b/web/src/features/datasets/components/DatasetActionButton.tsx@@ -3,10 +3,12 @@ import { Edit, LockIcon, Pen, PlusIcon, Trash } from "lucide-react";import {Dialog,DialogContent,- DialogDescription,DialogHeader,DialogTitle,} from "@/src/components/ui/dialog";+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";+import { Input } from "@/src/components/ui/input";+import { Label } from "@/src/components/ui/label";import { useState, forwardRef } from "react";import { DialogTrigger } from "@radix-ui/react-dialog";import { DatasetForm } from "@/src/features/datasets/components/DatasetForm";@@ -14,6 +16,7 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { type Prisma } from "@langfuse/shared";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { IconOnlyButton } from "@/src/components/IconOnlyButton";+import { api } from "@/src/utils/api";interface BaseDatasetButtonProps {mode: "create" | "update" | "delete";@@ -57,10 +60,13 @@ export const DatasetActionButton = forwardRef<>((props, ref) => {const capture = usePostHogClientCapture();const [open, setOpen] = useState(false);+ const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");const hasAccess = useHasProjectAccess({projectId: props.projectId,scope: "datasets:CUD",});+ const utils = api.useUtils();+ const deleteMutation = api.datasets.deleteDataset.useMutation();const actionButton =props.mode === "update" ? (@@ -176,6 +182,53 @@ export const DatasetActionButton = forwardRef<// so they are rendered directly rather than as an asChild dialog trigger.const isIconMode = props.mode !== "create" && props.icon;+ if (props.mode === "delete") {+ const { projectId, datasetId, datasetName } = props;+ const handleDelete = async () => {+ capture("datasets:delete_form_submit");+ try {+ await deleteMutation.mutateAsync({ projectId, datasetId });+ utils.datasets.invalidate();+ setDeleteConfirmationInput("");+ setOpen(false);+ } catch (error) {+ console.error(error);+ }+ };++ return (+ <>+ {isIconMode ? actionButton : null}+ <ConfirmDialog+ open={hasAccess && open}+ onOpenChange={(isOpen) => {+ setOpen(isOpen);+ if (!isOpen) setDeleteConfirmationInput("");+ }}+ trigger={isIconMode ? undefined : actionButton}+ size="lg"+ title="Please confirm"+ description="This action cannot be undone and removes all the data associated with this dataset."+ confirmLabel="Delete dataset"+ confirmDisabled={deleteConfirmationInput !== datasetName}+ loading={deleteMutation.isPending}+ onConfirm={handleDelete}+ >+ <div className="grid w-full gap-1.5">+ <Label htmlFor="delete-confirmation">+ Type "{datasetName}" to confirm deletion+ </Label>+ <Input+ id="delete-confirmation"+ value={deleteConfirmationInput}+ onChange={(e) => setDeleteConfirmationInput(e.target.value)}+ />+ </div>+ </ConfirmDialog>+ </>+ );+ }+return (<Dialog open={hasAccess && open} onOpenChange={setOpen}>{isIconMode ? (@@ -185,19 +238,9 @@ export const DatasetActionButton = forwardRef<)}<DialogContent className="max-h-[90vh] sm:max-w-2xl md:max-w-3xl"><DialogHeader>- <DialogTitle className="mb-4">- {props.mode === "create"- ? "Create new dataset"- : props.mode === "delete"- ? "Please confirm"- : "Update dataset"}+ <DialogTitle>+ {props.mode === "create" ? "Create new dataset" : "Update dataset"}</DialogTitle>- {props.mode === "delete" && (- <DialogDescription className="p-0">- This action cannot be undone and removes all the data associated- with this dataset.- </DialogDescription>- )}</DialogHeader>{props.mode === "create" ? (@@ -207,14 +250,6 @@ export const DatasetActionButton = forwardRef<onFormSuccess={() => setOpen(false)}folderPrefix={props.folderPrefix}/>- ) : props.mode === "delete" ? (- <DatasetForm- mode="delete"- projectId={props.projectId}- onFormSuccess={() => setOpen(false)}- datasetId={props.datasetId}- datasetName={props.datasetName}- />) : (<DatasetFormmode="update"diff --git a/web/src/features/datasets/components/DatasetForm.tsx b/web/src/features/datasets/components/DatasetForm.tsxindex b95e53d30b..2318930945 100644--- a/web/src/features/datasets/components/DatasetForm.tsx+++ b/web/src/features/datasets/components/DatasetForm.tsx@@ -28,7 +28,6 @@ import {type Prisma,} from "@langfuse/shared";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { Label } from "@/src/components/ui/label";import { useRouter } from "next/router";import { useUniqueNameValidation } from "@/src/hooks/useUniqueNameValidation";import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";@@ -51,7 +50,7 @@ export interface DatasetFormRef {}interface BaseDatasetFormProps {- mode: "create" | "update" | "delete";+ mode: "create" | "update";projectId: string;onFormSuccess?: () => void;onCreateDatasetSuccess?: (params: {@@ -71,12 +70,6 @@ interface CreateDatasetFormProps extends BaseDatasetFormProps {folderPrefix?: string;}-interface DeleteDatasetFormProps extends BaseDatasetFormProps {- mode: "delete";- datasetName: string;- datasetId: string;-}-interface UpdateDatasetFormProps extends BaseDatasetFormProps {mode: "update";datasetId: string;@@ -87,10 +80,7 @@ interface UpdateDatasetFormProps extends BaseDatasetFormProps {datasetExpectedOutputSchema?: Prisma.JsonValue;}-type DatasetFormProps =- | CreateDatasetFormProps- | UpdateDatasetFormProps- | DeleteDatasetFormProps;+type DatasetFormProps = CreateDatasetFormProps | UpdateDatasetFormProps;// Validation schema for JSON Schema stringsexport const jsonSchemaStringValidator = z.string().refine(@@ -141,7 +131,6 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(setServerSideSchemaValidationErrors,] = useState<ServerSideSchemaValidationErrors | null>(null);const capture = usePostHogClientCapture();- const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");const inputSchemaString =props.mode === "update" && props.datasetInputSchema@@ -181,7 +170,6 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(const router = useRouter();const createMutation = api.datasets.createDataset.useMutation();const updateMutation = api.datasets.updateDataset.useMutation();- const deleteMutation = api.datasets.deleteDataset.useMutation();const allDatasets = api.datasets.allDatasetMeta.useQuery({ projectId: props.projectId },@@ -217,8 +205,7 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(const isValid = form.formState.isValid && !form.formState.errors.name;const isSubmitting =(mode === "create" && createMutation.isPending) ||- (mode === "update" && updateMutation.isPending) ||- (mode === "delete" && deleteMutation.isPending);+ (mode === "update" && updateMutation.isPending);const prev = prevValidationRef.current;if (@@ -235,7 +222,6 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(form.formState.errors.name,createMutation.isPending,updateMutation.isPending,- deleteMutation.isPending,mode,onValidationChange,]);@@ -245,13 +231,11 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(ref,() => ({submit: () => {- if (props.mode !== "delete") {- form.handleSubmit(onSubmit)();- }+ form.handleSubmit(onSubmit)();},}),// eslint-disable-next-line react-hooks/exhaustive-deps- [props.mode],+ [],);function onSubmit(values: z.infer<typeof formSchema>) {@@ -333,167 +317,119 @@ export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(}}- const handleDelete = (e: React.SyntheticEvent) => {- e.preventDefault();-- // helps with type safety- if (props.mode !== "delete") return;-- if (deleteConfirmationInput !== props.datasetName) {- setFormError(- "Please type the correct dataset name to confirm deletion",- );- return;- }-- capture("datasets:delete_form_submit");- deleteMutation- .mutateAsync({- projectId: props.projectId,- datasetId: props.datasetId,- })- .then(() => {- utils.datasets.invalidate();- form.reset();- })- .catch((error: Error) => {- setFormError(error.message);- console.error(error);- });- };-return (<Form {...form}><form- onSubmit={- props.mode === "delete" ? handleDelete : form.handleSubmit(onSubmit)- }+ onSubmit={form.handleSubmit(onSubmit)}className="flex h-full min-h-0 flex-col"><DialogBodyclassName={props.showFooter === false ? "p-0" : undefined}>- {props.mode === "delete" ? (- <div className="mb-8 grid w-full gap-1.5">- <Label htmlFor="delete-confirmation">- Type "{props.datasetName}" to confirm deletion- </Label>- <Input- id="delete-confirmation"- value={deleteConfirmationInput}- onChange={(e) => setDeleteConfirmationInput(e.target.value)}- />- </div>- ) : (- <div className="mb-8 space-y-6">- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Name</FormLabel>- <FormDescription>- Use slashes '/' in dataset names to organize- them into <em>folders</em>.- </FormDescription>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="description"- render={({ field }) => (- <FormItem>- <FormLabel>Description (optional)</FormLabel>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="metadata"- render={({ field }) => (- <FormItem>- <FormLabel>Metadata (optional)</FormLabel>- <FormControl>- <CodeMirrorEditor- mode="json"- value={field.value}- onChange={(v) => {- field.onChange(v);- }}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="inputSchema"- render={({ field }) => (- <DatasetSchemaInput- label="Input schema"- description="Validate dataset item inputs against a JSON Schema. All new and existing items must conform to this schema."- value={field.value}- onChange={field.onChange}- initialValue={inputSchemaString}- />- )}- />- <FormField- control={form.control}- name="expectedOutputSchema"- render={({ field }) => (- <DatasetSchemaInput- label="Expected output schema"- description="Validate dataset item expected outputs against a JSON Schema. All new and existing items must conform to this schema."- value={field.value}- onChange={field.onChange}- initialValue={expectedOutputSchemaString}- />- )}- />-- {/* Show validation errors inline with form */}- {serverSideSchemaValidationErrors && (- <DatasetSchemaValidationError- projectId={props.projectId}- datasetId={- props.mode === "update" ? props.datasetId : "unknown"- }- errors={serverSideSchemaValidationErrors}+ <div className="mb-8 space-y-6">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormDescription>+ Use slashes '/' in dataset names to organize+ them into <em>folders</em>.+ </FormDescription>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Description (optional)</FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="metadata"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Metadata (optional)</FormLabel>+ <FormControl>+ <CodeMirrorEditor+ mode="json"+ value={field.value}+ onChange={(v) => {+ field.onChange(v);+ }}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="inputSchema"+ render={({ field }) => (+ <DatasetSchemaInput+ label="Input schema"+ description="Validate dataset item inputs against a JSON Schema. All new and existing items must conform to this schema."+ value={field.value}+ onChange={field.onChange}+ initialValue={inputSchemaString}/>)}- </div>- )}+ />+ <FormField+ control={form.control}+ name="expectedOutputSchema"+ render={({ field }) => (+ <DatasetSchemaInput+ label="Expected output schema"+ description="Validate dataset item expected outputs against a JSON Schema. All new and existing items must conform to this schema."+ value={field.value}+ onChange={field.onChange}+ initialValue={expectedOutputSchemaString}+ />+ )}+ />++ {/* Show validation errors inline with form */}+ {serverSideSchemaValidationErrors && (+ <DatasetSchemaValidationError+ projectId={props.projectId}+ datasetId={+ props.mode === "update" ? props.datasetId : "unknown"+ }+ errors={serverSideSchemaValidationErrors}+ />+ )}+ </div></DialogBody>{props.showFooter !== false && (<DialogFooter><div className="flex w-full flex-col gap-4"><Buttontype="submit"- variant={props.mode === "delete" ? "destructive" : "default"}disabled={!!form.formState.errors.name}loading={(props.mode === "create" && createMutation.isPending) ||- (props.mode === "update" && updateMutation.isPending) ||- (props.mode === "delete" && deleteMutation.isPending)+ (props.mode === "update" && updateMutation.isPending)}className="w-full">{props.mode === "create"? "Create dataset"- : props.mode === "delete"- ? "Delete Dataset"- : "Update dataset"}+ : "Update dataset"}</Button>{formError && (<p className="mt-4 text-center text-sm text-red-500">diff --git a/web/src/features/datasets/components/DatasetsTable.tsx b/web/src/features/datasets/components/DatasetsTable.tsxindex eea8ab41fb..df7b14297a 100644--- a/web/src/features/datasets/components/DatasetsTable.tsx+++ b/web/src/features/datasets/components/DatasetsTable.tsx@@ -7,10 +7,14 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/contextimport { api } from "@/src/utils/api";import { withDefault, useQueryParam, StringParam } from "use-query-params";import { type RouterOutput } from "@/src/utils/types";-import { useEffect, useMemo } from "react";+import { useEffect, useMemo, useState } from "react";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";-import { TableViewPresetTableName, type Prisma } from "@langfuse/shared";+import {+ TableViewPresetTableName,+ type Prisma,+ type TableViewPresetState,+} from "@langfuse/shared";import { IOTableCell } from "@/src/components/ui/IOTableCell";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";@@ -21,8 +25,26 @@ import { useFolderPagination } from "@/src/features/folders/hooks/useFolderPaginimport { FolderBreadcrumb } from "@/src/features/folders/components/FolderBreadcrumb";import { buildFullPath } from "@/src/features/folders/utils";import { FolderBreadcrumbLink } from "@/src/features/folders/components/FolderBreadcrumbLink";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import {+ createDatasetsTableStore,+ toFolderRowId,+ type DatasetsTableStore,+} from "@/src/features/datasets/store/datasetsTableStore";+import { useDatasetsTableSelectionSync } from "@/src/features/datasets/hooks/useDatasetsTableSelectionSync";+import { useStore } from "zustand";+import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";+import {+ ActionId,+ BatchActionType,+ BatchExportTableName,+} from "@langfuse/shared";+import { type TableAction } from "@/src/features/table/types";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";type DatasetTableRow = {+ id: string;key: {id: string;name: string; // Display name (segment only)@@ -39,6 +61,13 @@ type DatasetTableRow = {expectedOutputSchema?: Prisma.JsonValue | null;};+type DatasetTableViewControllers = {+ applyViewState: (viewData: TableViewPresetState) => void;+ selectedViewId: string | null;+ appliedViewId: string | null;+ handleSetViewId: (viewId: string | null) => void;+};+function createRow(data: Partial<DatasetTableRow> & {key: {@@ -50,6 +79,7 @@ function createRow(},): DatasetTableRow {return {+ id: data.isFolder ? toFolderRowId(data.folderPath) : data.key.id,description: null,createdAt: null,lastRunAt: null,@@ -62,9 +92,171 @@ function createRow(};}+function DatasetsMultiSelectActionMenu({+ currentFolderPath,+ projectId,+ searchQuery,+ store,+}: {+ currentFolderPath: string | undefined;+ projectId: string;+ searchQuery: string | null;+ store: DatasetsTableStore;+}) {+ const selectAll = useStore(store, (state) => state.selectAll);+ const selectedCount = useStore(+ store,+ (state) => state.selectedPageRowIds.length,+ );+ const clearSelection = useStore(+ store,+ (state) => state.actions.clearSelection,+ );+ const deleteSelected = useStore(+ store,+ (state) => state.actions.deleteSelected,+ );+ const capture = usePostHogClientCapture();+ const utils = api.useUtils();+ const deleteManyMutation = api.datasets.deleteMany.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Datasets deleted",+ description:+ "Selected datasets will be deleted. Associated run items and media links are cleaned up asynchronously.",+ });+ },+ onSettled: () => {+ utils.datasets.invalidate();+ },+ });++ if (selectedCount === 0 && !selectAll) return null;++ const tableActions: TableAction[] = [+ {+ id: ActionId.DatasetDelete,+ type: BatchActionType.Delete,+ label: "Delete",+ description:+ "This action cannot be undone. Selected folders delete all datasets contained in them.",+ accessCheck: {+ scope: "datasets:CUD",+ },+ execute: ({ projectId }) =>+ deleteSelected({+ projectId,+ deleteMany: deleteManyMutation.mutateAsync,+ capture,+ scope: { folderPath: currentFolderPath, searchQuery },+ }),+ },+ ];++ return (+ <TableActionMenu+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Datasets}+ selectedCount={selectedCount}+ approximateCount={selectAll}+ onClearSelection={clearSelection}+ />+ );+}++function DatasetsTableToolbar({+ columnOrder,+ columnVisibility,+ columns,+ currentFolderPath,+ paginationState,+ projectId,+ rowHeight,+ searchQuery,+ setColumnOrder,+ setColumnVisibility,+ setRowHeight,+ setSearchQuery,+ store,+ totalCount,+ viewControllers,+}: {+ columnOrder: ReturnType<typeof useColumnOrder<DatasetTableRow>>[0];+ columnVisibility: ReturnType<typeof useColumnVisibility<DatasetTableRow>>[0];+ columns: LangfuseColumnDef<DatasetTableRow>[];+ currentFolderPath: string | undefined;+ paginationState: { pageIndex: number; pageSize: number };+ projectId: string;+ rowHeight: ReturnType<typeof useRowHeightLocalStorage>[0];+ searchQuery: string | null;+ setColumnOrder: ReturnType<typeof useColumnOrder<DatasetTableRow>>[1];+ setColumnVisibility: ReturnType<+ typeof useColumnVisibility<DatasetTableRow>+ >[1];+ setRowHeight: ReturnType<typeof useRowHeightLocalStorage>[1];+ setSearchQuery: (value: string | null | undefined) => void;+ store: DatasetsTableStore;+ totalCount: number | null;+ viewControllers: DatasetTableViewControllers;+}) {+ const selectAll = useStore(store, (state) => state.selectAll);+ const selectedPageRowIds = useStore(+ store,+ (state) => state.selectedPageRowIds,+ );+ const selectionActions = useStore(store, (state) => state.actions);++ return (+ <DataTableToolbar+ columns={columns}+ columnVisibility={columnVisibility}+ setColumnVisibility={setColumnVisibility}+ columnOrder={columnOrder}+ setColumnOrder={setColumnOrder}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ searchConfig={{+ metadataSearchFields: ["Name"],+ updateQuery: setSearchQuery,+ currentQuery: searchQuery ?? undefined,+ tableAllowsFullTextSearch: false,+ setSearchType: undefined,+ searchType: undefined,+ }}+ viewConfig={{+ tableName: TableViewPresetTableName.Datasets,+ projectId,+ controllers: viewControllers,+ }}+ actionButtons={[+ <DatasetsMultiSelectActionMenu+ key="datasets-multi-select-delete"+ currentFolderPath={currentFolderPath}+ projectId={projectId}+ searchQuery={searchQuery}+ store={store}+ />,+ ]}+ multiSelect={{+ selectAll,+ setSelectAll: selectionActions.setSelectAll,+ selectedRowIds: selectedPageRowIds,+ setRowSelection: selectionActions.setRowSelection,+ totalCount,+ // A folder row deletes every dataset under it, so the displayed row+ // count understates the true deletion scope — keep the banner vague.+ approximateCount: true,+ ...paginationState,+ }}+ />+ );+}+export function DatasetsTable(props: { projectId: string }) {const { setDetailPageList } = useDetailPageLists();const [rowHeight, setRowHeight] = useRowHeightLocalStorage("datasets", "s");+ const [datasetsTableStore] = useState(() => createDatasetsTableStore());const {paginationState,@@ -113,7 +305,16 @@ export function DatasetsTable(props: { projectId: string }) {// eslint-disable-next-line react-hooks/exhaustive-deps}, [datasets.isSuccess, datasets.data]);+ const { selectActionColumn } = TableSelectionManager<DatasetTableRow>({+ projectId: props.projectId,+ tableName: "datasets",+ setSelectedRows: datasetsTableStore.getState().actions.setRowSelection,+ setSelectAll: datasetsTableStore.getState().actions.setSelectAll,+ selectionStore: datasetsTableStore,+ });+const columns: LangfuseColumnDef<DatasetTableRow>[] = [+ selectActionColumn,{accessorKey: "key",header: "Name",@@ -355,6 +556,21 @@ export function DatasetsTable(props: { projectId: string }) {};}, [datasetsDatasetTableRow, currentFolderPath]);+ const pageRowIds = useMemo(+ () => processedRowData.rows.map((row) => row.id),+ [processedRowData.rows],+ );++ const selectAll = useStore(datasetsTableStore, (state) => state.selectAll);++ useDatasetsTableSelectionSync({+ store: datasetsTableStore,+ pageRowIds,+ totalCount: datasets.data?.totalDatasets ?? null,+ currentFolderPath,+ searchQuery,+ });+return (<>{currentFolderPath && (@@ -363,7 +579,7 @@ export function DatasetsTable(props: { projectId: string }) {navigateToFolder={navigateToFolder}/>)}- <DataTableToolbar+ <DatasetsTableToolbarcolumns={columns}columnVisibility={columnVisibility}setColumnVisibility={setColumnVisibility}@@ -371,23 +587,20 @@ export function DatasetsTable(props: { projectId: string }) {setColumnOrder={setColumnOrder}rowHeight={rowHeight}setRowHeight={setRowHeight}- searchConfig={{- metadataSearchFields: ["Name"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: false,- setSearchType: undefined,- searchType: undefined,- }}- viewConfig={{- tableName: TableViewPresetTableName.Datasets,- projectId: props.projectId,- controllers: viewControllers,- }}+ currentFolderPath={currentFolderPath}+ paginationState={paginationState}+ projectId={props.projectId}+ searchQuery={searchQuery}+ setSearchQuery={setSearchQuery}+ store={datasetsTableStore}+ totalCount={datasets.data?.totalDatasets ?? null}+ viewControllers={viewControllers}/><DataTabletableName={"datasets"}columns={columns}+ selectionStore={datasetsTableStore}+ highlightAllRows={selectAll}data={datasets.isLoading || isViewLoading? { isLoading: true, isError: false }diff --git a/web/src/features/datasets/components/DeleteDatasetRunButton.tsx b/web/src/features/datasets/components/DeleteDatasetRunButton.tsxindex 891cc65d46..21de12d540 100644--- a/web/src/features/datasets/components/DeleteDatasetRunButton.tsx+++ b/web/src/features/datasets/components/DeleteDatasetRunButton.tsx@@ -1,14 +1,6 @@import { Trash } from "lucide-react";import { Button } from "@/src/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { api } from "@/src/utils/api";@@ -55,44 +47,24 @@ export const DeleteDatasetRunButton = ({);return hasAccess ? (- <Dialog+ <ConfirmDialogopen={isDialogOpen}- onOpenChange={(isOpen) => {- if (!mutDelete.isPending) {- setIsDialogOpen(isOpen);- }+ onOpenChange={setIsDialogOpen}+ trigger={button}+ title="Please confirm"+ description="This action cannot be undone. Traces linked to this run must be deleted manually."+ confirmLabel="Delete Dataset Run"+ loading={mutDelete.isPending}+ onConfirm={async () => {+ capture("dataset_run:delete_form_submit");+ await mutDelete.mutateAsync({+ projectId,+ datasetId: datasetId,+ datasetRunIds: [datasetRunId],+ });+ setIsDialogOpen(false);}}- >- <DialogTrigger asChild>{button}</DialogTrigger>- <DialogContent className="sm:max-w-xl">- <DialogHeader>- <DialogTitle className="mb-4">Please confirm</DialogTitle>- <DialogDescription className="p-0">- This action cannot be undone. Traces linked to this run must be- deleted manually.- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- variant="destructive"- loading={mutDelete.isPending}- disabled={mutDelete.isPending}- onClick={async (event) => {- event.preventDefault();- capture("dataset_run:delete_form_submit");- await mutDelete.mutateAsync({- projectId,- datasetId: datasetId,- datasetRunIds: [datasetRunId],- });- setIsDialogOpen(false);- }}- >- Delete Dataset Run- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ />) : (button);diff --git a/web/src/features/datasets/hooks/useDatasetsTableSelectionSync.ts b/web/src/features/datasets/hooks/useDatasetsTableSelectionSync.tsnew file mode 100644index 0000000000..d01de23798--- /dev/null+++ b/web/src/features/datasets/hooks/useDatasetsTableSelectionSync.ts@@ -0,0 +1,34 @@+import { useEffect } from "react";+import { type DatasetsTableStore } from "@/src/features/datasets/store/datasetsTableStore";++/**+ * Bridges React Query page data into the selection store, and resets the+ * selection when the folder/search scope changes. The reset is an effect (not a+ * nav-handler call) so browser back/forward — which changes the route without+ * firing a handler — also clears a now-out-of-scope selection.+ */+export function useDatasetsTableSelectionSync({+ store,+ pageRowIds,+ totalCount,+ currentFolderPath,+ searchQuery,+}: {+ store: DatasetsTableStore;+ pageRowIds: string[];+ totalCount: number | null;+ currentFolderPath: string | undefined;+ searchQuery: string | null;+}) {+ // Mirror the visible page's rows into the store so selection stays page-scoped.+ useEffect(() => {+ store.getState().actions.syncPageRows({ pageRowIds, totalCount });+ }, [store, pageRowIds, totalCount]);++ // Reset the selection when the folder/search scope changes so Delete never+ // targets rows from a scope the user has left. Pagination is excluded — it+ // keeps the same scope.+ useEffect(() => {+ store.getState().actions.clearSelection();+ }, [store, currentFolderPath, searchQuery]);+}diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex 1f415c2ca2..622b304b3b 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -27,6 +27,11 @@ import {LangfuseNotFoundError,InvalidRequestError,datasetItemMediaFields,+ DatasetNameSchema,+ BatchActionQuerySchema,+ ActionId,+ BatchActionType,+ BatchExportTableName,} from "@langfuse/shared";import { env } from "@/src/env.mjs";import { TRPCError } from "@trpc/server";@@ -80,6 +85,8 @@ import {fetchWithSecureRedirects,whitelistFromEnv,WEBHOOK_URL_VALIDATION_LOG_CONTEXT,+ deleteDatasetsByIds,+ findDatasetsForDeletion,} from "@langfuse/shared/src/server";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import {@@ -88,6 +95,7 @@ import {} from "@/src/features/datasets/server/actions/createDataset";import { type BulkDatasetItemValidationError } from "@langfuse/shared";import { v4 } from "uuid";+import { createBatchActionJob } from "@/src/features/table/server/createBatchActionJob";// Batch size kept small (100) as items may have large input/output/metadata JSONconst DUPLICATE_DATASET_ITEMS_BATCH_SIZE = 100;@@ -1274,6 +1282,89 @@ export const datasetRouter = createTRPCRouter({throw error;}}),+ deleteMany: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ datasetIds: z.array(z.string()).default([]),+ folderPaths: z.array(DatasetNameSchema).default([]),+ query: BatchActionQuerySchema.optional(),+ isBatchAction: z.boolean().default(false),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "datasets:CUD",+ });++ if (input.isBatchAction && input.query) {+ await createBatchActionJob({+ projectId: input.projectId,+ actionId: ActionId.DatasetDelete,+ actionType: BatchActionType.Delete,+ tableName: BatchExportTableName.Datasets,+ session: ctx.session,+ query: input.query,+ });++ return { deletedCount: null };+ }++ if (input.datasetIds.length === 0 && input.folderPaths.length === 0) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Either datasetIds, folderPaths, or a batch action query must be provided to delete datasets.",+ });+ }++ const deletedDatasets = await ctx.prisma.$transaction(async (tx) => {+ const datasetsToDelete = await findDatasetsForDeletion({+ client: tx,+ projectId: input.projectId,+ datasetIds: input.datasetIds,+ folderPaths: input.folderPaths,+ });++ if (datasetsToDelete.length === 0) return [];++ await deleteDatasetsByIds({+ client: tx,+ projectId: input.projectId,+ datasetIds: datasetsToDelete.map((dataset) => dataset.id),+ });++ return datasetsToDelete;+ });++ await Promise.all(+ deletedDatasets.map((dataset) =>+ addToDeleteDatasetQueue({+ deletionType: "dataset",+ projectId: input.projectId,+ datasetId: dataset.id,+ }),+ ),+ );++ await Promise.all(+ deletedDatasets.map((dataset) =>+ auditLog({+ session: ctx.session,+ resourceType: "dataset",+ resourceId: dataset.id,+ action: "delete",+ before: dataset,+ }),+ ),+ );++ return {+ deletedCount: deletedDatasets.length,+ };+ }),deleteDatasetItem: protectedProjectProcedure.input(diff --git a/web/src/features/datasets/store/datasetsTableStore.ts b/web/src/features/datasets/store/datasetsTableStore.tsnew file mode 100644index 0000000000..720e900fc7--- /dev/null+++ b/web/src/features/datasets/store/datasetsTableStore.ts@@ -0,0 +1,183 @@+import { createStore, type StoreApi } from "zustand/vanilla";+import { type RowSelectionState, type Updater } from "@tanstack/react-table";+import { type TableSelectionStoreState } from "@/src/components/table/table-selection-store";+import { type RouterInput } from "@/src/utils/types";+import { type usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++type RowSelectionUpdater = Updater<RowSelectionState>;+type BooleanUpdater = Updater<boolean>;+type DeleteManyInput = RouterInput["datasets"]["deleteMany"];+type PostHogClientCapture = ReturnType<typeof usePostHogClientCapture>;++// Row ids encode whether a row is a folder so the selection (just ids) can be+// split back into datasets vs folders without the full row objects.+const FOLDER_ROW_ID_PREFIX = "folder:";++export function toFolderRowId(folderPath: string) {+ return `${FOLDER_ROW_ID_PREFIX}${folderPath}`;+}++function splitSelectedRowIds(rowIds: string[]) {+ const datasetIds: string[] = [];+ const folderPaths: string[] = [];+ for (const rowId of rowIds) {+ if (rowId.startsWith(FOLDER_ROW_ID_PREFIX)) {+ folderPaths.push(rowId.slice(FOLDER_ROW_ID_PREFIX.length));+ } else {+ datasetIds.push(rowId);+ }+ }+ return { datasetIds, folderPaths };+}++// Folder + search the delete targets; passed at click time (route state, not+// mirrored into the store).+type DatasetsTableScope = {+ folderPath: string | undefined;+ searchQuery: string | null;+};++export interface DatasetsTableStoreState extends TableSelectionStoreState {+ actions: TableSelectionStoreState["actions"] & {+ syncPageRows: (payload: {+ pageRowIds: string[];+ totalCount: number | null;+ }) => void;+ deleteSelected: (params: {+ projectId: string;+ deleteMany: (input: DeleteManyInput) => Promise<unknown>;+ capture: PostHogClientCapture;+ scope: DatasetsTableScope;+ }) => Promise<void>;+ };+}++export type DatasetsTableStore = StoreApi<DatasetsTableStoreState>;++function resolveUpdater<TValue>(+ updater: Updater<TValue>,+ previousValue: TValue,+): TValue {+ return typeof updater === "function"+ ? (updater as (old: TValue) => TValue)(previousValue)+ : updater;+}++function getSelectedPageRowIds(+ rowSelection: RowSelectionState,+ pageRowIds: string[],+) {+ return pageRowIds.filter((rowId) => Boolean(rowSelection[rowId]));+}++export function createDatasetsTableStore(): DatasetsTableStore {+ return createStore<DatasetsTableStoreState>((set, get) => {+ const updateSelection = (+ rowSelection: RowSelectionState,+ selectAll = get().selectAll,+ ) => {+ const { pageRowIds } = get();++ set({+ rowSelection,+ selectAll,+ selectedPageRowIds: getSelectedPageRowIds(rowSelection, pageRowIds),+ });+ };++ const setSelectAll = (updater: BooleanUpdater) => {+ const nextSelectAll = resolveUpdater(updater, get().selectAll);+ if (nextSelectAll === get().selectAll) return;++ set({ selectAll: nextSelectAll });+ };++ const clearSelection = () => {+ updateSelection({}, false);+ };++ const toggleRows = (rowIds: string[], nextSelected: boolean) => {+ const nextRowSelection = { ...get().rowSelection };+ for (const rowId of rowIds) {+ if (nextSelected) {+ nextRowSelection[rowId] = true;+ } else {+ delete nextRowSelection[rowId];+ }+ }++ updateSelection(nextRowSelection, nextSelected ? get().selectAll : false);+ };++ return {+ rowSelection: {},+ selectAll: false,+ selectedPageRowIds: [],+ pageRowIds: [],+ totalCount: null,+ actions: {+ setRowSelection: (updater: RowSelectionUpdater) => {+ updateSelection(resolveUpdater(updater, get().rowSelection));+ },+ setSelectAll,+ toggleRow: (rowId: string, nextSelected: boolean) => {+ toggleRows([rowId], nextSelected);+ },+ toggleRows,+ togglePageRows: (rowIds: string[], nextSelected: boolean) => {+ if (!nextSelected) {+ clearSelection();+ return;+ }++ const nextRowSelection = { ...get().rowSelection };+ for (const rowId of rowIds) {+ nextRowSelection[rowId] = true;+ }++ updateSelection(nextRowSelection);+ },+ clearSelection,+ syncPageRows: ({ pageRowIds, totalCount }) => {+ const { rowSelection } = get();+ set({+ pageRowIds,+ totalCount,+ selectedPageRowIds: getSelectedPageRowIds(rowSelection, pageRowIds),+ });+ },+ deleteSelected: async ({ projectId, deleteMany, capture, scope }) => {+ const { selectAll, selectedPageRowIds } = get();+ const { datasetIds, folderPaths } =+ splitSelectedRowIds(selectedPageRowIds);++ capture("datasets:delete_form_submit", {+ source: "table-multi-select",+ // Folder-expanded total is unknown client-side, so omit for select-all.+ count: selectAll+ ? undefined+ : datasetIds.length + folderPaths.length,+ datasets: datasetIds.length,+ folders: folderPaths.length,+ selectAll,+ });++ await deleteMany({+ projectId,+ datasetIds,+ folderPaths,+ isBatchAction: selectAll,+ query: {+ filter: null,+ orderBy: { column: "createdAt", order: "DESC" },+ searchQuery: scope.searchQuery ?? undefined,+ pathPrefix: scope.folderPath,+ },+ });++ clearSelection();+ },+ },+ };+ });+}diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsxindex 381eb80663..b3801a20d0 100644--- a/web/src/features/public-api/components/ApiKeyList.tsx+++ b/web/src/features/public-api/components/ApiKeyList.tsx@@ -3,14 +3,7 @@ import { Button } from "@/src/components/ui/button";import { Card } from "@/src/components/ui/card";import { CodeView } from "@/src/components/ui/CodeJsonViewer";import { Input } from "@/src/components/ui/input";-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";import {Table,TableBody,@@ -25,7 +18,6 @@ import { CreateApiKeyButton } from "@/src/features/public-api/components/CreateAimport { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { api } from "@/src/utils/api";-import { DialogDescription } from "@radix-ui/react-dialog";import { TrashIcon } from "lucide-react";import { useState } from "react";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";@@ -238,36 +230,20 @@ function DeleteApiKeyButton(props: {};return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>+ <ConfirmDialog+ open={open}+ onOpenChange={setOpen}+ trigger={<Button variant="ghost" size="icon"><TrashIcon className="h-4 w-4" /></Button>- </DialogTrigger>- <DialogContent>- <DialogHeader>- <DialogTitle className="mb-5">Delete API key</DialogTitle>- <DialogDescription>- Are you sure you want to delete this API key? This action cannot be- undone.- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- variant="destructive"- onClick={handleDelete}- loading={- mutDeleteOrgApiKey.isPending || mutDeleteProjectApiKey.isPending- }- >- Permanently delete- </Button>- <Button variant="ghost" onClick={() => setOpen(false)}>- Cancel- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ }+ title="Delete API key"+ description="Are you sure you want to delete this API key? This action cannot be undone."+ confirmLabel="Permanently delete"+ loading={mutDeleteOrgApiKey.isPending || mutDeleteProjectApiKey.isPending}+ onConfirm={handleDelete}+ />);}diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsxindex 7359816c3d..d0989a5d82 100644--- a/web/src/features/public-api/components/LLMApiKeyList.tsx+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx@@ -3,14 +3,7 @@ import { useState } from "react";import Header from "@/src/components/layouts/header";import { Button } from "@/src/components/ui/button";import { Card } from "@/src/components/ui/card";-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";+import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";import {Table,TableBody,@@ -22,7 +15,6 @@ import {import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";-import { DialogDescription } from "@radix-ui/react-dialog";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";import { CreateLLMApiKeyDialog } from "./CreateLLMApiKeyDialog";import { UpdateLLMApiKeyDialog } from "./UpdateLLMApiKeyDialog";@@ -180,47 +172,32 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {if (!hasAccess) return null;return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>+ <ConfirmDialog+ open={open}+ onOpenChange={setOpen}+ trigger={<Button variant="ghost" size="icon"><TrashIcon className="h-4 w-4" /></Button>- </DialogTrigger>- <DialogContent>- <DialogHeader>- <DialogTitle className="mb-5">Delete LLM Connection</DialogTitle>- <DialogDescription>- Are you sure you want to delete this connection? This action cannot- be undone.- </DialogDescription>- </DialogHeader>-- <DialogFooter>- <Button- variant="destructive"- onClick={() => {- mutDeleteApiKey- .mutateAsync({- projectId: props.projectId,- id: props.apiKeyId,- })- .then(() => {- capture("project_settings:llm_api_key_delete");- setOpen(false);- })- .catch((error) => {- console.error(error);- });- }}- loading={mutDeleteApiKey.isPending}- >- Permanently delete- </Button>- <Button variant="ghost" onClick={() => setOpen(false)}>- Cancel- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ }+ title="Delete LLM Connection"+ description="Are you sure you want to delete this connection? This action cannot be undone."+ confirmLabel="Permanently delete"+ loading={mutDeleteApiKey.isPending}+ onConfirm={() => {+ mutDeleteApiKey+ .mutateAsync({+ projectId: props.projectId,+ id: props.apiKeyId,+ })+ .then(() => {+ capture("project_settings:llm_api_key_delete");+ setOpen(false);+ })+ .catch((error) => {+ console.error(error);+ });+ }}+ />);}diff --git a/web/src/features/table/components/TableActionDialog.tsx b/web/src/features/table/components/TableActionDialog.tsxindex 088f030d2d..b84293d8a9 100644--- a/web/src/features/table/components/TableActionDialog.tsx+++ b/web/src/features/table/components/TableActionDialog.tsx@@ -106,11 +106,8 @@ export function TableActionDialog({}}><DialogContent className="sm:max-w-md">- <DialogHeader>+ <DialogHeader variant="action"><DialogTitle>{action.label}</DialogTitle>- <DialogDescription className="mt-2">- {action.description}- </DialogDescription></DialogHeader>{action.type === "create" && (@@ -120,6 +117,7 @@ export function TableActionDialog({onSubmit={form.handleSubmit(handleConfirm)}><DialogBody>+ <DialogDescription>{action.description}</DialogDescription><FormFieldcontrol={form.control}name="targetId"@@ -146,7 +144,7 @@ export function TableActionDialog({)}/></DialogBody>- <DialogFooter>+ <DialogFooter variant="action">{isInProgress.data && (<div className="flex items-center gap-1"><Spinner size="xxs" />@@ -170,26 +168,31 @@ export function TableActionDialog({)}{action.type === "delete" && (- <DialogFooter>- {isInProgress.data && (- <div className="flex items-center gap-1">- <Spinner size="xxs" />- <p className="text-muted-foreground text-sm">- Batch action is in progress, please wait.- </p>- </div>- )}- <ActionButton- variant="destructive"- hasAccess={hasAccess}- hasEntitlement={hasEntitlement}- loading={isInProgress.isLoading}- disabled={isInProgress.data}- onClick={handleConfirm}- >- Confirm- </ActionButton>- </DialogFooter>+ <>+ <DialogBody>+ <DialogDescription>{action.description}</DialogDescription>+ </DialogBody>+ <DialogFooter variant="action">+ {isInProgress.data && (+ <div className="flex items-center gap-1">+ <Spinner size="xxs" />+ <p className="text-muted-foreground text-sm">+ Batch action is in progress, please wait.+ </p>+ </div>+ )}+ <ActionButton+ variant="destructive"+ hasAccess={hasAccess}+ hasEntitlement={hasEntitlement}+ loading={isInProgress.isLoading}+ disabled={isInProgress.data}+ onClick={handleConfirm}+ >+ Confirm+ </ActionButton>+ </DialogFooter>+ </>)}</DialogContent></Dialog>diff --git a/web/src/features/table/components/TableActionMenu.tsx b/web/src/features/table/components/TableActionMenu.tsxindex 58e8524fc0..192f0381e0 100644--- a/web/src/features/table/components/TableActionMenu.tsx+++ b/web/src/features/table/components/TableActionMenu.tsx@@ -21,6 +21,10 @@ type TableActionMenuProps = {actions: TableAction[];tableName: BatchExportTableName;selectedCount: number | null;+ // When the selected-row count is not the affected-entity count (e.g. datasets+ // select-all, where folder rows expand on delete), render a non-numeric label+ // instead of the count/loading spinner.+ approximateCount?: boolean;onClearSelection: () => void;onCustomAction?: (actionType: CustomDialogTableAction["id"]) => void;};@@ -37,6 +41,7 @@ export function TableActionMenu({actions,tableName,selectedCount,+ approximateCount = false,onClearSelection,onCustomAction,}: TableActionMenuProps) {@@ -64,7 +69,9 @@ export function TableActionMenu({<div className="pointer-events-none fixed inset-x-0 bottom-16 z-50 flex justify-center"><div className="ring-dark-blue/20 dark:border-dark-blue/30 dark:ring-dark-blue/30 bg-background pointer-events-auto flex items-center gap-2 rounded-lg border px-3 py-2 opacity-95 shadow-lg ring-2 backdrop-blur-md dark:shadow-none"><div className="text-sm font-medium">- {selectedCount !== null ? (+ {approximateCount ? (+ <span> All matching selected</span>+ ) : selectedCount !== null ? (<span> {`${numberFormatter(selectedCount, 0)} selected`}</span>) : (<Spinner size="sm" />diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex d509855413..56eb6904c3 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -244,6 +244,60 @@ describe("select all test suite", () => {expect(scores).toHaveLength(0);});+ it("should delete only datasets matching path and search query", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ await prisma.dataset.createMany({+ data: [+ {+ id: uuidv4(),+ projectId,+ name: "folder/match",+ createdAt: new Date("2024-01-01"),+ },+ {+ id: uuidv4(),+ projectId,+ name: "folder/other",+ createdAt: new Date("2024-01-01"),+ },+ {+ id: uuidv4(),+ projectId,+ name: "other/match",+ createdAt: new Date("2024-01-01"),+ },+ ],+ });++ await handleBatchActionJob({+ id: uuidv4(),+ timestamp: new Date(),+ name: QueueJobs.BatchActionProcessingJob as const,+ payload: {+ projectId,+ actionId: "dataset-delete",+ tableName: BatchExportTableName.Datasets,+ cutoffCreatedAt: new Date("2024-01-02"),+ query: {+ filter: null,+ orderBy: { column: "createdAt", order: "DESC" },+ searchQuery: "match",+ pathPrefix: "folder",+ },+ type: BatchActionType.Delete,+ },+ });++ await expect(+ prisma.dataset.findMany({+ where: { projectId },+ select: { name: true },+ orderBy: { name: "asc" },+ }),+ ).resolves.toEqual([{ name: "folder/other" }, { name: "other/match" }]);+ });+it("should schedule only traces matching search query for deletion", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex 67eef57461..1946de9489 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -7,6 +7,7 @@ import {QueueJobs,QueueName,TQueueJobTypes,+ findDatasetIdsForBatchDeletion,traceDeletionProcessor,} from "@langfuse/shared/src/server";import {@@ -40,6 +41,7 @@ import {import { processAddObservationsToDataset } from "./processAddObservationsToDataset";import { ObservationAddToDatasetConfigSchema } from "@langfuse/shared";import { processBatchedObservationEval } from "./processBatchedObservationEval";+import { processDeleteDatasets } from "./processDeleteDatasets";const CHUNK_SIZE = 1000;const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {@@ -92,6 +94,10 @@ async function processActionChunk(await processClickhouseScoreDelete(projectId, chunkIds);break;+ case "dataset-delete":+ await processDeleteDatasets(projectId, chunkIds);+ break;+default:throw new Error(`Unknown action: ${actionId}`);}@@ -166,7 +172,8 @@ export const handleBatchActionJob = async (actionId === "trace-add-to-annotation-queue" ||actionId === "session-add-to-annotation-queue" ||actionId === "observation-add-to-annotation-queue" ||- actionId === "score-delete"+ actionId === "score-delete" ||+ actionId === "dataset-delete") {const { projectId, tableName, query, cutoffCreatedAt, targetId, type } =batchActionEvent;@@ -184,21 +191,27 @@ export const handleBatchActionJob = async (};const dbReadStream =- actionId === "trace-delete"- ? await getTraceIdentifierStream({- ...streamParams,- orderBy: query.orderBy,+ actionId === "dataset-delete"+ ? await findDatasetIdsForBatchDeletion({+ projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ query,})- : tableName === BatchTableNames.Events- ? await getEventsStreamForAnnotationQueue(streamParams)- : tableName === BatchTableNames.Observations- ? await getObservationStream(streamParams)- : await getDatabaseReadStreamPaginated({- ...streamParams,- orderBy: query.orderBy,- tableName: tableName as BatchTableNames,- useEventsTable: query.useEventsTable,- });+ : actionId === "trace-delete"+ ? await getTraceIdentifierStream({+ ...streamParams,+ orderBy: query.orderBy,+ })+ : tableName === BatchTableNames.Events+ ? await getEventsStreamForAnnotationQueue(streamParams)+ : tableName === BatchTableNames.Observations+ ? await getObservationStream(streamParams)+ : await getDatabaseReadStreamPaginated({+ ...streamParams,+ orderBy: query.orderBy,+ tableName: tableName as BatchTableNames,+ useEventsTable: query.useEventsTable,+ });// Process stream in database-sized batches// 1. Read all recordsdiff --git a/worker/src/features/batchAction/processDeleteDatasets.ts b/worker/src/features/batchAction/processDeleteDatasets.tsnew file mode 100644index 0000000000..008777afab--- /dev/null+++ b/worker/src/features/batchAction/processDeleteDatasets.ts@@ -0,0 +1,32 @@+import {+ addToDeleteDatasetQueue,+ deleteDatasetsByIds,+ findDatasetIdsByIds,+} from "@langfuse/shared/src/server";++export async function processDeleteDatasets(+ projectId: string,+ datasetIds: string[],+) {+ const datasetsToDelete = await findDatasetIdsByIds({+ projectId,+ datasetIds,+ });++ if (datasetsToDelete.length === 0) return;++ await deleteDatasetsByIds({+ projectId,+ datasetIds: datasetsToDelete.map((dataset) => dataset.id),+ });++ await Promise.all(+ datasetsToDelete.map((dataset) =>+ addToDeleteDatasetQueue({+ deletionType: "dataset",+ projectId,+ datasetId: dataset.id,+ }),+ ),+ );+}diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.tsindex b52b90a07c..a60b747247 100644--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts@@ -44,6 +44,7 @@ const tableNameToTimeFilterColumn: Record<BatchTableNames, string> = {traces: "timestamp",observations: "startTime",events: "startTime",+ datasets: "createdAt",dataset_run_items: "createdAt",dataset_items: "createdAt", // TODO: flip to validFrom once we write in new formataudit_logs: "createdAt",@@ -54,6 +55,7 @@ const tableNameToTimeFilterColumnCh: Record<BatchTableNames, string> = {traces: "timestamp",observations: "startTime",events: "startTime",+ datasets: "createdAt",dataset_run_items: "createdAt",dataset_items: "createdAt",audit_logs: "createdAt",