🪢 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): batch add observations to dataset (#10997)
Hassieb Pakzad288fcf849911
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 9c3665c1ab..db86029feb 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -298,6 +298,23 @@ export type BackgroundMigration = {worker_id: string | null;locked_at: Timestamp | null;};+export type BatchAction = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ user_id: string;+ action_type: string;+ table_name: string;+ status: string;+ finished_at: Timestamp | null;+ query: unknown;+ config: unknown | null;+ total_count: number | null;+ processed_count: number | null;+ failed_count: number | null;+ log: string | null;+};export type BatchExport = {id: string;created_at: Generated<Timestamp>;@@ -926,6 +943,7 @@ export type DB = {automation_executions: AutomationExecution;automations: Automation;background_migrations: BackgroundMigration;+ batch_actions: BatchAction;batch_exports: BatchExport;billing_meter_backups: BillingMeterBackup;blob_storage_integrations: BlobStorageIntegration;diff --git a/packages/shared/prisma/migrations/20251210130559_add_batch_action_table/migration.sql b/packages/shared/prisma/migrations/20251210130559_add_batch_action_table/migration.sqlnew file mode 100644index 0000000000..73590e1062--- /dev/null+++ b/packages/shared/prisma/migrations/20251210130559_add_batch_action_table/migration.sql@@ -0,0 +1,32 @@+-- CreateTable+CREATE TABLE "batch_actions" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "action_type" TEXT NOT NULL,+ "table_name" TEXT NOT NULL,+ "status" TEXT NOT NULL,+ "finished_at" TIMESTAMP(3),+ "query" JSONB NOT NULL,+ "config" JSONB,+ "total_count" INTEGER,+ "processed_count" INTEGER,+ "failed_count" INTEGER,+ "log" TEXT,++ CONSTRAINT "batch_actions_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "batch_actions_project_id_user_id_idx" ON "batch_actions"("project_id", "user_id");++-- CreateIndex+CREATE INDEX "batch_actions_status_idx" ON "batch_actions"("status");++-- CreateIndex+CREATE INDEX "batch_actions_project_id_action_type_idx" ON "batch_actions"("project_id", "action_type");++-- AddForeignKey+ALTER TABLE "batch_actions" ADD CONSTRAINT "batch_actions_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 2b241eb3aa..a5790a19be 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -153,6 +153,7 @@ model Project {BlobStorageIntegration BlobStorageIntegration[]scoreConfig ScoreConfig[]BatchExport BatchExport[]+ BatchAction BatchAction[]comment Comment[]commentReactions CommentReaction[]annotationQueue AnnotationQueue[]@@ -1175,6 +1176,35 @@ model BatchExport {@@map("batch_exports")}+model BatchAction {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ userId String @map("user_id")++ actionType String @map("action_type")+ tableName String @map("table_name")++ status String+ finishedAt DateTime? @map("finished_at")++ query Json+ config Json?++ totalCount Int? @map("total_count")+ processedCount Int? @map("processed_count")+ failedCount Int? @map("failed_count")+ log String?++ @@index([projectId, userId])+ @@index([status])+ @@index([projectId, actionType])+ @@map("batch_actions")+}+model Media {id Stringsha256Hash String @map("sha_256_hash") @db.Char(44)diff --git a/packages/shared/src/features/batchAction/addToDatasetTypes.ts b/packages/shared/src/features/batchAction/addToDatasetTypes.tsnew file mode 100644index 0000000000..6ddb4c9331--- /dev/null+++ b/packages/shared/src/features/batchAction/addToDatasetTypes.ts@@ -0,0 +1,70 @@+import z from "zod/v4";++// Source field type+export const SourceFieldSchema = z.enum(["input", "output", "metadata"]);++// Mapping mode for each field+export const MappingModeSchema = z.enum(["full", "custom", "none"]);++// Mapping target type: "root" extracts single value, "keyValueMap" builds an object+export const MappingTargetSchema = z.enum(["root", "keyValueMap"]);++// Root mapping config - single JSON path extraction+export const RootMappingConfigSchema = z.object({+ sourceField: SourceFieldSchema,+ jsonPath: z.string(),+});++// Key-value mapping entry - key-value pair for building objects+export const KeyValueMappingEntrySchema = z.object({+ id: z.string(),+ key: z.string().min(1, "Key is required"),+ sourceField: SourceFieldSchema,+ value: z.string(), // JSON path if starts with $, else literal string+});++// Custom mapping config - either root or key-value map type+export const CustomMappingConfigSchema = z.object({+ type: MappingTargetSchema,+ rootConfig: RootMappingConfigSchema.optional(),+ keyValueMapConfig: z+ .object({+ entries: z+ .array(KeyValueMappingEntrySchema)+ .min(1, "At least one entry is required"),+ })+ .optional(),+});++// Per-field mapping config+export const FieldMappingConfigSchema = z.object({+ mode: MappingModeSchema,+ custom: CustomMappingConfigSchema.optional(),+});++// Complete mapping config for all three fields+export const AddToDatasetMappingSchema = z.object({+ input: FieldMappingConfigSchema,+ expectedOutput: FieldMappingConfigSchema,+ metadata: FieldMappingConfigSchema,+});++// Config for the batch action+export const ObservationAddToDatasetConfigSchema = z.object({+ datasetId: z.string(),+ datasetName: z.string(),+ mapping: AddToDatasetMappingSchema,+});++// Type exports+export type SourceField = z.infer<typeof SourceFieldSchema>;+export type MappingMode = z.infer<typeof MappingModeSchema>;+export type MappingTarget = z.infer<typeof MappingTargetSchema>;+export type RootMappingConfig = z.infer<typeof RootMappingConfigSchema>;+export type KeyValueMappingEntry = z.infer<typeof KeyValueMappingEntrySchema>;+export type CustomMappingConfig = z.infer<typeof CustomMappingConfigSchema>;+export type FieldMappingConfig = z.infer<typeof FieldMappingConfigSchema>;+export type AddToDatasetMapping = z.infer<typeof AddToDatasetMappingSchema>;+export type ObservationAddToDatasetConfig = z.infer<+ typeof ObservationAddToDatasetConfigSchema+>;diff --git a/packages/shared/src/features/batchAction/applyFieldMapping.ts b/packages/shared/src/features/batchAction/applyFieldMapping.tsnew file mode 100644index 0000000000..74cf69bb71--- /dev/null+++ b/packages/shared/src/features/batchAction/applyFieldMapping.ts@@ -0,0 +1,219 @@+import { JSONPath } from "jsonpath-plus";+import { set } from "lodash";+import type {+ FieldMappingConfig,+ SourceField,+ AddToDatasetMapping,+} from "./addToDatasetTypes";++type ObservationData = {+ input: unknown;+ output: unknown;+ metadata: unknown;+};++/**+ * Test if a JSON path is valid against the given data+ */+export function testJsonPath(props: { jsonPath: string; data: unknown }): {+ success: boolean;+ error?: string;+} {+ try {+ const parsed =+ typeof props.data === "string" ? JSON.parse(props.data) : props.data;+ JSONPath({ path: props.jsonPath, json: parsed });+ return { success: true };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : "Unknown error",+ };+ }+}++/**+ * Evaluate a JSON path against the given data and return the result+ */+export function evaluateJsonPath(data: unknown, jsonPath: string): unknown {+ try {+ const parsed = typeof data === "string" ? JSON.parse(data) : data;+ const results = JSONPath({ path: jsonPath, json: parsed });+ return results?.[0];+ } catch {+ return undefined;+ }+}++/**+ * Check if a value is a JSON path (starts with $)+ */+export function isJsonPath(value: string): boolean {+ return value.startsWith("$");+}++/**+ * Set a value at a nested path using dot notation.+ * Creates intermediate objects as needed.+ * Uses lodash's set which has built-in prototype pollution protection.+ *+ * @example+ * setNestedValue({}, "context.user_id", "123")+ * // Returns: { context: { user_id: "123" } }+ */+function setNestedValue(+ obj: Record<string, unknown>,+ path: string,+ value: unknown,+): void {+ set(obj, path, value);+}++/**+ * Apply field mapping config to get the result for a single field+ */+export function applyFieldMappingConfig(props: {+ observation: ObservationData;+ config: FieldMappingConfig;+ defaultSourceField: SourceField;+}): unknown {+ const { observation, config, defaultSourceField } = props;++ switch (config.mode) {+ case "full":+ // Return the full source field+ return observation[defaultSourceField];++ case "none":+ // Return null (will be written as Prisma.DbNull)+ return null;++ case "custom":+ if (!config.custom) {+ return observation[defaultSourceField];+ }++ if (config.custom.type === "root") {+ // Root mode: extract single value using JSON path+ const rootConfig = config.custom.rootConfig;+ if (!rootConfig) {+ return observation[defaultSourceField];+ }++ const sourceData = observation[rootConfig.sourceField];+ return evaluateJsonPath(sourceData, rootConfig.jsonPath);+ }++ if (config.custom.type === "keyValueMap") {+ // Key-value map mode: build object from entries+ // Supports dot notation for nested objects (e.g., "context.user_id")+ const keyValueMapConfig = config.custom.keyValueMapConfig;+ if (!keyValueMapConfig || keyValueMapConfig.entries.length === 0) {+ return observation[defaultSourceField];+ }++ const result: Record<string, unknown> = {};+ for (const entry of keyValueMapConfig.entries) {+ // Skip entries with empty values+ if (!entry.value && entry.value !== "") {+ continue;+ }++ let resolvedValue: unknown;+ if (isJsonPath(entry.value)) {+ // It's a JSON path - evaluate it+ const sourceData = observation[entry.sourceField];+ resolvedValue = evaluateJsonPath(sourceData, entry.value);+ } else {+ // It's a literal string (including empty string)+ resolvedValue = entry.value;+ }++ // Use dot notation path setter for nested objects+ if (entry.key.includes(".")) {+ setNestedValue(result, entry.key, resolvedValue);+ } else {+ result[entry.key] = resolvedValue;+ }+ }+ return result;+ }++ return observation[defaultSourceField];++ default:+ return observation[defaultSourceField];+ }+}++/**+ * Apply the full mapping config to an observation and return the dataset item fields+ */+export function applyFullMapping(props: {+ observation: ObservationData;+ mapping: AddToDatasetMapping;+}): {+ input: unknown;+ expectedOutput: unknown;+ metadata: unknown;+} {+ const { observation, mapping } = props;++ return {+ input: applyFieldMappingConfig({+ observation,+ config: mapping.input,+ defaultSourceField: "input",+ }),+ expectedOutput: applyFieldMappingConfig({+ observation,+ config: mapping.expectedOutput,+ defaultSourceField: "output",+ }),+ metadata: applyFieldMappingConfig({+ observation,+ config: mapping.metadata,+ defaultSourceField: "metadata",+ }),+ };+}++/**+ * Generate autocomplete suggestions for JSON paths based on the data structure+ */+export function generateJsonPathSuggestions(+ data: unknown,+ prefix: string = "$",+): string[] {+ const suggestions: string[] = [];++ if (data === null || data === undefined) {+ return suggestions;+ }++ if (typeof data === "object") {+ if (Array.isArray(data)) {+ // For arrays, suggest index access and wildcard+ suggestions.push(`${prefix}[0]`);+ suggestions.push(`${prefix}[*]`);+ // Also recurse into first element+ if (data.length > 0) {+ suggestions.push(+ ...generateJsonPathSuggestions(data[0], `${prefix}[0]`),+ );+ }+ } else {+ // For objects, suggest each key+ for (const [key, value] of Object.entries(+ data as Record<string, unknown>,+ )) {+ const childPath = `${prefix}.${key}`;+ suggestions.push(childPath);+ // Recurse into nested objects/arrays+ suggestions.push(...generateJsonPathSuggestions(value, childPath));+ }+ }+ }++ return suggestions;+}diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.tsindex 7ac6104692..9ebed82faf 100644--- a/packages/shared/src/features/batchAction/types.ts+++ b/packages/shared/src/features/batchAction/types.ts@@ -10,15 +10,24 @@ export enum BatchActionType {Delete = "delete",}-const ActionIdSchema = z.enum([- "score-delete",- "trace-delete",- "trace-add-to-annotation-queue",- "session-add-to-annotation-queue",- "observation-add-to-annotation-queue",-]);--export type ActionId = z.infer<typeof ActionIdSchema>;+export enum BatchActionStatus {+ Queued = "QUEUED",+ Processing = "PROCESSING",+ Completed = "COMPLETED",+ Failed = "FAILED",+ Partial = "PARTIAL",+}++export enum ActionId {+ ScoreDelete = "score-delete",+ TraceDelete = "trace-delete",+ TraceAddToAnnotationQueue = "trace-add-to-annotation-queue",+ SessionAddToAnnotationQueue = "session-add-to-annotation-queue",+ ObservationAddToAnnotationQueue = "observation-add-to-annotation-queue",+ ObservationAddToDataset = "observation-add-to-dataset",+}++const ActionIdSchema = z.nativeEnum(ActionId);export const BatchActionQuerySchema = z.object({filter: z.array(singleFilter).nullable(),diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex bf2ddc405c..ae468721d9 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -33,6 +33,8 @@ export * from "./features/evals/utilities";// table actionsexport * from "./features/batchExport/types";export * from "./features/batchAction/types";+export * from "./features/batchAction/addToDatasetTypes";+export * from "./features/batchAction/applyFieldMapping";export { BatchTableNames } from "./interfaces/tableNames";// annotationdiff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex a5d299496e..6b29961768 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -8,6 +8,7 @@ import {import { BatchTableNames } from "../interfaces/tableNames";import { EventActionSchema } from "../domain";import { PromptDomainSchema } from "../domain/prompts";+import { ObservationAddToDatasetConfigSchema } from "../features/batchAction/addToDatasetTypes";export const IngestionEvent = z.object({data: z.object({@@ -165,6 +166,16 @@ export const BatchActionProcessingEventSchema = z.discriminatedUnion(cutoffCreatedAt: z.date(),query: BatchActionQuerySchema,}),+ z.object({+ actionId: z.literal("observation-add-to-dataset"),+ projectId: z.string(),+ query: BatchActionQuerySchema,+ tableName: z.enum(BatchTableNames),+ cutoffCreatedAt: z.date(),+ batchActionId: z.string(),+ config: ObservationAddToDatasetConfigSchema,+ type: z.enum(BatchActionType),+ }),],);diff --git a/packages/shared/src/server/repositories/dataset-items.ts b/packages/shared/src/server/repositories/dataset-items.tsindex 10df9ab391..c8612f0dc9 100644--- a/packages/shared/src/server/repositories/dataset-items.ts+++ b/packages/shared/src/server/repositories/dataset-items.ts@@ -374,7 +374,7 @@ export async function deleteDatasetItem(props: {/*** Bulk creates multiple dataset items with validation.- * Validates all items before insertion - if any fail, none are inserted.+ * Validates all items before insertion - if any fail, none are inserted (unless allowPartialSuccess is true).** **Performance:** Compiles schemas once per dataset (not per item), providing* 3800x+ speedup over individual validations.@@ -388,23 +388,37 @@ export async function deleteDatasetItem(props: {* to original CSV rows or API payloads for user-friendly error reporting.** @param props.items - Can contain items from multiple datasets- * @returns Success with all created items, or validation errors with indices+ * @param props.allowPartialSuccess - If true, create valid items even if some fail validation.+ * When enabled, the return type changes:+ * - `success: true` with `validationErrors` array (partial success)+ * - `successCount` and `failedCount` indicate how many items were created vs failed+ * @returns When allowPartialSuccess=false: success with all items OR failure with all errors.+ * When allowPartialSuccess=true: success with created items AND any validation errors.*/export async function createManyDatasetItems(props: {projectId: string;items: CreateManyItemsPayload;normalizeOpts: { sanitizeControlChars?: boolean };validateOpts: { normalizeUndefinedToNull?: boolean };+ allowPartialSuccess?: boolean;}): Promise<| {success: true;datasetItems: CreateManyItemsInsert;+ validationErrors?: CreateManyValidationError[];+ successCount: number;+ failedCount: number;}| {success: false;validationErrors: CreateManyValidationError[];+ successCount: number;+ failedCount: number;}> {+ let successCount = 0;+ let failedCount = 0;+// 1. Group items by datasetId and add original index (preserves CSV row mapping)const itemsByDataset = props.items.reduce((acc, item, index) => {@@ -475,6 +489,8 @@ export async function createManyDatasetItems(props: {});if (!result.success) {+ failedCount++;+// Validation failed - add errors with original indexif (result.cause?.inputErrors) {validationErrors.push({@@ -491,6 +507,8 @@ export async function createManyDatasetItems(props: {});}} else {+ successCount++;+// Validation passed - prepare for insertpreparedItems.push({itemId: v4(),@@ -508,21 +526,39 @@ export async function createManyDatasetItems(props: {}}- // 4. If any validation errors, return early- if (validationErrors.length > 0) {+ // 4. If any validation errors and partial success not allowed, return early+ if (validationErrors.length > 0 && !props.allowPartialSuccess) {return {success: false,validationErrors,+ successCount,+ failedCount,};}// 5. Bulk insert all valid items- await prisma.datasetItem.createMany({- data: preparedItems.map(toPostgresDatasetItem),- });+ if (preparedItems.length > 0) {+ await prisma.datasetItem.createMany({+ data: preparedItems.map(toPostgresDatasetItem),+ });+ }++ // 6. Return appropriate response+ if (validationErrors.length > 0 && props.allowPartialSuccess) {+ // Partial success: some items created, some failed+ return {+ success: true,+ datasetItems: preparedItems,+ validationErrors,+ successCount,+ failedCount,+ };+ }return {success: true,datasetItems: preparedItems,+ successCount,+ failedCount,};}diff --git a/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts b/packages/shared/src/server/services/DatasetService/DatasetItemValidator.tsindex 94dfbe20c8..7912cac5a1 100644--- a/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts+++ b/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts@@ -190,6 +190,26 @@ export class DatasetItemValidator {normalizeOpts?: { sanitizeControlChars?: boolean };validateOpts: { normalizeUndefinedToNull?: boolean };}): ValidateAndNormalizeResult {+ // If we have a create operation, input cannot be undefined / null+ // Use explicit null check (not falsy) to allow valid JSON values like 0, false, ""+ if (+ params.validateOpts.normalizeUndefinedToNull &&+ (params.input === null || params.input === undefined)+ ) {+ return {+ success: false,+ message: "Dataset item input cannot be null",+ cause: {+ inputErrors: [+ {+ message: "Dataset item input cannot be null",+ path: "/",+ },+ ],+ },+ };+ }+// 1. Normalize IOconst normalizedInput = this.normalize(params.input, params.normalizeOpts);const normalizedExpectedOutput = this.normalize(diff --git a/web/src/__tests__/async/datasets-schema-validation.servertest.ts b/web/src/__tests__/async/datasets-schema-validation.servertest.tsindex 1970712982..32bee1bb03 100644--- a/web/src/__tests__/async/datasets-schema-validation.servertest.ts+++ b/web/src/__tests__/async/datasets-schema-validation.servertest.ts@@ -294,7 +294,7 @@ describe("Unit Tests - DatasetItemValidator", () => {it("should reject null when schema doesn't allow null", () => {const result = defaultValidator.validateAndNormalize({- input: null,+ input: "whassup",expectedOutput: null,metadata: undefined,validateOpts: { normalizeUndefinedToNull: true },@@ -308,13 +308,27 @@ describe("Unit Tests - DatasetItemValidator", () => {}});- it("should pass when null is allowed in schema", () => {+ it("should block if input is null despite allowed in schema", () => {const validator = new DatasetItemValidator({inputSchema: TEST_SCHEMAS.allowsNull,expectedOutputSchema: TEST_SCHEMAS.allowsNull,});const result = validator.validateAndNormalize({input: null,+ expectedOutput: { text: "hello" },+ metadata: undefined,+ validateOpts: { normalizeUndefinedToNull: true },+ });+ expect(result.success).toBe(false);+ });++ it("should pass when null is allowed in schema", () => {+ const validator = new DatasetItemValidator({+ inputSchema: TEST_SCHEMAS.allowsNull,+ expectedOutputSchema: TEST_SCHEMAS.allowsNull,+ });+ const result = validator.validateAndNormalize({+ input: { text: "hello" },expectedOutput: null,metadata: undefined,validateOpts: { normalizeUndefinedToNull: true },@@ -585,6 +599,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"/api/public/dataset-items",{datasetName: "valid-output-test",+ input: "Hello",expectedOutput: { value: 42 },},auth,@@ -618,7 +633,7 @@ describe("Public API - Dataset Schema Enforcement", () => {expect(res.status).toBe(200);});- it("should create item with null when schema allows null", async () => {+ it("should not create item with null even when schema allows null", async () => {await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST",@@ -630,8 +645,7 @@ describe("Public API - Dataset Schema Enforcement", () => {auth,);- const res = await makeZodVerifiedAPICall(- PostDatasetItemsV1Response,+ const res = await makeAPICall("POST","/api/public/dataset-items",{@@ -641,7 +655,7 @@ describe("Public API - Dataset Schema Enforcement", () => {auth,);- expect(res.status).toBe(200);+ expect(res.status).toBe(400);});it("should reject item with invalid input", async () => {@@ -972,7 +986,8 @@ describe("Public API - Dataset Schema Enforcement", () => {"/api/public/dataset-items",{datasetName: "null-items",- input: null,+ input: "hello",+ expectedOutput: null,},auth,);@@ -983,7 +998,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"/api/public/v2/datasets",{name: "null-items",- inputSchema: TEST_SCHEMAS.simpleText, // Requires object+ expectedOutputSchema: TEST_SCHEMAS.simpleText, // Requires object},auth,);diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsxindex a0b4ba3ec9..35bc082160 100644--- a/web/src/components/layouts/status-badge.tsx+++ b/web/src/components/layouts/status-badge.tsx@@ -8,6 +8,7 @@ const statusCategories = {inactive: ["disabled", "inactive"],completed: ["completed", "done", "finished"],error: ["error", "failed"],+ partial: ["partial"],};export type Status =@@ -49,6 +50,9 @@ export const StatusBadge = ({} else if (statusCategories.completed.includes(type.toLowerCase())) {badgeColor = "bg-light-green text-dark-green";showDot = false;+ } else if (statusCategories.partial.includes(type.toLowerCase())) {+ badgeColor = "bg-light-yellow text-dark-yellow";+ showDot = false;}return (@@ -75,7 +79,7 @@ export const StatusBadge = ({></span></span>)}- {showText && <span>{type}</span>}+ {showText && <span>{type[0].toUpperCase() + type.slice(1)}</span>}{children}</div>);diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsxindex 8fa60e043b..1640e8c7a7 100644--- a/web/src/components/table/use-cases/observations.tsx+++ b/web/src/components/table/use-cases/observations.tsx@@ -27,6 +27,7 @@ import {TableViewPresetTableName,AnnotationQueueObjectType,BatchActionType,+ ActionId,type TimeFilter,} from "@langfuse/shared";import { cn } from "@/src/utils/tailwind";@@ -67,6 +68,7 @@ import { type TableAction } from "@/src/features/table/types";import { type DataTablePeekViewProps } from "@/src/components/table/peek";import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";+import { AddObservationsToDatasetDialog } from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/index";export type ObservationsTableRow = {// Shown by default@@ -134,6 +136,7 @@ export default function ObservationsTable({useFullTextSearch();const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");+ const [showAddToDatasetDialog, setShowAddToDatasetDialog] = useState(false);const [paginationState, setPaginationState] = useQueryParams({pageIndex: withDefault(NumberParam, 0),@@ -476,7 +479,7 @@ export default function ObservationsTable({const tableActions: TableAction[] = [{- id: "observation-add-to-annotation-queue",+ id: ActionId.ObservationAddToAnnotationQueue,type: BatchActionType.Create,label: "Add to Annotation Queue",description: "Add selected observations to an annotation queue.",@@ -486,6 +489,16 @@ export default function ObservationsTable({scope: "annotationQueues:CUD",},},+ {+ id: ActionId.ObservationAddToDataset,+ type: BatchActionType.Create,+ label: "Add to Dataset",+ description: "Add selected observations to a dataset",+ customDialog: true,+ accessCheck: {+ scope: "datasets:CUD",+ },+ },];const columns: LangfuseColumnDef<ObservationsTableRow>[] = [@@ -1200,6 +1213,11 @@ export default function ObservationsTable({projectId={projectId}actions={tableActions}tableName={BatchExportTableName.Observations}+ onCustomAction={(actionType) => {+ if (actionType === ActionId.ObservationAddToDataset) {+ setShowAddToDatasetDialog(true);+ }+ }}/>) : null,]}@@ -1287,6 +1305,44 @@ export default function ObservationsTable({</div></ResizableFilterLayout></div>++ {/* Add to Dataset Dialog */}+ {showAddToDatasetDialog && (+ <AddObservationsToDatasetDialog+ projectId={projectId}+ selectedObservationIds={Object.keys(selectedRows).filter((id) =>+ generations.data?.generations.map((g) => g.id).includes(id),+ )}+ query={{+ filter: backendFilterState,+ orderBy: orderByState,+ searchQuery: searchQuery ?? undefined,+ searchType,+ }}+ selectAll={selectAll}+ totalCount={totalCount ?? 0}+ onClose={() => {+ setShowAddToDatasetDialog(false);+ setSelectedRows({});+ setSelectAll(false);+ }}+ exampleObservation={(() => {+ // Get the first selected observation to use for preview+ const selectedIds = Object.keys(selectedRows).filter((id) =>+ generations.data?.generations.map((g) => g.id).includes(id),+ );+ const firstId = selectedIds[0];+ const firstGen = generations.data?.generations.find(+ (g) => g.id === firstId,+ );+ return {+ id: firstGen?.id ?? "",+ traceId: firstGen?.traceId ?? "",+ startTime: firstGen?.traceTimestamp ?? undefined,+ };+ })()}+ />+ )}</DataTableControlsProvider>);}diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsxindex 75ade8ef94..d57d666b0a 100644--- a/web/src/components/table/use-cases/sessions.tsx+++ b/web/src/components/table/use-cases/sessions.tsx@@ -22,6 +22,7 @@ import {TableViewPresetTableName,AnnotationQueueObjectType,BatchActionType,+ ActionId,type TimeFilter,} from "@langfuse/shared";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";@@ -346,7 +347,7 @@ export default function SessionsTable({const tableActions: TableAction[] = [{- id: "session-add-to-annotation-queue",+ id: ActionId.SessionAddToAnnotationQueue,type: BatchActionType.Create,label: "Add to Annotation Queue",description: "Add selected sessions to an annotation queue.",diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex 2045d75fc6..f8efe8bd4a 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -37,6 +37,7 @@ import {BatchExportTableName,AnnotationQueueObjectType,BatchActionType,+ ActionId,TableViewPresetTableName,type TimeFilter,} from "@langfuse/shared";@@ -471,7 +472,7 @@ export default function TracesTable({...(hasTraceDeletionEntitlement? [{- id: "trace-delete",+ id: ActionId.TraceDelete,type: BatchActionType.Delete,label: "Delete Traces",description: `This action permanently deletes ${displayCount} traces and cannot be undone. Trace deletion happens asynchronously and may take up to 15 minutes.`,@@ -484,7 +485,7 @@ export default function TracesTable({]: []),{- id: "trace-add-to-annotation-queue",+ id: ActionId.TraceAddToAnnotationQueue,type: BatchActionType.Create,label: "Add to Annotation Queue",description: "Add selected traces to an annotation queue.",diff --git a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.tsindex 9a893eee0f..6a0b27e4a4 100644--- a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts+++ b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts@@ -6,7 +6,7 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import {- type ActionId,+ ActionId,type AnnotationQueueItem,AnnotationQueueObjectType,AnnotationQueueStatus,@@ -36,18 +36,21 @@ const isItemLocked = (item: AnnotationQueueItem) => {const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<AnnotationQueueObjectType,- { actionId: ActionId; tableName: BatchTableNames }+ {+ actionId: Exclude<ActionId, ActionId.ObservationAddToDataset>;+ tableName: BatchTableNames;+ }> = {[AnnotationQueueObjectType.TRACE]: {- actionId: "trace-add-to-annotation-queue",+ actionId: ActionId.TraceAddToAnnotationQueue,tableName: BatchExportTableName.Traces,},[AnnotationQueueObjectType.SESSION]: {- actionId: "session-add-to-annotation-queue",+ actionId: ActionId.SessionAddToAnnotationQueue,tableName: BatchExportTableName.Sessions,},[AnnotationQueueObjectType.OBSERVATION]: {- actionId: "observation-add-to-annotation-queue",+ actionId: ActionId.ObservationAddToAnnotationQueue,tableName: BatchExportTableName.Observations,},};diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetChoiceStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetChoiceStep.tsxnew file mode 100644index 0000000000..30c72a36fc--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetChoiceStep.tsx@@ -0,0 +1,40 @@+import { Database, Plus } from "lucide-react";+import type { DatasetChoiceStepProps } from "./types";++export function DatasetChoiceStep(props: DatasetChoiceStepProps) {+ const { onSelectMode } = props;++ return (+ <div className="grid grid-cols-2 gap-6 p-6">+ {/* Existing Dataset Card */}+ <button+ type="button"+ onClick={() => onSelectMode("select")}+ className="flex flex-col items-center rounded-lg border-2 p-8 text-center transition-all hover:border-tertiary hover:bg-accent"+ >+ <div className="mb-4 rounded-full bg-primary/10 p-4">+ <Database className="h-8 w-8 text-primary" />+ </div>+ <h3 className="mb-2 text-lg font-semibold">Existing Dataset</h3>+ <p className="text-sm text-muted-foreground">+ Add to a dataset that already exists+ </p>+ </button>++ {/* New Dataset Card */}+ <button+ type="button"+ onClick={() => onSelectMode("create")}+ className="flex flex-col items-center rounded-lg border-2 p-8 text-center transition-all hover:border-tertiary hover:bg-accent"+ >+ <div className="mb-4 rounded-full bg-primary/10 p-4">+ <Plus className="h-8 w-8 text-primary" />+ </div>+ <h3 className="mb-2 text-lg font-semibold">New Dataset</h3>+ <p className="text-sm text-muted-foreground">+ Create a new dataset for these observations+ </p>+ </button>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetCreateStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetCreateStep.tsxnew file mode 100644index 0000000000..023d464ce4--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetCreateStep.tsx@@ -0,0 +1,27 @@+import { DatasetForm } from "@/src/features/datasets/components/DatasetForm";+import type { DatasetCreateStepProps } from "./types";++export function DatasetCreateStep(props: DatasetCreateStepProps) {+ const { projectId, formRef, onDatasetCreated, onValidationChange } = props;++ return (+ <div className="space-y-6 p-6">+ <div>+ <h3 className="text-lg font-medium">Create New Dataset</h3>+ <p className="text-sm text-muted-foreground">+ Fill in the details to create a new dataset+ </p>+ </div>++ <DatasetForm+ ref={formRef}+ projectId={projectId}+ mode="create"+ redirectOnSuccess={false}+ showFooter={false}+ onCreateDatasetSuccess={onDatasetCreated}+ onValidationChange={onValidationChange}+ />+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetSelectStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetSelectStep.tsxnew file mode 100644index 0000000000..c89a787254--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/DatasetSelectStep.tsx@@ -0,0 +1,85 @@+import { useState } from "react";+import { Check, ChevronsUpDown } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+} from "@/src/components/ui/command";+import { cn } from "@/src/utils/tailwind";+import { api } from "@/src/utils/api";+import type { DatasetSelectStepProps } from "./types";++export function DatasetSelectStep({+ projectId,+ dataset,+ onDatasetSelect,+}: DatasetSelectStepProps) {+ const [open, setOpen] = useState(false);++ // Fetch all datasets+ const datasets = api.datasets.allDatasetMeta.useQuery({+ projectId,+ });++ return (+ <div className="space-y-6 p-6">+ <div>+ <h3 className="text-lg font-medium">Select Dataset</h3>+ <p className="text-sm text-muted-foreground">+ Choose an existing dataset to add your observations to+ </p>+ </div>++ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ role="combobox"+ aria-expanded={open}+ className="w-full justify-between py-6 text-base"+ >+ {dataset.name || "Select dataset..."}+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[500px] p-0" align="start">+ <Command>+ <CommandInput placeholder="Search datasets..." />+ <CommandEmpty>No dataset found.</CommandEmpty>+ <CommandGroup className="max-h-[300px] overflow-auto">+ {datasets.data?.map((d) => (+ <CommandItem+ key={d.id}+ value={d.name}+ onSelect={() => {+ onDatasetSelect(d);+ setOpen(false);+ }}+ className="flex items-center justify-between"+ >+ <div className="flex items-center">+ <Check+ className={cn(+ "mr-2 h-4 w-4",+ dataset.id === d.id ? "opacity-100" : "opacity-0",+ )}+ />+ <span>{d.name}</span>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsxnew file mode 100644index 0000000000..e2565c3017--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx@@ -0,0 +1,108 @@+import { useMemo } from "react";+import { Button } from "@/src/components/ui/button";+import { Pencil } from "lucide-react";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import type { FinalPreviewStepProps, DialogStep } from "./types";+import { applyFullMapping } from "@langfuse/shared";++export function FinalPreviewStep({+ dataset,+ mapping,+ observationData,+ totalCount,+ onEditStep,+}: FinalPreviewStepProps) {+ // Compute the full preview+ const previewResult = useMemo(() => {+ if (!observationData) return null;++ return applyFullMapping({+ observation: {+ input: observationData.input,+ output: observationData.output,+ metadata: observationData.metadata,+ },+ mapping,+ });+ }, [observationData, mapping]);++ return (+ <div className="h-[62vh] space-y-6 p-6">+ <div>+ <h3 className="text-lg font-semibold">Review Configuration</h3>+ <p className="text-sm text-muted-foreground">+ Adding {totalCount} observation{totalCount !== 1 ? "s" : ""} to+ dataset "+ {dataset.name}"+ </p>+ </div>++ <div className="text-sm text-muted-foreground">+ Sample dataset item preview (from first selected observation):+ </div>++ {!observationData ? (+ <div className="flex h-64 items-center justify-center rounded-md border bg-muted/30 p-4">+ <p className="text-sm text-muted-foreground">+ No observation data available for preview+ </p>+ </div>+ ) : (+ <div className="space-y-4">+ {/* Input Preview */}+ <PreviewCard+ label="Input"+ data={previewResult?.input}+ onEdit={() => onEditStep("input-mapping" as DialogStep)}+ />++ {/* Expected Output Preview */}+ <PreviewCard+ label="Expected Output"+ data={previewResult?.expectedOutput}+ onEdit={() => onEditStep("output-mapping" as DialogStep)}+ />++ {/* Metadata Preview */}+ <PreviewCard+ label="Metadata"+ data={previewResult?.metadata}+ onEdit={() => onEditStep("metadata-mapping" as DialogStep)}+ />+ </div>+ )}+ </div>+ );+}++type PreviewCardProps = {+ label: string;+ data: unknown;+ onEdit: () => void;+};++function PreviewCard({ label, data, onEdit }: PreviewCardProps) {+ return (+ <div className="rounded-lg border">+ <div className="flex items-center justify-between border-b bg-muted/30 px-4 py-2">+ <span className="text-sm font-medium">{label}</span>+ <Button+ variant="ghost"+ size="sm"+ onClick={onEdit}+ className="h-7 gap-1 text-xs"+ >+ <Pencil className="h-3 w-3" />+ Edit+ </Button>+ </div>+ <div className="max-h-62 overflow-auto">+ {data === null ? (+ <div className="p-4 text-sm italic text-muted-foreground">null</div>+ ) : (+ <JSONView json={data} className="text-xs" />+ )}+ </div>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/MappingStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/MappingStep.tsxnew file mode 100644index 0000000000..6dc75ef678--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/MappingStep.tsx@@ -0,0 +1,170 @@+import { useEffect, useRef } from "react";+import { MappingModeSelector } from "./components/MappingModeSelector";+import { CustomMappingEditor } from "./components/CustomMappingEditor";+import { MappingPreviewPanel } from "./components/MappingPreviewPanel";+import { DatasetSchemaHoverCard } from "@/src/features/datasets/components/DatasetSchemaHoverCard";+import {+ extractSchemaFields,+ isObjectSchema,+ generateEntriesFromSchema,+} from "./utils/extractSchemaFields";+import type {+ MappingStepProps,+ MappingMode,+ CustomMappingConfig,+} from "./types";++export function MappingStep({+ field,+ fieldLabel,+ defaultSourceField,+ config,+ onConfigChange,+ observationData,+ isLoading,+ schema,+ onValidationChange,+}: MappingStepProps) {+ const hasSchema = schema !== null && schema !== undefined;+ const isObjectType = hasSchema && isObjectSchema(schema);+ const hasInitializedRef = useRef(false);++ // Auto-initialize to custom key-value mode with schema-derived entries when:+ // 1. Schema exists and is an object type+ // 2. Config hasn't been manually set yet (mode is "full" which is the default)+ // 3. We haven't already initialized+ useEffect(() => {+ if (+ isObjectType &&+ config.mode === "full" &&+ !hasInitializedRef.current &&+ !config.custom?.keyValueMapConfig // Don't override if already has key-value config+ ) {+ hasInitializedRef.current = true;++ const schemaFields = extractSchemaFields(schema);+ if (schemaFields.length > 0) {+ const entries = generateEntriesFromSchema(+ schemaFields,+ defaultSourceField,+ );++ onConfigChange({+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries,+ },+ },+ });+ }+ }+ }, [+ isObjectType,+ schema,+ config.mode,+ config.custom,+ defaultSourceField,+ onConfigChange,+ ]);++ // Get the full label for the "Full" option+ const getFullLabel = () => {+ switch (field) {+ case "input":+ return "Full observation input";+ case "expectedOutput":+ return "Full observation output";+ case "metadata":+ return "Full observation metadata";+ default:+ return `Full observation ${field}`;+ }+ };++ const handleModeChange = (mode: MappingMode) => {+ if (mode === "custom") {+ // Initialize custom config if switching to custom+ onConfigChange({+ mode: "custom",+ custom: config.custom ?? {+ type: "root",+ rootConfig: {+ sourceField: defaultSourceField,+ jsonPath: "$",+ },+ },+ });+ } else {+ onConfigChange({+ mode,+ custom: config.custom, // Preserve custom config in case they switch back+ });+ }+ };++ const handleCustomConfigChange = (customConfig: CustomMappingConfig) => {+ onConfigChange({+ ...config,+ custom: customConfig,+ });+ };++ return (+ <div className="grid h-[62vh] grid-cols-[1fr,1fr] gap-6 overflow-auto p-6">+ {/* Left: Configuration */}+ <div className="space-y-6">+ <div>+ <div className="flex items-center gap-2">+ <h3 className="flex-grow text-lg font-semibold">+ Dataset Item {fieldLabel}+ </h3>+ {hasSchema && (+ <DatasetSchemaHoverCard+ schemaType={+ field === "expectedOutput" ? "expectedOutput" : "input"+ }+ schema={schema}+ showLabel+ />+ )}+ </div>+ <p className="text-sm text-muted-foreground">+ Configure how observation data maps to the Dataset Item {fieldLabel}+ .+ </p>+ </div>++ <MappingModeSelector+ value={config.mode}+ onChange={handleModeChange}+ fullLabel={getFullLabel()}+ fieldName={field}+ />++ {config.mode === "custom" && config.custom && (+ <CustomMappingEditor+ config={config.custom}+ onChange={handleCustomConfigChange}+ defaultSourceField={defaultSourceField}+ observationData={observationData}+ />+ )}+ </div>++ {/* Right: Preview */}+ <div className="h-full border-l pl-6">+ <MappingPreviewPanel+ fieldLabel={fieldLabel}+ defaultSourceField={defaultSourceField}+ config={config}+ observationData={observationData}+ isLoading={isLoading}+ schema={schema}+ onValidationChange={onValidationChange}+ />+ </div>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/StatusStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/StatusStep.tsxnew file mode 100644index 0000000000..5c41a27c45--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/StatusStep.tsx@@ -0,0 +1,192 @@+import { Button } from "@/src/components/ui/button";+import { Progress } from "@/src/components/ui/progress";+import { api } from "@/src/utils/api";+import { StatusBadge } from "@/src/components/layouts/status-badge";+import { BatchActionStatus } from "@langfuse/shared";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import Link from "next/link";+import { Check, AlertCircle, Loader2 } from "lucide-react";++type StatusStepProps = {+ projectId: string;+ batchActionId: string;+ dataset: { id: string; name: string };+ expectedCount: number;+ onClose: () => void;+};++export function StatusStep({+ projectId,+ batchActionId,+ dataset,+ expectedCount,+ onClose,+}: StatusStepProps) {+ // Poll for status updates+ const status = api.batchAction.byId.useQuery(+ {+ projectId,+ batchActionId,+ },+ {+ refetchInterval: 2000, // Poll every 2 seconds+ },+ );++ // Use expectedCount as fallback when API hasn't populated totalCount yet+ const totalCount = status.data?.totalCount ?? expectedCount;+ const processedCount = status.data?.processedCount ?? 0;+ const failedCount = status.data?.failedCount ?? 0;+ const progressPercent =+ totalCount > 0 ? Math.round((processedCount / totalCount) * 100) : 0;++ const isComplete = [+ BatchActionStatus.Completed,+ BatchActionStatus.Failed,+ BatchActionStatus.Partial,+ ].includes(status.data?.status as BatchActionStatus);+ const isSuccess = status.data?.status === BatchActionStatus.Completed;+ const hasPartialSuccess =+ status.data?.status === BatchActionStatus.Partial ||+ status.data?.status === BatchActionStatus.Completed;++ return (+ <div className="flex flex-col items-center justify-center p-6">+ <div className="w-full max-w-2xl space-y-8">+ {/* Status Icon and Title */}+ <div className="flex flex-col items-center text-center">+ {!isComplete && (+ <div className="mb-4 rounded-full bg-primary/10 p-6">+ <Loader2 className="h-12 w-12 animate-spin text-primary" />+ </div>+ )}+ {isSuccess && (+ <div className="mb-4 rounded-full bg-green-100 p-6 dark:bg-green-900/20">+ <Check className="h-12 w-12 text-green-600 dark:text-green-500" />+ </div>+ )}+ {isComplete && !isSuccess && (+ <div className="mb-4 rounded-full bg-yellow-100 p-6 dark:bg-yellow-900/20">+ <AlertCircle className="h-12 w-12 text-yellow-600 dark:text-yellow-500" />+ </div>+ )}++ <h2 className="mb-2 text-2xl font-semibold">+ {!isComplete && "Adding Observations to Dataset"}+ {isSuccess && "Successfully Added!"}+ {isComplete && !isSuccess && "Completed with Issues"}+ </h2>+ <p className="text-sm text-muted-foreground">+ {!isComplete &&+ `Adding ${totalCount} observations to ${dataset.name}`}+ {isSuccess &&+ `${processedCount} observations have been added to ${dataset.name}`}+ {isComplete &&+ !isSuccess &&+ `${processedCount} observations added, ${failedCount} failed`}+ </p>+ </div>++ {/* Progress/Results Card */}+ {(!isComplete || status.data?.log || failedCount > 0) && (+ <Card>+ <CardHeader>+ <div className="flex items-center justify-between">+ <CardTitle className="text-base">+ {isComplete ? "Results" : "Progress"}+ </CardTitle>+ <StatusBadge+ type={status.data?.status?.toLowerCase() ?? "pending"}+ />+ </div>+ </CardHeader>+ <CardContent className="space-y-4">+ {!isComplete && totalCount > 0 && (+ <>+ <div className="space-y-2">+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted-foreground">+ {processedCount} of {totalCount} processed+ </span>+ <span className="font-medium">{progressPercent}%</span>+ </div>+ <Progress value={progressPercent} className="h-2" />+ </div>++ <div className="grid grid-cols-2 gap-4 rounded-lg bg-muted/50 p-3 text-sm">+ <div className="flex items-center justify-between">+ <span className="text-muted-foreground">Processed</span>+ <span className="font-semibold">{processedCount}</span>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-muted-foreground">Failed</span>+ <span+ className={`font-semibold ${failedCount > 0 ? "text-destructive" : ""}`}+ >+ {failedCount}+ </span>+ </div>+ </div>+ </>+ )}++ {isComplete && failedCount > 0 && (+ <div className="rounded-lg bg-muted/50 p-4 text-sm">+ <div className="flex items-center justify-between">+ <span className="text-muted-foreground">+ Successfully processed+ </span>+ <span className="font-semibold">{processedCount}</span>+ </div>+ <div className="mt-2 flex items-center justify-between">+ <span className="text-muted-foreground">Failed</span>+ <span className="font-semibold text-destructive">+ {failedCount}+ </span>+ </div>+ </div>+ )}++ {status.data?.log && (+ <div className="space-y-2 rounded-lg border border-destructive/50 bg-destructive/5 p-3">+ <p className="text-xs font-medium text-destructive">+ Error Summary:+ </p>+ <pre className="max-h-32 overflow-auto text-[10px] text-muted-foreground">+ {status.data.log}+ </pre>+ </div>+ )}+ </CardContent>+ </Card>+ )}++ {/* Action Buttons */}+ <div className="space-y-3">+ <div className="flex gap-3">+ <Button+ variant="outline"+ onClick={onClose}+ className={isComplete && hasPartialSuccess ? "flex-1" : "w-full"}+ >+ Close+ </Button>+ {isComplete && hasPartialSuccess && (+ <Link+ href={`/project/${projectId}/datasets/${dataset.id}/items`}+ className="flex-1"+ >+ <Button className="w-full">Go to Dataset</Button>+ </Link>+ )}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsxnew file mode 100644index 0000000000..62aeb910f2--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx@@ -0,0 +1,353 @@+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { Label } from "@/src/components/ui/label";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import { Plus, Trash2 } from "lucide-react";+import { JsonPathInput } from "./JsonPathInput";+import { SourceFieldSelector } from "./SourceFieldSelector";+import type {+ CustomMappingConfig,+ SourceField,+ KeyValueMappingEntry,+ ObservationPreviewData,+ MappingTarget,+} from "../types";+import { isJsonPath } from "@langfuse/shared";++type CustomMappingEditorProps = {+ config: CustomMappingConfig;+ onChange: (config: CustomMappingConfig) => void;+ defaultSourceField: SourceField;+ observationData: ObservationPreviewData | null;+};++export function CustomMappingEditor({+ config,+ onChange,+ defaultSourceField,+ observationData,+}: CustomMappingEditorProps) {+ const handleTypeChange = (type: MappingTarget) => {+ if (type === "root") {+ onChange({+ type: "root",+ rootConfig: config.rootConfig ?? {+ sourceField: defaultSourceField,+ jsonPath: "$.",+ },+ keyValueMapConfig: config.keyValueMapConfig,+ });+ } else {+ onChange({+ type: "keyValueMap",+ rootConfig: config.rootConfig,+ keyValueMapConfig: config.keyValueMapConfig ?? {+ entries: [+ {+ id: crypto.randomUUID(),+ key: "value",+ sourceField: defaultSourceField,+ value: "$.",+ },+ ],+ },+ });+ }+ };++ const handleRootConfigChange = (+ field: "sourceField" | "jsonPath",+ value: string,+ ) => {+ onChange({+ ...config,+ rootConfig: {+ sourceField:+ field === "sourceField"+ ? (value as SourceField)+ : (config.rootConfig?.sourceField ?? defaultSourceField),+ jsonPath:+ field === "jsonPath" ? value : (config.rootConfig?.jsonPath ?? "$."),+ },+ });+ };++ const handleAddEntry = () => {+ const entries = config.keyValueMapConfig?.entries ?? [];+ const existingKeys = new Set(entries.map((e) => e.key));+ // Generate a unique default key+ let keyIndex = entries.length + 1;+ let newKey = `field_${keyIndex}`;+ while (existingKeys.has(newKey)) {+ keyIndex++;+ newKey = `field_${keyIndex}`;+ }+ onChange({+ ...config,+ keyValueMapConfig: {+ entries: [+ ...entries,+ {+ id: crypto.randomUUID(),+ key: newKey,+ sourceField: defaultSourceField,+ value: "$.",+ },+ ],+ },+ });+ };++ const handleRemoveEntry = (id: string) => {+ const entries = config.keyValueMapConfig?.entries ?? [];+ const entryToRemove = entries.find((e) => e.id === id);++ // Prevent removing required schema-derived entries+ if (entryToRemove?.fromSchema && entryToRemove?.isRequired) {+ return;+ }++ // Keep at least one entry (unless it's an empty schema-derived optional)+ const remainingEntries = entries.filter((e) => e.id !== id);+ if (remainingEntries.length < 1) return;++ onChange({+ ...config,+ keyValueMapConfig: {+ entries: remainingEntries,+ },+ });+ };++ const handleEntryChange = (+ id: string,+ field: keyof KeyValueMappingEntry,+ value: string,+ ) => {+ const entries = config.keyValueMapConfig?.entries ?? [];+ onChange({+ ...config,+ keyValueMapConfig: {+ entries: entries.map((e) =>+ e.id === id ? { ...e, [field]: value } : e,+ ),+ },+ });+ };++ const getSourceData = (sourceField: SourceField) => {+ if (!observationData) return null;+ return observationData[sourceField];+ };++ return (+ <div className="space-y-2 rounded-md border bg-muted/30 p-4">+ <div>+ <Label className="text-sm font-medium">Target</Label>+ <Tabs+ value={config.type}+ onValueChange={(v) => handleTypeChange(v as MappingTarget)}+ className="mt-2"+ >+ <TabsList className="grid w-full grid-cols-2">+ <TabsTrigger value="root">Root</TabsTrigger>+ <TabsTrigger value="keyValueMap">Key-value map</TabsTrigger>+ </TabsList>+ </Tabs>+ </div>++ {config.type === "root" && (+ <div className="space-y-4">+ <div>+ <Label className="text-sm font-medium">Source</Label>+ <div className="mt-1">+ <SourceFieldSelector+ value={config.rootConfig?.sourceField ?? defaultSourceField}+ onChange={(v) => handleRootConfigChange("sourceField", v)}+ />+ </div>+ </div>+ <div>+ <Label className="text-sm font-medium">JSON Path</Label>+ <div className="mt-1">+ <JsonPathInput+ value={config.rootConfig?.jsonPath ?? "$."}+ onChange={(v) => handleRootConfigChange("jsonPath", v)}+ sourceData={getSourceData(+ config.rootConfig?.sourceField ?? defaultSourceField,+ )}+ placeholder="$.path.to.field"+ />+ </div>+ <p className="p-1 text-xs text-muted-foreground">+ Start with $. to use a JSON path (e.g., $.field)+ </p>+ </div>+ </div>+ )}++ {config.type === "keyValueMap" && (+ <div className="max-h-[35vh] space-y-3 overflow-auto">+ <Label className="text-sm font-medium">Key-value mappings</Label>+ <p className="text-xs text-muted-foreground">+ Build an object with custom keys. Values starting with $ are treated+ as JSON paths.+ </p>++ <div className="space-y-3">+ {(config.keyValueMapConfig?.entries ?? []).map((entry) => {+ // Determine if this entry can be removed+ const isRequiredSchemaField =+ entry.fromSchema === true && entry.isRequired === true;+ const hasMultipleEntries =+ (config.keyValueMapConfig?.entries.length ?? 0) > 1;+ const canRemove = !isRequiredSchemaField && hasMultipleEntries;++ return (+ <KeyValueEntryRow+ key={entry.id}+ entry={entry}+ onKeyChange={(key) => handleEntryChange(entry.id, "key", key)}+ onSourceFieldChange={(sf) =>+ handleEntryChange(entry.id, "sourceField", sf)+ }+ onValueChange={(value) =>+ handleEntryChange(entry.id, "value", value)+ }+ onRemove={() => handleRemoveEntry(entry.id)}+ canRemove={canRemove}+ sourceData={getSourceData(entry.sourceField)}+ />+ );+ })}+ </div>++ <Button+ type="button"+ variant="outline"+ onClick={handleAddEntry}+ className="w-full"+ >+ <Plus className="mr-2 h-4 w-4" />+ Add field+ </Button>+ </div>+ )}+ </div>+ );+}++type KeyValueEntryRowProps = {+ entry: KeyValueMappingEntry;+ onKeyChange: (key: string) => void;+ onSourceFieldChange: (sourceField: SourceField) => void;+ onValueChange: (value: string) => void;+ onRemove: () => void;+ canRemove: boolean;+ sourceData: unknown;+};++function KeyValueEntryRow({+ entry,+ onKeyChange,+ onSourceFieldChange,+ onValueChange,+ onRemove,+ canRemove,+ sourceData,+}: KeyValueEntryRowProps) {+ const isPath = isJsonPath(entry.value);+ const isSchemaField = entry.fromSchema === true;+ const isRequired = entry.isRequired === true;++ return (+ <div+ className={`space-y-2 rounded-md border bg-background p-3 ${+ isSchemaField ? "border-primary/30" : ""+ }`}+ >+ <div className="grid grid-cols-[1fr,auto] gap-2">+ <div>+ <Label className="text-xs text-muted-foreground">+ Key+ {isRequired && <span className="ml-1 text-destructive">*</span>}+ {isSchemaField && (+ <span className="ml-2 text-primary">(from schema)</span>+ )}+ </Label>+ <Input+ value={entry.key}+ onChange={(e) => onKeyChange(e.target.value)}+ placeholder="field_name"+ className="mt-1 h-8"+ readOnly={isSchemaField}+ disabled={isSchemaField}+ />+ </div>+ <div className="flex items-end">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={onRemove}+ disabled={!canRemove}+ className="h-8 w-8 p-0"+ title={+ isSchemaField && isRequired+ ? "Required schema field cannot be removed"+ : "Remove field"+ }+ >+ <Trash2+ className={`h-4 w-4 ${+ !canRemove+ ? "text-muted-foreground/30"+ : "text-muted-foreground"+ }`}+ />+ </Button>+ </div>+ </div>++ <div className="grid grid-cols-[38fr,62fr] gap-2">+ <div>+ <Label className="text-xs text-muted-foreground">Source</Label>+ <div className="mt-1">+ <SourceFieldSelector+ value={entry.sourceField}+ onChange={onSourceFieldChange}+ disabled={!isPath}+ />+ </div>+ </div>+ <div>+ <Label className="text-xs text-muted-foreground">+ Value {!isPath && "(literal)"}+ </Label>+ <div className="mt-1">+ {isPath ? (+ <JsonPathInput+ value={entry.value}+ onChange={onValueChange}+ sourceData={sourceData}+ placeholder="$.path"+ className="h-9"+ />+ ) : (+ <Input+ value={entry.value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder="literal value"+ className="h-9"+ />+ )}++ <p className="pt-1 text-xs text-muted-foreground">+ Start with $. to use a JSON path (e.g., $.field)+ </p>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsxnew file mode 100644index 0000000000..49f5666029--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx@@ -0,0 +1,162 @@+import { useState, useCallback, useMemo } from "react";+import CodeMirror, { EditorView } from "@uiw/react-codemirror";+import { StreamLanguage } from "@codemirror/language";+import type { StringStream } from "@codemirror/language";+import { useTheme } from "next-themes";+import { lightTheme } from "@/src/components/editor/light-theme";+import { darkTheme } from "@/src/components/editor/dark-theme";+import { cn } from "@/src/utils/tailwind";+import { evaluateJsonPath } from "@langfuse/shared";++// JSON path language mode for syntax highlighting+const jsonPathLanguage = StreamLanguage.define({+ name: "jsonpath",+ startState: () => ({ inBracket: false }),+ token: (stream: StringStream, state: { inBracket: boolean }) => {+ // Root $ symbol+ if (stream.match("$")) {+ return "keyword";+ }++ // Dot accessor+ if (stream.match(".")) {+ return "punctuation";+ }++ // Array bracket start+ if (stream.match("[")) {+ state.inBracket = true;+ return "bracket";+ }++ // Array bracket end+ if (stream.match("]")) {+ state.inBracket = false;+ return "bracket";+ }++ // Wildcard+ if (stream.match("*")) {+ return "keyword";+ }++ // Number (array index)+ if (state.inBracket && stream.match(/\d+/)) {+ return "number";+ }++ // Property name+ if (stream.match(/[a-zA-Z_][a-zA-Z0-9_]*/)) {+ return "variable";+ }++ // Skip unknown characters+ stream.next();+ return null;+ },+});++type JsonPathInputProps = {+ value: string;+ onChange: (value: string) => void;+ onBlur?: () => void;+ sourceData: unknown;+ placeholder?: string;+ error?: string;+ className?: string;+};++export function JsonPathInput({+ value,+ onChange,+ onBlur,+ sourceData,+ placeholder = "$.path.to.field",+ error,+ className,+}: JsonPathInputProps) {+ const { resolvedTheme } = useTheme();+ const codeMirrorTheme = resolvedTheme === "dark" ? darkTheme : lightTheme;++ const [resolveError, setResolveError] = useState<string | null>(null);++ // Parse source data once+ const parsedSourceData = useMemo(() => {+ if (sourceData === null || sourceData === undefined) {+ return null;+ }+ if (typeof sourceData === "string") {+ try {+ return JSON.parse(sourceData);+ } catch {+ return sourceData;+ }+ }+ return sourceData;+ }, [sourceData]);++ // Update resolved value when input changes+ const handleChange = useCallback(+ (newValue: string) => {+ onChange(newValue);++ // Try to resolve the JSON path+ if (newValue && newValue.startsWith("$") && parsedSourceData) {+ try {+ evaluateJsonPath(parsedSourceData, newValue);+ } catch (e) {+ setResolveError(e instanceof Error ? e.message : "Invalid JSON path");+ }+ } else {+ setResolveError(null);+ }+ },+ [onChange, parsedSourceData],+ );++ const displayError = error || resolveError;++ return (+ <div className="space-y-1">+ <CodeMirror+ value={value}+ theme={codeMirrorTheme}+ basicSetup={{+ lineNumbers: false,+ foldGutter: false,+ highlightActiveLine: false,+ }}+ extensions={[+ EditorView.theme({+ "&.cm-focused": {+ outline: "none",+ },+ ".cm-content": {+ padding: "8px 12px",+ minHeight: "36px",+ },+ ".cm-line": {+ padding: 0,+ },+ ".cm-scroller": {+ overflow: "auto",+ },+ }),+ jsonPathLanguage,+ EditorView.lineWrapping,+ ]}+ onChange={handleChange}+ onBlur={onBlur}+ placeholder={placeholder}+ className={cn(+ "overflow-hidden rounded-md border text-sm",+ displayError && "border-destructive",+ className,+ )}+ />+ {displayError && (+ <p className="text-xs text-destructive">{displayError}</p>+ )}+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingModeSelector.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingModeSelector.tsxnew file mode 100644index 0000000000..87879d55e7--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingModeSelector.tsx@@ -0,0 +1,55 @@+import { Label } from "@/src/components/ui/label";+import { RadioGroup, RadioGroupItem } from "@/src/components/ui/radio-group";+import type { MappingMode } from "../types";++type MappingModeSelectorProps = {+ value: MappingMode;+ onChange: (mode: MappingMode) => void;+ fullLabel: string; // e.g., "Full observation input"+ fieldName: string; // e.g., "input", "output", "metadata"+};++export function MappingModeSelector({+ value,+ onChange,+ fullLabel,+ fieldName,+}: MappingModeSelectorProps) {+ return (+ <RadioGroup value={value} onValueChange={(v) => onChange(v as MappingMode)}>+ <div className="flex items-center space-x-3 rounded-md border px-3 hover:bg-muted/50">+ <RadioGroupItem value="full" id={`${fieldName}-full`} />+ <Label+ htmlFor={`${fieldName}-full`}+ className="flex-1 cursor-pointer py-3 text-sm font-medium"+ >+ {fullLabel}+ </Label>+ </div>+ <div className="flex items-center space-x-3 rounded-md border px-3 hover:bg-muted/50">+ <RadioGroupItem value="custom" id={`${fieldName}-custom`} />+ <Label+ htmlFor={`${fieldName}-custom`}+ className="flex-1 cursor-pointer py-3 text-sm font-medium"+ >+ Custom mapping+ </Label>+ </div>+ {fieldName !== "input" && (+ <div className="flex items-center space-x-3 rounded-md border px-3 hover:bg-muted/50">+ <RadioGroupItem+ value="none"+ id={`${fieldName}-none`}+ disabled={fieldName === "input"}+ />+ <Label+ htmlFor={`${fieldName}-none`}+ className="flex-1 cursor-pointer py-3 text-sm font-medium"+ >+ None+ </Label>+ </div>+ )}+ </RadioGroup>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsxnew file mode 100644index 0000000000..7da3420d06--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx@@ -0,0 +1,263 @@+import { useMemo, useEffect, useRef } from "react";+import { ArrowDown, AlertCircle, CheckCircle2 } from "lucide-react";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import { Skeleton } from "@/src/components/ui/skeleton";+import type {+ FieldMappingConfig,+ SourceField,+ ObservationPreviewData,+ SchemaValidationError,+} from "../types";+import {+ applyFieldMappingConfig,+ validateFieldAgainstSchema,+} from "@langfuse/shared";++type MappingPreviewPanelProps = {+ fieldLabel: string;+ defaultSourceField: SourceField;+ config: FieldMappingConfig;+ observationData: ObservationPreviewData | null;+ isLoading: boolean;+ /** JSON Schema to validate the result against */+ schema?: unknown;+ /** Callback when validation state changes */+ onValidationChange?: (+ isValid: boolean,+ errors: SchemaValidationError[],+ ) => void;+};++export function MappingPreviewPanel({+ fieldLabel,+ defaultSourceField,+ config,+ observationData,+ isLoading,+ schema,+ onValidationChange,+}: MappingPreviewPanelProps) {+ const hasSchema = schema !== null && schema !== undefined;++ // Compute source data to display+ const sourceData = useMemo(() => {+ if (!observationData) return null;++ // Determine which source field to show based on config+ if (config.mode === "custom" && config.custom) {+ if (config.custom.type === "root" && config.custom.rootConfig) {+ return observationData[config.custom.rootConfig.sourceField];+ }+ // For keyValueMap type, show the default source field+ return observationData[defaultSourceField];+ }++ return observationData[defaultSourceField];+ }, [observationData, config, defaultSourceField]);++ // Compute result data+ const resultData = useMemo(() => {+ if (!observationData) return null;++ return applyFieldMappingConfig({+ observation: {+ input: observationData.input,+ output: observationData.output,+ metadata: observationData.metadata,+ },+ config,+ defaultSourceField,+ });+ }, [observationData, config, defaultSourceField]);++ // Validate result against schema+ const validationResult = useMemo(() => {+ // Skip validation if no schema or "none" mode+ if (!hasSchema || config.mode === "none") {+ return { isValid: true, errors: [] as SchemaValidationError[] };+ }++ // Skip if no result data (no observation)+ if (resultData === null || resultData === undefined) {+ return { isValid: true, errors: [] as SchemaValidationError[] };+ }++ try {+ const result = validateFieldAgainstSchema({+ data: resultData,+ schema: schema as Record<string, unknown>,+ });++ if (result.isValid) {+ return { isValid: true, errors: [] as SchemaValidationError[] };+ }++ return {+ isValid: false,+ errors: result.errors.map((e) => ({+ path: e.path,+ message: e.message,+ })),+ };+ } catch {+ // If validation fails to run, treat as valid (don't block on validation errors)+ return { isValid: true, errors: [] as SchemaValidationError[] };+ }+ }, [hasSchema, config.mode, resultData, schema]);++ // Track previous validation state to avoid redundant callbacks+ const prevValidationRef = useRef<{+ isValid: boolean;+ errorsJson: string;+ } | null>(null);++ // Notify parent of validation state changes (only when values actually change)+ useEffect(() => {+ const errorsJson = JSON.stringify(validationResult.errors);+ const prev = prevValidationRef.current;++ // Only call if values actually changed+ if (+ !prev ||+ prev.isValid !== validationResult.isValid ||+ prev.errorsJson !== errorsJson+ ) {+ prevValidationRef.current = {+ isValid: validationResult.isValid,+ errorsJson,+ };+ onValidationChange?.(validationResult.isValid, validationResult.errors);+ }+ }, [validationResult.isValid, validationResult.errors, onValidationChange]);++ // Determine source label based on config+ const sourceLabel = useMemo(() => {+ if (config.mode === "custom" && config.custom) {+ if (config.custom.type === "root" && config.custom.rootConfig) {+ return `observation.${config.custom.rootConfig.sourceField}`;+ }+ if (config.custom.type === "keyValueMap") {+ // For keyValueMap type, multiple sources may be used+ const sources = new Set(+ config.custom.keyValueMapConfig?.entries.map((e) => e.sourceField) ??+ [],+ );+ if (sources.size === 1) {+ return `observation.${Array.from(sources)[0]}`;+ }+ return "multiple sources";+ }+ }+ return `observation.${defaultSourceField}`;+ }, [config, defaultSourceField]);++ if (isLoading) {+ return (+ <div className="space-y-4">+ <div>+ <h3 className="text-sm font-semibold">Preview</h3>+ <p className="text-xs text-muted-foreground">+ Sample from first observation+ </p>+ </div>+ <Skeleton className="h-32 w-full" />+ <Skeleton className="h-32 w-full" />+ </div>+ );+ }++ if (!observationData) {+ return (+ <div className="space-y-4">+ <div>+ <h3 className="text-sm font-semibold">Preview</h3>+ <p className="text-xs text-muted-foreground">+ Sample from first observation+ </p>+ </div>+ <div className="flex h-64 items-center justify-center rounded-md border bg-muted/30 p-4">+ <p className="text-sm text-muted-foreground">+ No observation data available+ </p>+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-2">+ <div>+ <h3 className="text-sm font-semibold">Preview</h3>+ <p className="text-xs text-muted-foreground">+ Sample from first observation+ </p>+ </div>++ {/* Source data */}+ <div className="space-y-2">+ <p className="text-xs font-medium text-muted-foreground">+ Source: {sourceLabel}+ </p>+ <div className="max-h-[21vh] overflow-auto rounded-md border bg-muted/30">+ <JSONView json={sourceData} className="text-xs" />+ </div>+ </div>++ {/* Arrow */}+ <div className="flex justify-center">+ <ArrowDown className="h-6 w-6 text-muted-foreground" />+ </div>++ {/* Result data */}+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <p className="text-xs font-medium text-muted-foreground">+ Result: Dataset Item {fieldLabel}+ </p>+ {/* Validation status indicator */}+ {hasSchema && config.mode !== "none" && (+ <div className="flex items-center gap-1">+ {validationResult.isValid ? (+ <CheckCircle2 className="h-3.5 w-3.5 text-green-600" />+ ) : (+ <AlertCircle className="h-3.5 w-3.5 text-destructive" />+ )}+ </div>+ )}+ </div>+ <div+ className={`max-h-[21vh] overflow-auto rounded-md border bg-background ${+ hasSchema && !validationResult.isValid && config.mode !== "none"+ ? "border-destructive"+ : ""+ }`}+ >+ {config.mode === "none" ? (+ <div className="p-3 text-xs italic text-muted-foreground">null</div>+ ) : (+ <JSONView json={resultData} className="text-xs" />+ )}+ </div>++ {/* Validation errors */}+ {hasSchema &&+ !validationResult.isValid &&+ validationResult.errors.length > 0 && (+ <div className="max-h-[5vh] overflow-y-auto rounded-md border border-destructive/50 bg-destructive/10 p-2">+ <p className="mb-1 text-xs font-medium text-destructive">+ Schema validation errors:+ </p>+ <ul className="space-y-0.5">+ {validationResult.errors.map((error, idx) => (+ <li key={idx} className="text-xs text-destructive">+ <span className="font-mono">{error.path || "root"}</span>:{" "}+ {error.message}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/SourceFieldSelector.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/SourceFieldSelector.tsxnew file mode 100644index 0000000000..24f8847e91--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/SourceFieldSelector.tsx@@ -0,0 +1,37 @@+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import type { SourceField } from "../types";++type SourceFieldSelectorProps = {+ value: SourceField;+ onChange: (field: SourceField) => void;+ disabled?: boolean;+};++export function SourceFieldSelector({+ value,+ onChange,+ disabled = false,+}: SourceFieldSelectorProps) {+ return (+ <Select+ value={value}+ onValueChange={(v) => onChange(v as SourceField)}+ disabled={disabled}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="input">Input</SelectItem>+ <SelectItem value="output">Output</SelectItem>+ <SelectItem value="metadata">Metadata</SelectItem>+ </SelectContent>+ </Select>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsxnew file mode 100644index 0000000000..6bfcbca945--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx@@ -0,0 +1,196 @@+import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogBody,+ DialogFooter,+} from "@/src/components/ui/dialog";+import { ChevronLeft } from "lucide-react";+import type { BatchActionQuery } from "@langfuse/shared";++// Step components+import { DatasetChoiceStep } from "./DatasetChoiceStep";+import { DatasetSelectStep } from "./DatasetSelectStep";+import { DatasetCreateStep } from "./DatasetCreateStep";+import { MappingStep } from "./MappingStep";+import { FinalPreviewStep } from "./FinalPreviewStep";+import { StatusStep } from "./StatusStep";++// Hook+import { useAddToDatasetWizard } from "./useAddToDatasetWizard";++type AddObservationsToDatasetDialogProps = {+ projectId: string;+ selectedObservationIds: string[];+ query: BatchActionQuery;+ selectAll: boolean;+ totalCount: number;+ onClose: () => void;+ exampleObservation: {+ id: string;+ traceId: string;+ startTime?: Date;+ };+};++export function AddObservationsToDatasetDialog(+ props: AddObservationsToDatasetDialogProps,+) {+ const { projectId, onClose } = props;++ const {+ state,+ formRef,+ observationData,+ isLoadingObservation,+ displayCount,+ selectMode,+ goBack,+ goToStep,+ handleNextClick,+ handleDatasetSelect,+ handleDatasetCreated,+ handleInputConfigChange,+ handleOutputConfigChange,+ handleMetadataConfigChange,+ handleCreateValidationChange,+ handleInputValidationChange,+ handleOutputValidationChange,+ isNextDisabled,+ nextButtonLabel,+ dialogDescription,+ showBackButton,+ canClose,+ isLoading,+ } = useAddToDatasetWizard(props);++ const { step } = state;++ return (+ <Dialog open onOpenChange={(open) => !open && canClose && onClose()}>+ <DialogContent className="flex max-h-[90vh] max-w-6xl flex-col">+ <DialogHeader>+ <DialogTitle>+ Add {displayCount} Observation(s) to dataset+ {!["select", "create", "choice"].includes(step)+ ? " " + state.dataset.name+ : ""}+ </DialogTitle>+ <DialogDescription className="mt-1">+ {dialogDescription}+ </DialogDescription>+ </DialogHeader>++ <DialogBody className="flex-1 overflow-y-auto p-0">+ {step === "choice" && <DatasetChoiceStep onSelectMode={selectMode} />}++ {step === "select" && (+ <DatasetSelectStep+ projectId={projectId}+ dataset={state.dataset}+ onDatasetSelect={handleDatasetSelect}+ />+ )}++ {step === "create" && (+ <DatasetCreateStep+ projectId={projectId}+ formRef={formRef}+ onDatasetCreated={handleDatasetCreated}+ onValidationChange={handleCreateValidationChange}+ />+ )}++ {step === "input-mapping" && (+ <MappingStep+ field="input"+ fieldLabel="Input"+ defaultSourceField="input"+ config={state.mapping.input}+ onConfigChange={handleInputConfigChange}+ observationData={observationData}+ isLoading={isLoadingObservation}+ schema={state.dataset.inputSchema}+ onValidationChange={handleInputValidationChange}+ />+ )}++ {step === "output-mapping" && (+ <MappingStep+ field="expectedOutput"+ fieldLabel="Expected Output"+ defaultSourceField="output"+ config={state.mapping.expectedOutput}+ onConfigChange={handleOutputConfigChange}+ observationData={observationData}+ isLoading={isLoadingObservation}+ schema={state.dataset.expectedOutputSchema}+ onValidationChange={handleOutputValidationChange}+ />+ )}++ {step === "metadata-mapping" && (+ <MappingStep+ field="metadata"+ fieldLabel="Metadata"+ defaultSourceField="metadata"+ config={state.mapping.metadata}+ onConfigChange={handleMetadataConfigChange}+ observationData={observationData}+ isLoading={isLoadingObservation}+ />+ )}++ {step === "preview" && state.dataset.id && state.dataset.name && (+ <FinalPreviewStep+ dataset={{ id: state.dataset.id, name: state.dataset.name }}+ mapping={state.mapping}+ observationData={observationData}+ totalCount={displayCount}+ onEditStep={goToStep}+ />+ )}++ {step === "status" &&+ state.submission.batchActionId &&+ state.dataset.id &&+ state.dataset.name && (+ <StatusStep+ projectId={projectId}+ batchActionId={state.submission.batchActionId}+ dataset={{ id: state.dataset.id, name: state.dataset.name }}+ expectedCount={displayCount}+ onClose={onClose}+ />+ )}+ </DialogBody>++ {/* Footer with navigation buttons */}+ {step !== "status" && step !== "choice" && (+ <DialogFooter className="flex justify-between">+ <div className="flex-grow">+ {showBackButton && (+ <Button type="button" variant="ghost" onClick={goBack}>+ <ChevronLeft className="mr-1 h-4 w-4" />+ Back+ </Button>+ )}+ </div>+ <div>+ <Button+ onClick={handleNextClick}+ disabled={isNextDisabled}+ loading={isLoading}+ >+ {nextButtonLabel}+ </Button>+ </div>+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/types.ts b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/types.tsnew file mode 100644index 0000000000..2ef5db0fe9--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/types.ts@@ -0,0 +1,203 @@+import type { RefObject } from "react";+import type { DatasetFormRef } from "@/src/features/datasets/components/DatasetForm";++// Re-export base types from shared+export type {+ SourceField,+ MappingMode,+ MappingTarget,+ RootMappingConfig,+ AddToDatasetMapping,+} from "@langfuse/shared";++import type {+ SourceField,+ MappingMode,+ RootMappingConfig,+ KeyValueMappingEntry as SharedKeyValueMappingEntry,+ MappingTarget,+} from "@langfuse/shared";++// Step definitions - dialog-specific+export type DialogStep =+ | "choice"+ | "select"+ | "create"+ | "input-mapping"+ | "output-mapping"+ | "metadata-mapping"+ | "preview"+ | "status";++// Extended KeyValueMappingEntry with UI-specific properties+export type KeyValueMappingEntry = SharedKeyValueMappingEntry & {+ /** Whether this entry was generated from schema (UI only, not persisted) */+ fromSchema?: boolean;+ /** Whether this is a required field per schema (UI only, not persisted) */+ isRequired?: boolean;+};++// Custom mapping configuration using UI-extended KeyValueMappingEntry+export type CustomMappingConfig = {+ type: MappingTarget;+ rootConfig?: RootMappingConfig;+ keyValueMapConfig?: {+ entries: KeyValueMappingEntry[];+ };+};++// Per-field mapping config using UI-extended CustomMappingConfig+export type FieldMappingConfig = {+ mode: MappingMode;+ custom?: CustomMappingConfig;+};++// Complete mapping config for all three fields (UI version with extended types)+export type MappingConfig = {+ input: FieldMappingConfig;+ expectedOutput: FieldMappingConfig;+ metadata: FieldMappingConfig;+};++// Default mapping config+export const DEFAULT_MAPPING_CONFIG: MappingConfig = {+ input: { mode: "full" },+ expectedOutput: { mode: "full" },+ metadata: { mode: "none" },+};++// Observation data for preview+export type ObservationPreviewData = {+ id: string;+ input: unknown;+ output: unknown;+ metadata: unknown;+};++// Prop groups for each step+export type DatasetChoiceStepProps = {+ onSelectMode: (mode: "create" | "select") => void;+};++export type DatasetSelectStepProps = {+ projectId: string;+ dataset: WizardState["dataset"];+ onDatasetSelect: (dataset: DatasetInfo) => void;+};++export type DatasetCreateStepProps = {+ projectId: string;+ formRef: RefObject<DatasetFormRef | null>;+ onDatasetCreated: (params: {+ id: string;+ name: string;+ inputSchema: unknown;+ expectedOutputSchema: unknown;+ }) => void;+ onValidationChange?: (isValid: boolean, isSubmitting: boolean) => void;+};++// Schema validation error type+export type SchemaValidationError = {+ path: string;+ message: string;+};++// Mapping step props (reusable for Input/Output/Metadata)+export type MappingStepProps = {+ field: "input" | "expectedOutput" | "metadata";+ fieldLabel: string;+ defaultSourceField: SourceField;+ config: FieldMappingConfig;+ onConfigChange: (config: FieldMappingConfig) => void;+ observationData: ObservationPreviewData | null;+ isLoading: boolean;+ /** JSON Schema for this field (inputSchema for input, expectedOutputSchema for expectedOutput) */+ schema?: unknown;+ /** Callback when validation state changes */+ onValidationChange?: (+ isValid: boolean,+ errors: SchemaValidationError[],+ ) => void;+};++// Final preview step props+export type FinalPreviewStepProps = {+ dataset: { id: string; name: string };+ mapping: MappingConfig;+ observationData: ObservationPreviewData | null;+ totalCount: number;+ onEditStep: (step: DialogStep) => void;+};++export type StatusStepProps = {+ projectId: string;+ batchActionId: string;+ dataset: { id: string; name: string };+ expectedCount: number;+ onClose: () => void;+};++// Dataset info for selection/creation+export type DatasetInfo = {+ id: string;+ name: string;+ inputSchema: unknown;+ expectedOutputSchema: unknown;+};++// Wizard state for useReducer+export type WizardState = {+ step: DialogStep;+ dataset: {+ id: string | null;+ name: string | null;+ inputSchema: unknown;+ expectedOutputSchema: unknown;+ };+ mapping: MappingConfig;+ submission: {+ batchActionId: string | null;+ isSubmitting: boolean;+ };+ validation: {+ inputMapping: boolean;+ outputMapping: boolean;+ };+ createStep: {+ canContinue: boolean;+ isCreating: boolean;+ };+};++// Wizard actions for useReducer+export type WizardAction =+ // Navigation+ | { type: "SELECT_MODE"; mode: "create" | "select" }+ | { type: "NEXT_STEP" }+ | { type: "BACK" }+ | { type: "GO_TO_STEP"; step: DialogStep }+ // Dataset+ | { type: "SELECT_DATASET"; dataset: DatasetInfo }+ | { type: "DATASET_CREATED"; dataset: DatasetInfo }+ // Mapping+ | {+ type: "UPDATE_MAPPING";+ field: "input" | "expectedOutput" | "metadata";+ config: FieldMappingConfig;+ }+ // Validation+ | {+ type: "SET_MAPPING_VALIDATION";+ field: "input" | "output";+ isValid: boolean;+ }+ | {+ type: "SET_CREATE_VALIDATION";+ canContinue: boolean;+ isCreating: boolean;+ }+ // Submission+ | { type: "SUBMIT_START" }+ | { type: "SUBMIT_SUCCESS"; batchActionId: string }+ | { type: "SUBMIT_ERROR" };diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/useAddToDatasetWizard.ts b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/useAddToDatasetWizard.tsnew file mode 100644index 0000000000..62ac545854--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/useAddToDatasetWizard.ts@@ -0,0 +1,354 @@+import { useReducer, useCallback, useMemo, useRef } from "react";+import { api } from "@/src/utils/api";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import type { BatchActionQuery } from "@langfuse/shared";+import type { DatasetFormRef } from "@/src/features/datasets/components/DatasetForm";+import type {+ DatasetInfo,+ DialogStep,+ FieldMappingConfig,+ ObservationPreviewData,+ SchemaValidationError,+} from "./types";+import { wizardReducer, initialWizardState } from "./wizardReducer";++export type UseAddToDatasetWizardProps = {+ projectId: string;+ selectedObservationIds: string[];+ query: BatchActionQuery;+ selectAll: boolean;+ totalCount: number;+ exampleObservation: {+ id: string;+ traceId: string;+ startTime?: Date;+ };+};++export function useAddToDatasetWizard(props: UseAddToDatasetWizardProps) {+ const {+ projectId,+ selectedObservationIds,+ query,+ selectAll,+ totalCount,+ exampleObservation,+ } = props;++ const [state, dispatch] = useReducer(wizardReducer, initialWizardState);++ // Ref for DatasetForm imperative submit+ const formRef = useRef<DatasetFormRef>(null);++ // Get example observation for preview+ const observationQuery = api.observations.byId.useQuery(+ {+ observationId: exampleObservation.id,+ traceId: exampleObservation.traceId,+ projectId,+ startTime: exampleObservation.startTime,+ },+ {+ enabled: true,+ },+ );++ // Transform observation data for preview+ const observationData: ObservationPreviewData | null = observationQuery.data+ ? {+ id: observationQuery.data.id,+ input: observationQuery.data.input,+ output: observationQuery.data.output,+ metadata: observationQuery.data.metadata,+ }+ : null;++ // Mutation for creating batch action+ const createBatchAction = api.batchAction.addToDataset.create.useMutation({+ onSuccess: (data) => {+ dispatch({ type: "SUBMIT_SUCCESS", batchActionId: data.id });+ },+ onError: (error) => {+ showErrorToast("Failed to schedule action", error.message);+ dispatch({ type: "SUBMIT_ERROR" });+ },+ });++ // Display count+ const displayCount = selectAll ? totalCount : selectedObservationIds.length;++ // Action dispatchers+ const selectMode = useCallback((mode: "create" | "select") => {+ dispatch({ type: "SELECT_MODE", mode });+ }, []);++ const goNext = useCallback(() => {+ dispatch({ type: "NEXT_STEP" });+ }, []);++ const goBack = useCallback(() => {+ dispatch({ type: "BACK" });+ }, []);++ const goToStep = useCallback((step: DialogStep) => {+ dispatch({ type: "GO_TO_STEP", step });+ }, []);++ // Submit handler+ const handleSubmit = useCallback(async () => {+ if (!state.dataset.id || !state.dataset.name) return;++ dispatch({ type: "SUBMIT_START" });++ // If not selecting all, inject ID filter to only process selected observations+ const finalQuery = selectAll+ ? query+ : {+ ...query,+ filter: [+ ...(query.filter || []),+ {+ column: "id",+ operator: "any of" as const,+ value: selectedObservationIds,+ type: "stringOptions" as const,+ },+ ],+ };++ await createBatchAction.mutateAsync({+ projectId,+ query: finalQuery,+ config: {+ datasetId: state.dataset.id,+ datasetName: state.dataset.name,+ mapping: state.mapping,+ },+ });+ }, [+ state.dataset.id,+ state.dataset.name,+ state.mapping,+ selectAll,+ query,+ selectedObservationIds,+ projectId,+ createBatchAction,+ ]);++ // Handle next button click - coordinates different actions per step+ const handleNextClick = useCallback(() => {+ switch (state.step) {+ case "select":+ goNext();+ break;+ case "create":+ // Trigger form submission via ref+ formRef.current?.submit();+ break;+ case "input-mapping":+ case "output-mapping":+ case "metadata-mapping":+ goNext();+ break;+ case "preview":+ handleSubmit();+ break;+ default:+ break;+ }+ }, [state.step, goNext, handleSubmit]);++ // Callback adapters for child components+ const handleDatasetSelect = useCallback((dataset: DatasetInfo) => {+ dispatch({ type: "SELECT_DATASET", dataset });+ }, []);++ const handleDatasetCreated = useCallback(+ (params: {+ id: string;+ name: string;+ inputSchema: unknown;+ expectedOutputSchema: unknown;+ }) => {+ dispatch({ type: "DATASET_CREATED", dataset: params });+ },+ [],+ );++ const handleMappingConfigChange = useCallback(+ (+ field: "input" | "expectedOutput" | "metadata",+ config: FieldMappingConfig,+ ) => {+ dispatch({ type: "UPDATE_MAPPING", field, config });+ },+ [],+ );++ // Pre-bound callbacks for each mapping field to avoid inline functions in JSX+ const handleInputConfigChange = useCallback((config: FieldMappingConfig) => {+ dispatch({ type: "UPDATE_MAPPING", field: "input", config });+ }, []);++ const handleOutputConfigChange = useCallback((config: FieldMappingConfig) => {+ dispatch({ type: "UPDATE_MAPPING", field: "expectedOutput", config });+ }, []);++ const handleMetadataConfigChange = useCallback(+ (config: FieldMappingConfig) => {+ dispatch({ type: "UPDATE_MAPPING", field: "metadata", config });+ },+ [],+ );++ const handleCreateValidationChange = useCallback(+ (isValid: boolean, isCreating: boolean) => {+ dispatch({+ type: "SET_CREATE_VALIDATION",+ canContinue: isValid,+ isCreating,+ });+ },+ [],+ );++ const handleInputValidationChange = useCallback(+ (isValid: boolean, _errors: SchemaValidationError[]) => {+ dispatch({ type: "SET_MAPPING_VALIDATION", field: "input", isValid });+ },+ [],+ );++ const handleOutputValidationChange = useCallback(+ (isValid: boolean, _errors: SchemaValidationError[]) => {+ dispatch({ type: "SET_MAPPING_VALIDATION", field: "output", isValid });+ },+ [],+ );++ // Derived state+ const canContinueFromSelect = useMemo(+ () => !!state.dataset.id && !!state.dataset.name,+ [state.dataset.id, state.dataset.name],+ );++ const isNextDisabled = useMemo(() => {+ switch (state.step) {+ case "select":+ return !canContinueFromSelect;+ case "create":+ return !state.createStep.canContinue || state.createStep.isCreating;+ case "input-mapping":+ // Block if schema validation fails (only when schema exists)+ return (+ state.dataset.inputSchema !== null && !state.validation.inputMapping+ );+ case "output-mapping":+ // Block if schema validation fails (only when schema exists)+ return (+ state.dataset.expectedOutputSchema !== null &&+ !state.validation.outputMapping+ );+ case "preview":+ return state.submission.isSubmitting;+ default:+ return false;+ }+ }, [+ state.step,+ canContinueFromSelect,+ state.createStep.canContinue,+ state.createStep.isCreating,+ state.dataset.inputSchema,+ state.dataset.expectedOutputSchema,+ state.validation.inputMapping,+ state.validation.outputMapping,+ state.submission.isSubmitting,+ ]);++ const nextButtonLabel = useMemo(() => {+ switch (state.step) {+ case "select":+ return "Continue";+ case "create":+ return state.createStep.isCreating+ ? "Creating..."+ : "Create & Continue";+ case "input-mapping":+ case "output-mapping":+ case "metadata-mapping":+ return "Next";+ case "preview":+ return state.submission.isSubmitting ? "Adding..." : "Add to Dataset";+ default:+ return "Continue";+ }+ }, [state.step, state.createStep.isCreating, state.submission.isSubmitting]);++ const dialogDescription = useMemo(() => {+ switch (state.step) {+ case "choice":+ return "Choose where to add your observations";+ case "select":+ return "Select an existing dataset";+ case "create":+ return "Create a new dataset";+ case "input-mapping":+ return "Configure dataset item input mapping";+ case "output-mapping":+ return "Configure dataset item expected output mapping";+ case "metadata-mapping":+ return "Configure dataset item metadata mapping";+ case "preview":+ return "Review and confirm your configuration";+ case "status":+ return "Your bulk action status";+ default:+ return "";+ }+ }, [state.step]);++ const showBackButton = state.step !== "choice" && state.step !== "status";+ const canClose = state.step !== "status";+ const isLoading =+ state.step === "create"+ ? state.createStep.isCreating+ : state.step === "preview"+ ? state.submission.isSubmitting+ : false;++ return {+ // State+ state,+ formRef,+ observationData,+ isLoadingObservation: observationQuery.isLoading,+ displayCount,++ // Actions+ selectMode,+ goBack,+ goToStep,+ handleNextClick,++ // Child component callbacks+ handleDatasetSelect,+ handleDatasetCreated,+ handleMappingConfigChange,+ handleInputConfigChange,+ handleOutputConfigChange,+ handleMetadataConfigChange,+ handleCreateValidationChange,+ handleInputValidationChange,+ handleOutputValidationChange,++ // Derived state+ isNextDisabled,+ nextButtonLabel,+ dialogDescription,+ showBackButton,+ canClose,+ isLoading,+ };+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/utils/extractSchemaFields.ts b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/utils/extractSchemaFields.tsnew file mode 100644index 0000000000..4372cdf4db--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/utils/extractSchemaFields.ts@@ -0,0 +1,204 @@+/**+ * Utility to extract fields from a JSON Schema for pre-populating key-value mapping.+ *+ * Extracts top-level and nested object properties with dot notation paths.+ * Handles common JSON Schema patterns but intentionally limits complexity.+ */++export type SchemaField = {+ /** Dot notation path, e.g., "context.user_id" */+ path: string;+ /** JSON Schema type: "string", "number", "object", "array", etc. */+ type: string;+ /** Whether this field is required */+ required: boolean;+ /** Description from schema, if available */+ description?: string;+};++type JSONSchemaObject = {+ type?: string | string[];+ properties?: Record<string, JSONSchemaObject>;+ required?: string[];+ items?: JSONSchemaObject;+ description?: string;+ anyOf?: JSONSchemaObject[];+ oneOf?: JSONSchemaObject[];+ allOf?: JSONSchemaObject[];+ $ref?: string;+};++/**+ * Extract fields from a JSON Schema for use in key-value mapping.+ *+ * @param schema - The JSON Schema to extract fields from+ * @param maxDepth - Maximum nesting depth to traverse (default: 3)+ * @returns Array of schema fields with paths, types, and required status+ *+ * @example+ * const schema = {+ * type: "object",+ * required: ["prompt"],+ * properties: {+ * prompt: { type: "string" },+ * context: {+ * type: "object",+ * properties: {+ * user_id: { type: "string" }+ * }+ * }+ * }+ * };+ *+ * extractSchemaFields(schema);+ * // Returns:+ * // [+ * // { path: "prompt", type: "string", required: true },+ * // { path: "context", type: "object", required: false },+ * // { path: "context.user_id", type: "string", required: false }+ * // ]+ */+export function extractSchemaFields(+ schema: unknown,+ maxDepth: number = 3,+): SchemaField[] {+ if (!isJsonSchemaObject(schema)) {+ return [];+ }++ // Only extract from object-type schemas+ const schemaType = getSchemaType(schema);+ if (schemaType !== "object") {+ return [];+ }++ const fields: SchemaField[] = [];+ extractFieldsRecursive({+ schema,+ prefix: "",+ requiredSet: new Set(schema.required ?? []),+ fields,+ depth: 0,+ maxDepth,+ });++ return fields;+}++/**+ * Check if the schema is an object type (key-value mapping makes sense).+ */+export function isObjectSchema(schema: unknown): boolean {+ if (!isJsonSchemaObject(schema)) {+ return false;+ }+ return getSchemaType(schema) === "object";+}++// --- Internal helpers ---++function isJsonSchemaObject(value: unknown): value is JSONSchemaObject {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function getSchemaType(schema: JSONSchemaObject): string | undefined {+ if (typeof schema.type === "string") {+ return schema.type;+ }+ if (Array.isArray(schema.type) && schema.type.length > 0) {+ // Return first non-null type+ return schema.type.find((t) => t !== "null") ?? schema.type[0];+ }+ // Infer object type if properties exist+ if (schema.properties) {+ return "object";+ }+ return undefined;+}++function extractFieldsRecursive(params: {+ schema: JSONSchemaObject;+ prefix: string;+ requiredSet: Set<string>;+ fields: SchemaField[];+ depth: number;+ maxDepth: number;+}): void {+ const { schema, prefix, requiredSet, fields, depth, maxDepth } = params;++ if (depth >= maxDepth) {+ return;+ }++ const properties = schema.properties;+ if (!properties) {+ return;+ }++ for (const [key, propSchema] of Object.entries(properties)) {+ if (!isJsonSchemaObject(propSchema)) {+ continue;+ }++ const path = prefix ? `${prefix}.${key}` : key;+ const propType = getSchemaType(propSchema) ?? "unknown";+ const isRequired = requiredSet.has(key);++ // Add this field+ fields.push({+ path,+ type: propType,+ required: isRequired,+ description: propSchema.description,+ });++ // Recurse into nested objects (but not arrays - those are complex)+ if (propType === "object" && propSchema.properties) {+ extractFieldsRecursive({+ schema: propSchema,+ prefix: path,+ requiredSet: new Set(propSchema.required ?? []),+ fields,+ depth: depth + 1,+ maxDepth,+ });+ }+ }+}++/**+ * Generate default key-value entries from schema fields.+ * Only includes required fields and top-level optional fields.+ */+export function generateEntriesFromSchema(+ schemaFields: SchemaField[],+ defaultSourceField: "input" | "output" | "metadata",+): Array<{+ id: string;+ key: string;+ sourceField: "input" | "output" | "metadata";+ value: string;+ fromSchema: boolean;+ isRequired: boolean;+}> {+ // Filter to include:+ // 1. All required fields+ // 2. Top-level optional fields (no dot in path)+ // 3. Skip nested optional fields to avoid clutter+ const fieldsToInclude = schemaFields.filter((field) => {+ if (field.required) return true;+ // Include top-level optional fields+ if (!field.path.includes(".")) return true;+ // Skip deeply nested optional fields+ return false;+ });++ return fieldsToInclude.map((field, index) => ({+ id: `schema-${index}-${field.path}`,+ key: field.path,+ sourceField: defaultSourceField,+ value: "", // User fills this in+ fromSchema: true,+ isRequired: field.required,+ }));+}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/wizardReducer.ts b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/wizardReducer.tsnew file mode 100644index 0000000000..1487878a92--- /dev/null+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/wizardReducer.ts@@ -0,0 +1,147 @@+import type { WizardState, WizardAction, DialogStep } from "./types";+import { DEFAULT_MAPPING_CONFIG } from "./types";++export const initialWizardState: WizardState = {+ step: "choice",+ dataset: {+ id: null,+ name: null,+ inputSchema: null,+ expectedOutputSchema: null,+ },+ mapping: DEFAULT_MAPPING_CONFIG,+ submission: {+ batchActionId: null,+ isSubmitting: false,+ },+ validation: {+ inputMapping: true,+ outputMapping: true,+ },+ createStep: {+ canContinue: false,+ isCreating: false,+ },+};++// Step transition maps for navigation+const NEXT_STEP_MAP: Partial<Record<DialogStep, DialogStep>> = {+ select: "input-mapping",+ "input-mapping": "output-mapping",+ "output-mapping": "metadata-mapping",+ "metadata-mapping": "preview",+};++const BACK_STEP_MAP: Partial<Record<DialogStep, DialogStep>> = {+ select: "choice",+ create: "choice",+ "input-mapping": "choice",+ "output-mapping": "input-mapping",+ "metadata-mapping": "output-mapping",+ preview: "metadata-mapping",+};++export function wizardReducer(+ state: WizardState,+ action: WizardAction,+): WizardState {+ switch (action.type) {+ case "SELECT_MODE":+ return { ...state, step: action.mode };++ case "NEXT_STEP": {+ const nextStep = NEXT_STEP_MAP[state.step];+ return nextStep ? { ...state, step: nextStep } : state;+ }++ case "BACK": {+ const prevStep = BACK_STEP_MAP[state.step];+ return prevStep ? { ...state, step: prevStep } : state;+ }++ case "GO_TO_STEP":+ return { ...state, step: action.step };++ case "SELECT_DATASET":+ return {+ ...state,+ dataset: {+ id: action.dataset.id,+ name: action.dataset.name,+ inputSchema: action.dataset.inputSchema,+ expectedOutputSchema: action.dataset.expectedOutputSchema,+ },+ // Reset mapping when dataset changes+ mapping: DEFAULT_MAPPING_CONFIG,+ validation: { inputMapping: true, outputMapping: true },+ };++ case "DATASET_CREATED":+ return {+ ...state,+ step: "input-mapping",+ dataset: {+ id: action.dataset.id,+ name: action.dataset.name,+ inputSchema: action.dataset.inputSchema,+ expectedOutputSchema: action.dataset.expectedOutputSchema,+ },+ // Reset mapping for new dataset+ mapping: DEFAULT_MAPPING_CONFIG,+ validation: { inputMapping: true, outputMapping: true },+ };++ case "UPDATE_MAPPING":+ return {+ ...state,+ mapping: {+ ...state.mapping,+ [action.field]: action.config,+ },+ };++ case "SET_MAPPING_VALIDATION":+ return {+ ...state,+ validation: {+ ...state.validation,+ [action.field === "input" ? "inputMapping" : "outputMapping"]:+ action.isValid,+ },+ };++ case "SET_CREATE_VALIDATION":+ return {+ ...state,+ createStep: {+ canContinue: action.canContinue,+ isCreating: action.isCreating,+ },+ };++ case "SUBMIT_START":+ return {+ ...state,+ submission: { ...state.submission, isSubmitting: true },+ };++ case "SUBMIT_SUCCESS":+ return {+ ...state,+ step: "status",+ submission: {+ batchActionId: action.batchActionId,+ isSubmitting: false,+ },+ };++ case "SUBMIT_ERROR":+ return {+ ...state,+ submission: { ...state.submission, isSubmitting: false },+ };++ default:+ return state;+ }+}diff --git a/web/src/features/batch-actions/components/BatchActionsSettingsPage.tsx b/web/src/features/batch-actions/components/BatchActionsSettingsPage.tsxnew file mode 100644index 0000000000..2682818bb8--- /dev/null+++ b/web/src/features/batch-actions/components/BatchActionsSettingsPage.tsx@@ -0,0 +1,36 @@+import Header from "@/src/components/layouts/header";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import { SettingsTableCard } from "@/src/components/layouts/settings-table-card";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { BatchActionsTable } from "./BatchActionsTable";++export function BatchActionsSettingsPage(props: { projectId: string }) {+ const hasAccess = useHasProjectAccess({+ projectId: props.projectId,+ scope: "datasets:CUD",+ });++ return (+ <>+ <Header title="Batch Actions" />+ <p className="mb-4 text-sm">+ Track the status of bulk operations performed on tables, such as adding+ observations to datasets, deleting traces, and adding items to+ annotation queues. Actions are processed asynchronously in the+ background.+ </p>+ {hasAccess ? (+ <SettingsTableCard>+ <BatchActionsTable projectId={props.projectId} />+ </SettingsTableCard>+ ) : (+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view batch actions.+ </AlertDescription>+ </Alert>+ )}+ </>+ );+}diff --git a/web/src/features/batch-actions/components/BatchActionsTable.tsx b/web/src/features/batch-actions/components/BatchActionsTable.tsxnew file mode 100644index 0000000000..e1d92b4689--- /dev/null+++ b/web/src/features/batch-actions/components/BatchActionsTable.tsx@@ -0,0 +1,211 @@+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { api } from "@/src/utils/api";+import { safeExtract } from "@/src/utils/map-utils";+import { StatusBadge } from "@/src/components/layouts/status-badge";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import { InfoIcon } from "lucide-react";+import { Avatar, AvatarImage } from "@/src/components/ui/avatar";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";++type BatchActionRow = {+ id: string;+ actionType: string;+ tableName: string;+ status: string;+ totalCount: number | null;+ processedCount: number | null;+ failedCount: number | null;+ createdAt: Date;+ finishedAt: Date | null;+ log: string | null;+ user: {+ name: string | null;+ image: string | null;+ } | null;+};++export function BatchActionsTable(props: { projectId: string }) {+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 10),+ });++ const batchActions = api.batchAction.all.useQuery({+ projectId: props.projectId,+ limit: paginationState.pageSize,+ page: paginationState.pageIndex,+ });++ const columns: LangfuseColumnDef<BatchActionRow>[] = [+ {+ accessorKey: "actionType",+ id: "actionType",+ header: "Action Type",+ size: 200,+ cell: ({ row }) => {+ const actionType = row.getValue("actionType") as string;+ const formattedType = actionType+ .split("-")+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(" ");+ return <span>{formattedType}</span>;+ },+ },+ {+ accessorKey: "tableName",+ id: "tableName",+ header: "Table",+ size: 120,+ cell: ({ row }) => {+ const tableName = row.getValue("tableName") as string;+ return <span className="capitalize">{tableName}</span>;+ },+ },+ {+ accessorKey: "status",+ id: "status",+ header: "Status",+ size: 110,+ cell: ({ row }) => {+ const status = row.getValue("status") as string;+ return (+ <StatusBadge type={status.toLowerCase()} className="capitalize" />+ );+ },+ },+ {+ accessorKey: "progress",+ id: "progress",+ header: "Progress",+ size: 150,+ cell: ({ row }) => {+ const totalCount = row.original.totalCount;+ const processedCount = row.original.processedCount ?? 0;+ const failedCount = row.original.failedCount ?? 0;++ if (!totalCount)+ return <span className="text-muted-foreground">-</span>;++ return (+ <div className="space-y-1">+ <div className="text-sm">+ {processedCount} / {totalCount}+ </div>+ {failedCount > 0 && (+ <div className="text-xs text-destructive">+ {failedCount} failed+ </div>+ )}+ </div>+ );+ },+ },+ {+ accessorKey: "createdAt",+ id: "createdAt",+ header: "Created",+ size: 150,+ cell: ({ row }) => {+ const createdAt = row.getValue("createdAt") as Date;+ return <LocalIsoDate date={createdAt} />;+ },+ },+ {+ accessorKey: "finishedAt",+ id: "finishedAt",+ header: "Finished",+ size: 150,+ cell: ({ row }) => {+ const finishedAt = row.getValue("finishedAt") as Date | null;+ return finishedAt ? (+ <LocalIsoDate date={finishedAt} />+ ) : (+ <span className="text-muted-foreground">-</span>+ );+ },+ },+ {+ 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("log") as string | null;+ return log ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger>+ <div className="flex items-center gap-1">+ <InfoIcon className="h-3 w-3 text-muted-foreground" />+ <span className="max-w-[250px] truncate text-xs">{log}</span>+ </div>+ </TooltipTrigger>+ <TooltipContent className="max-w-md">+ <pre className="max-h-60 overflow-auto whitespace-pre-wrap text-xs">+ {log}+ </pre>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : null;+ },+ },+ ];++ return (+ <DataTable+ tableName={"batchActions"}+ columns={columns}+ data={+ batchActions.isPending+ ? { isLoading: true, isError: false }+ : batchActions.isError+ ? {+ isLoading: false,+ isError: true,+ error: batchActions.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: safeExtract(batchActions.data, "batchActions", []),+ }+ }+ pagination={{+ totalCount: batchActions.data?.totalCount ?? 0,+ onChange: setPaginationState,+ state: paginationState,+ }}+ />+ );+}diff --git a/web/src/features/batch-actions/server/addToDatasetRouter.ts b/web/src/features/batch-actions/server/addToDatasetRouter.tsnew file mode 100644index 0000000000..9ca7801eb7--- /dev/null+++ b/web/src/features/batch-actions/server/addToDatasetRouter.ts@@ -0,0 +1,122 @@+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 {+ BatchActionQueue,+ logger,+ QueueJobs,+ getObservationsCountFromEventsTable,+ getObservationsTableCount,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import {+ BatchTableNames,+ BatchActionType,+ BatchActionStatus,+ ActionId,+} from "@langfuse/shared";+import { env } from "@/src/env.mjs";+import { CreateObservationAddToDatasetActionSchema } from "../validation";++const MAX_BATCH_ADD_TO_DATASET_ITEMS = 1000;++export const addToDatasetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateObservationAddToDatasetActionSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ // Check permissions+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "datasets:CUD",+ });++ const { projectId, query, config } = input;++ // Check observation count doesn't exceed maximum+ const queryOpts = {+ projectId,+ filter: query.filter ?? [],+ limit: 1,+ offset: 0,+ };+ const observationCount =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? await getObservationsCountFromEventsTable(queryOpts)+ : await getObservationsTableCount(queryOpts);++ if (observationCount > MAX_BATCH_ADD_TO_DATASET_ITEMS) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Too many observations selected. Maximum allowed is ${MAX_BATCH_ADD_TO_DATASET_ITEMS}, but ${observationCount} observations match your filters. Please refine your filters to reduce the count.`,+ });+ }+ const userId = ctx.session.user.id;++ logger.info("[TRPC] Creating observation-add-to-dataset action", {+ projectId,+ });++ // Create table batch action record+ const batchAction = await ctx.prisma.batchAction.create({+ data: {+ projectId,+ userId,+ actionType: ActionId.ObservationAddToDataset,+ tableName: BatchTableNames.Observations,+ status: BatchActionStatus.Queued,+ query,+ config,+ },+ });++ // Create audit log+ await auditLog({+ session: ctx.session,+ resourceType: "batchAction",+ resourceId: batchAction.id,+ projectId,+ action: "create",+ after: batchAction,+ });++ // Queue the job+ await BatchActionQueue.getInstance()?.add(+ QueueJobs.BatchActionProcessingJob,+ {+ id: batchAction.id,+ name: QueueJobs.BatchActionProcessingJob,+ timestamp: new Date(),+ payload: {+ batchActionId: batchAction.id,+ projectId,+ actionId: ActionId.ObservationAddToDataset,+ tableName: BatchTableNames.Observations,+ cutoffCreatedAt: new Date(),+ query,+ config,+ type: BatchActionType.Create,+ },+ },+ {+ jobId: batchAction.id,+ },+ );++ return { id: batchAction.id };+ } catch (e) {+ logger.error(e);+ if (e instanceof TRPCError) {+ throw e;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Creating add-to-dataset action failed.",+ });+ }+ }),+});diff --git a/web/src/features/batch-actions/server/batchActionRouter.ts b/web/src/features/batch-actions/server/batchActionRouter.tsnew file mode 100644index 0000000000..b04a81356b--- /dev/null+++ b/web/src/features/batch-actions/server/batchActionRouter.ts@@ -0,0 +1,121 @@+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { paginationZod } from "@langfuse/shared";+import { TRPCError } from "@trpc/server";+import { z } from "zod/v4";+import { GetBatchActionByIdSchema } from "../validation";+import { addToDatasetRouter } from "./addToDatasetRouter";++export const batchActionRouter = createTRPCRouter({+ addToDataset: addToDatasetRouter,+ byId: protectedProjectProcedure+ .input(GetBatchActionByIdSchema)+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "datasets:CUD",+ });++ const batchAction = await ctx.prisma.batchAction.findUnique({+ where: {+ id: input.batchActionId,+ projectId: input.projectId,+ },+ select: {+ id: true,+ status: true,+ totalCount: true,+ processedCount: true,+ failedCount: true,+ log: true,+ createdAt: true,+ finishedAt: true,+ actionType: true,+ tableName: true,+ config: true,+ },+ });++ if (!batchAction) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Batch action not found",+ });+ }++ return batchAction;+ }),++ all: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ ...paginationZod,+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "datasets:CUD",+ });++ const [batchActions, totalCount] = await Promise.all([+ ctx.prisma.batchAction.findMany({+ where: {+ projectId: input.projectId,+ },+ take: input.limit,+ skip: input.page * input.limit,+ orderBy: {+ createdAt: "desc",+ },+ }),+ ctx.prisma.batchAction.count({+ where: {+ projectId: input.projectId,+ },+ }),+ ]);++ // Look up users for each action+ const userIds = [...new Set(batchActions.map((a) => a.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]));++ return {+ batchActions: batchActions.map((action) => ({+ ...action,+ user: userMap.get(action.userId) ?? null,+ })),+ totalCount,+ };+ }),+});diff --git a/web/src/features/batch-actions/validation.ts b/web/src/features/batch-actions/validation.tsnew file mode 100644index 0000000000..745e9d06cf--- /dev/null+++ b/web/src/features/batch-actions/validation.ts@@ -0,0 +1,31 @@+import z from "zod/v4";+import {+ AddToDatasetMappingSchema,+ ObservationAddToDatasetConfigSchema,+ BatchActionQuerySchema,+} from "@langfuse/shared";++export const CreateObservationAddToDatasetActionSchema = z.object({+ projectId: z.string(),+ query: BatchActionQuerySchema,+ config: ObservationAddToDatasetConfigSchema,+});++export const ValidateBatchAddToDatasetMappingSchema = z.object({+ projectId: z.string(),+ observationId: z.string(),+ traceId: z.string(),+ datasetId: z.string(),+ mapping: AddToDatasetMappingSchema,+});++export const GetBatchActionByIdSchema = z.object({+ projectId: z.string(),+ batchActionId: z.string(),+});++export const ListBatchActionsSchema = z.object({+ projectId: z.string(),+ page: z.number(),+ limit: z.number(),+});diff --git a/web/src/features/datasets/components/DatasetForm.tsx b/web/src/features/datasets/components/DatasetForm.tsxindex c9aca9d80a..e83224ca65 100644--- a/web/src/features/datasets/components/DatasetForm.tsx+++ b/web/src/features/datasets/components/DatasetForm.tsx@@ -12,7 +12,14 @@ import {FormMessage,} from "@/src/components/ui/form";import { api } from "@/src/utils/api";-import { useMemo, useState } from "react";+import {+ useMemo,+ useState,+ useEffect,+ useRef,+ forwardRef,+ useImperativeHandle,+} from "react";import { Input } from "@/src/components/ui/input";import { CodeMirrorEditor } from "@/src/components/editor";import {@@ -38,11 +45,25 @@ type ServerSideSchemaValidationErrors = {}>;}[];+// Ref interface for imperative form submission+export interface DatasetFormRef {+ submit: () => void;+}+interface BaseDatasetFormProps {mode: "create" | "update" | "delete";projectId: string;onFormSuccess?: () => void;+ onCreateDatasetSuccess?: (params: {+ id: string;+ name: string;+ inputSchema: unknown;+ expectedOutputSchema: unknown;+ }) => void;className?: string;+ redirectOnSuccess?: boolean;+ showFooter?: boolean;+ onValidationChange?: (isValid: boolean, isSubmitting: boolean) => void;}interface CreateDatasetFormProps extends BaseDatasetFormProps {@@ -112,316 +133,381 @@ const formSchema = z.object({expectedOutputSchema: jsonSchemaStringValidator,});-export const DatasetForm = (props: DatasetFormProps) => {- const [formError, setFormError] = useState<string | null>(null);- const [- serverSideSchemaValidationErrors,- setServerSideSchemaValidationErrors,- ] = useState<ServerSideSchemaValidationErrors | null>(null);- const capture = usePostHogClientCapture();- const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");-- const inputSchemaString =- props.mode === "update" && props.datasetInputSchema- ? JSON.stringify(props.datasetInputSchema, null, 2)- : "";- const expectedOutputSchemaString =- props.mode === "update" && props.datasetExpectedOutputSchema- ? JSON.stringify(props.datasetExpectedOutputSchema, null, 2)- : "";-- const form = useForm({- resolver: zodResolver(formSchema),- defaultValues:- props.mode === "update"- ? {- name: props.datasetName,- description: props.datasetDescription ?? "",- metadata: props.datasetMetadata- ? JSON.stringify(props.datasetMetadata, null, 2)- : "",- inputSchema: inputSchemaString,- expectedOutputSchema: expectedOutputSchemaString,- }- : {- name:- props.mode === "create" && props.folderPrefix- ? `${props.folderPrefix}/`+export const DatasetForm = forwardRef<DatasetFormRef, DatasetFormProps>(+ (props, ref) => {+ const [formError, setFormError] = useState<string | null>(null);+ const [+ serverSideSchemaValidationErrors,+ setServerSideSchemaValidationErrors,+ ] = useState<ServerSideSchemaValidationErrors | null>(null);+ const capture = usePostHogClientCapture();+ const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");++ const inputSchemaString =+ props.mode === "update" && props.datasetInputSchema+ ? JSON.stringify(props.datasetInputSchema, null, 2)+ : "";+ const expectedOutputSchemaString =+ props.mode === "update" && props.datasetExpectedOutputSchema+ ? JSON.stringify(props.datasetExpectedOutputSchema, null, 2)+ : "";++ const form = useForm({+ resolver: zodResolver(formSchema),+ defaultValues:+ props.mode === "update"+ ? {+ name: props.datasetName,+ description: props.datasetDescription ?? "",+ metadata: props.datasetMetadata+ ? JSON.stringify(props.datasetMetadata, null, 2): "",- description: "",- metadata: "",- inputSchema: "",- expectedOutputSchema: "",- },- });-- const utils = api.useUtils();- 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 },- {- enabled: props.mode === "create" || props.mode === "update",- },- );-- const allDatasetNames = useMemo(() => {- return allDatasets.data?.map((dataset) => ({ value: dataset.name })) ?? [];- }, [allDatasets.data]);-- useUniqueNameValidation({- currentName: form.watch("name"),- allNames: allDatasetNames,- form,- errorMessage: "Dataset name already exists.",- whitelistedName: props.mode === "update" ? props.datasetName : undefined,- });-- function onSubmit(values: z.infer<typeof formSchema>) {- // Parse schemas if they're not empty (tRPC expects objects for DatasetJSONSchema)- const inputSchema =- values.inputSchema === "" ? null : JSON.parse(values.inputSchema);- const expectedOutputSchema =- values.expectedOutputSchema === ""- ? null- : JSON.parse(values.expectedOutputSchema);-- const trimmedValues = {- name: values.name.trim(),- description: values.description !== "" ? values.description.trim() : null,- // Keep metadata as string - resolveMetadata in tRPC will parse it- metadata: values.metadata !== "" ? values.metadata : null,- inputSchema,- expectedOutputSchema,- };+ inputSchema: inputSchemaString,+ expectedOutputSchema: expectedOutputSchemaString,+ }+ : {+ name:+ props.mode === "create" && props.folderPrefix+ ? `${props.folderPrefix}/`+ : "",+ description: "",+ metadata: "",+ inputSchema: "",+ expectedOutputSchema: "",+ },+ });- if (props.mode === "create") {- capture("datasets:new_form_submit");- createMutation- .mutateAsync({- ...trimmedValues,- projectId: props.projectId,- })- .then((result) => {- if (result.success) {- // Success - navigate to dataset items- void utils.datasets.invalidate();- props.onFormSuccess?.();- form.reset();- router.push(- `/project/${props.projectId}/datasets/${result.dataset.id}/items`,- );- } else {- // Validation failed - show errors- setServerSideSchemaValidationErrors(result.validationErrors);- setFormError(null);+ const utils = api.useUtils();+ 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 },+ {+ enabled: props.mode === "create" || props.mode === "update",+ },+ );++ const allDatasetNames = useMemo(() => {+ return (+ allDatasets.data?.map((dataset) => ({ value: dataset.name })) ?? []+ );+ }, [allDatasets.data]);++ useUniqueNameValidation({+ currentName: form.watch("name"),+ allNames: allDatasetNames,+ form,+ errorMessage: "Dataset name already exists.",+ whitelistedName: props.mode === "update" ? props.datasetName : undefined,+ });++ // Track previous validation state to avoid redundant callbacks+ const prevValidationRef = useRef<{+ isValid: boolean;+ isSubmitting: boolean;+ } | null>(null);++ // Report validation state to parent (only when values actually change)+ const { onValidationChange, mode } = props;+ useEffect(() => {+ if (onValidationChange) {+ const isValid = form.formState.isValid && !form.formState.errors.name;+ const isSubmitting =+ (mode === "create" && createMutation.isPending) ||+ (mode === "update" && updateMutation.isPending) ||+ (mode === "delete" && deleteMutation.isPending);++ const prev = prevValidationRef.current;+ if (+ !prev ||+ prev.isValid !== isValid ||+ prev.isSubmitting !== isSubmitting+ ) {+ prevValidationRef.current = { isValid, isSubmitting };+ onValidationChange(isValid, isSubmitting);+ }+ }+ }, [+ form.formState.isValid,+ form.formState.errors.name,+ createMutation.isPending,+ updateMutation.isPending,+ deleteMutation.isPending,+ mode,+ onValidationChange,+ ]);++ // Expose submit method via ref for external triggering+ useImperativeHandle(+ ref,+ () => ({+ submit: () => {+ if (props.mode !== "delete") {+ form.handleSubmit(onSubmit)();}- })- .catch((error: Error) => {- // System error (not validation)- setFormError(error.message);- setServerSideSchemaValidationErrors(null);- console.error(error);- });- } else if (props.mode === "update") {- capture("datasets:update_form_submit");- updateMutation+ },+ }),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [props.mode],+ );++ function onSubmit(values: z.infer<typeof formSchema>) {+ // Parse schemas if they're not empty (tRPC expects objects for DatasetJSONSchema)+ const inputSchema =+ values.inputSchema === "" ? null : JSON.parse(values.inputSchema);+ const expectedOutputSchema =+ values.expectedOutputSchema === ""+ ? null+ : JSON.parse(values.expectedOutputSchema);++ const trimmedValues = {+ name: values.name.trim(),+ description:+ values.description !== "" ? values.description.trim() : null,+ // Keep metadata as string - resolveMetadata in tRPC will parse it+ metadata: values.metadata !== "" ? values.metadata : null,+ inputSchema,+ expectedOutputSchema,+ };++ if (props.mode === "create") {+ capture("datasets:new_form_submit");+ createMutation+ .mutateAsync({+ ...trimmedValues,+ projectId: props.projectId,+ })+ .then((result) => {+ if (result.success) {+ // Success - navigate to dataset items+ void utils.datasets.invalidate();+ props.onCreateDatasetSuccess?.(result.dataset);+ props.onFormSuccess?.();+ form.reset();+ if (props.redirectOnSuccess !== false) {+ router.push(+ `/project/${props.projectId}/datasets/${result.dataset.id}/items`,+ );+ }+ } else {+ // Validation failed - show errors+ setServerSideSchemaValidationErrors(result.validationErrors);+ setFormError(null);+ }+ })+ .catch((error: Error) => {+ // System error (not validation)+ setFormError(error.message);+ setServerSideSchemaValidationErrors(null);+ console.error(error);+ });+ } else if (props.mode === "update") {+ capture("datasets:update_form_submit");+ updateMutation+ .mutateAsync({+ ...trimmedValues,+ projectId: props.projectId,+ datasetId: props.datasetId,+ })+ .then((result) => {+ if (result.success) {+ // Success - close dialog+ void utils.datasets.invalidate();+ props.onFormSuccess?.();+ form.reset();+ } else {+ // Validation failed - show errors+ setServerSideSchemaValidationErrors(result.validationErrors);+ setFormError(null);+ }+ })+ .catch((error: Error) => {+ // System error (not validation)+ setFormError(error.message);+ setServerSideSchemaValidationErrors(null);+ console.error(error);+ });+ }+ }++ const handleDelete = (e: React.FormEvent) => {+ 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({- ...trimmedValues,projectId: props.projectId,datasetId: props.datasetId,})- .then((result) => {- if (result.success) {- // Success - close dialog- void utils.datasets.invalidate();- props.onFormSuccess?.();- form.reset();- } else {- // Validation failed - show errors- setServerSideSchemaValidationErrors(result.validationErrors);- setFormError(null);- }+ .then(() => {+ void utils.datasets.invalidate();+ form.reset();}).catch((error: Error) => {- // System error (not validation)setFormError(error.message);- setServerSideSchemaValidationErrors(null);console.error(error);});- }- }-- const handleDelete = (e: React.FormEvent) => {- 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;- }+ return (+ <Form {...form}>+ <form+ onSubmit={+ props.mode === "delete" ? handleDelete : form.handleSubmit(onSubmit)+ }+ className="flex h-full min-h-0 flex-col"+ >+ <DialogBody+ className={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);+ }}+ minHeight="none"+ />+ </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}+ />+ )}+ />- capture("datasets:delete_form_submit");- deleteMutation- .mutateAsync({- projectId: props.projectId,- datasetId: props.datasetId,- })- .then(() => {- void utils.datasets.invalidate();- props.onFormSuccess?.();- form.reset();- })- .catch((error: Error) => {- setFormError(error.message);- console.error(error);- });- };-- return (- <Form {...form}>- <form- onSubmit={- props.mode === "delete" ? handleDelete : form.handleSubmit(onSubmit)- }- className="flex h-full min-h-0 flex-col"- >- <DialogBody>- {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);- }}- minHeight="none"- />- </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}/>)}- />-- {/* Show validation errors inline with form */}- {serverSideSchemaValidationErrors && (- <DatasetSchemaValidationError- projectId={props.projectId}- datasetId={- props.mode === "update" ? props.datasetId : "unknown"+ </div>+ )}+ </DialogBody>+ {props.showFooter !== false && (+ <DialogFooter>+ <div className="flex w-full flex-col gap-4">+ <Button+ type="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)}- errors={serverSideSchemaValidationErrors}- />- )}- </div>+ className="w-full"+ >+ {props.mode === "create"+ ? "Create dataset"+ : props.mode === "delete"+ ? "Delete Dataset"+ : "Update dataset"}+ </Button>+ {formError && (+ <p className="mt-4 text-center text-sm text-red-500">+ <span className="font-bold">Error:</span> {formError}+ </p>+ )}+ </div>+ </DialogFooter>)}- </DialogBody>- <DialogFooter>- <div className="flex w-full flex-col gap-4">- <Button- type="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)- }- className="w-full"- >- {props.mode === "create"- ? "Create dataset"- : props.mode === "delete"- ? "Delete Dataset"- : "Update dataset"}- </Button>- {formError && (- <p className="mt-4 text-center text-sm text-red-500">- <span className="font-bold">Error:</span> {formError}- </p>- )}- </div>- </DialogFooter>- </form>- </Form>- );-};+ </form>+ </Form>+ );+ },+);++DatasetForm.displayName = "DatasetForm";diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 23094f8565..bed5c7f295 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -22,6 +22,7 @@ import {type ObservationType,TableViewPresetTableName,BatchActionType,+ ActionId,} from "@langfuse/shared";import { cn } from "@/src/utils/tailwind";import { LevelColors } from "@/src/components/level-colors";@@ -285,7 +286,7 @@ export default function ObservationsEventsTable({const tableActions: TableAction[] = [{- id: "observation-add-to-annotation-queue",+ id: ActionId.ObservationAddToAnnotationQueue,type: BatchActionType.Create,label: "Add to Annotation Queue",description: "Add selected observations to an annotation queue.",diff --git a/web/src/features/table/components/TableActionDialog.tsx b/web/src/features/table/components/TableActionDialog.tsxindex 16fb0d58f2..0d2557355e 100644--- a/web/src/features/table/components/TableActionDialog.tsx+++ b/web/src/features/table/components/TableActionDialog.tsx@@ -66,7 +66,12 @@ export function TableActionDialog({);const handleConfirm = async () => {- await action.execute({ projectId, targetId: form.getValues().targetId });+ if ("execute" in action) {+ await action.execute({+ projectId,+ targetId: form.getValues().targetId,+ });+ }setSelectAll(false);onClose();};diff --git a/web/src/features/table/components/TableActionMenu.tsx b/web/src/features/table/components/TableActionMenu.tsxindex 412df08fd0..58d8346fd5 100644--- a/web/src/features/table/components/TableActionMenu.tsx+++ b/web/src/features/table/components/TableActionMenu.tsx@@ -8,7 +8,10 @@ import {import { Button } from "@/src/components/ui/button";import { ChevronDown, Trash } from "lucide-react";import { Plus } from "lucide-react";-import { type TableAction } from "@/src/features/table/types";+import {+ type TableAction,+ type CustomDialogTableAction,+} from "@/src/features/table/types";import { TableActionDialog } from "@/src/features/table/components/TableActionDialog";import { type BatchExportTableName } from "@langfuse/shared";@@ -16,6 +19,7 @@ type TableActionMenuProps = {projectId: string;actions: TableAction[];tableName: BatchExportTableName;+ onCustomAction?: (actionType: CustomDialogTableAction["id"]) => void;};const getDefaultIcon = (type: TableAction["type"]) => {@@ -29,6 +33,7 @@ export function TableActionMenu({projectId,actions,tableName,+ onCustomAction,}: TableActionMenuProps) {const [selectedAction, setSelectedAction] = useState<TableAction | null>(null,@@ -36,6 +41,10 @@ export function TableActionMenu({const [isDialogOpen, setDialogOpen] = useState(false);const handleActionSelect = (action: TableAction) => {+ if ("customDialog" in action && action.customDialog) {+ onCustomAction?.(action.id);+ return;+ }setSelectedAction(action);setDialogOpen(true);};diff --git a/web/src/features/table/server/createBatchActionJob.ts b/web/src/features/table/server/createBatchActionJob.tsindex 0f2c236e1c..eae7fe381c 100644--- a/web/src/features/table/server/createBatchActionJob.ts+++ b/web/src/features/table/server/createBatchActionJob.ts@@ -16,7 +16,7 @@ import { TRPCError } from "@trpc/server";type CreateBatchActionJob = {projectId: string;- actionId: ActionId;+ actionId: Exclude<ActionId, "observation-add-to-dataset">;tableName: BatchExportTableName;actionType: BatchActionType;session: {diff --git a/web/src/features/table/types.ts b/web/src/features/table/types.tsindex 3e02f21710..d9e390e707 100644--- a/web/src/features/table/types.ts+++ b/web/src/features/table/types.ts@@ -31,4 +31,13 @@ type DeleteTableAction = BaseTableAction & {execute: ({ projectId }: { projectId: string }) => Promise<void>;};-export type TableAction = CreateTableAction | DeleteTableAction;+export type CustomDialogTableAction = BaseTableAction & {+ type: BatchActionType.Create;+ customDialog: true;+ // No execute or targetLabel - dialog handles everything+};++export type TableAction =+ | CreateTableAction+ | DeleteTableAction+ | CustomDialogTableAction;diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxindex 6d9ee21dae..eaf33f0f54 100644--- a/web/src/pages/project/[projectId]/settings/index.tsx+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -21,6 +21,7 @@ import { 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";+import { BatchActionsSettingsPage } from "@/src/features/batch-actions/components/BatchActionsSettingsPage";import { AuditLogsSettingsPage } from "@/src/ee/features/audit-log-viewer/AuditLogsSettingsPage";import { ModelsSettings } from "@/src/features/models/components/ModelSettings";import ConfigureRetention from "@/src/features/projects/components/ConfigureRetention";@@ -208,6 +209,12 @@ export const getProjectSettingsPages = ({cmdKKeywords: ["csv", "download", "json", "batch"],content: <BatchExportsSettingsPage projectId={project.id} />,},+ {+ title: "Batch Actions",+ slug: "batch-actions",+ cmdKKeywords: ["bulk", "batch", "action", "dataset", "delete"],+ content: <BatchActionsSettingsPage projectId={project.id} />,+ },{title: "Audit Logs",slug: "audit-logs",diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 01e6d801c2..120145b6ae 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -41,6 +41,7 @@ import { mediaRouter } from "@/src/server/api/routers/media";import { backgroundMigrationsRouter } from "@/src/features/background-migrations/server/background-migrations-router";import { auditLogsRouter } from "./routers/auditLogs";import { tableRouter } from "@/src/features/table/server/tableRouter";+import { batchActionRouter } from "@/src/features/batch-actions/server/batchActionRouter";import { cloudStatusRouter } from "@/src/features/cloud-status-notification/server/cloud-status-router";import { dashboardWidgetRouter } from "./routers/dashboardWidgets";import { TableViewPresetsRouter } from "@/src/server/api/routers/tableViewPresets";@@ -103,6 +104,7 @@ export const appRouter = createTRPCRouter({backgroundMigrations: backgroundMigrationsRouter,auditLogs: auditLogsRouter,table: tableRouter,+ batchAction: batchActionRouter,cloudStatus: cloudStatusRouter,dashboardWidgets: dashboardWidgetRouter,TableViewPresets: TableViewPresetsRouter,diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex cb36e5f3c6..b846db6198 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -22,6 +22,7 @@ import {InternalServerError,BatchActionQuerySchema,BatchActionType,+ ActionId,BatchExportTableName,type ScoreDomain,CreateAnnotationScoreData,@@ -251,7 +252,7 @@ export const scoresRouter = createTRPCRouter({if (input.isBatchAction && input.query) {return createBatchActionJob({projectId: input.projectId,- actionId: "score-delete",+ actionId: ActionId.ScoreDelete,actionType: BatchActionType.Delete,tableName: BatchExportTableName.Scores,session: ctx.session,diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 5cb3a15d55..f10ffed9c3 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -12,6 +12,7 @@ import {BatchActionQuerySchema,BatchExportTableName,BatchActionType,+ ActionId,filterAndValidateDbScoreList,orderBy,paginationZod,@@ -415,7 +416,7 @@ export const traceRouter = createTRPCRouter({if (input.isBatchAction && input.query) {await createBatchActionJob({projectId: input.projectId,- actionId: "trace-delete",+ actionId: ActionId.TraceDelete,actionType: BatchActionType.Delete,tableName: BatchExportTableName.Traces,session: ctx.session,diff --git a/worker/src/__tests__/applyFieldMapping.test.ts b/worker/src/__tests__/applyFieldMapping.test.tsnew file mode 100644index 0000000000..77a01ee7ca--- /dev/null+++ b/worker/src/__tests__/applyFieldMapping.test.ts@@ -0,0 +1,876 @@+import { describe, it, expect } from "vitest";+import {+ applyFieldMappingConfig,+ applyFullMapping,+ evaluateJsonPath,+ isJsonPath,+ testJsonPath,+ generateJsonPathSuggestions,+} from "@langfuse/shared";++describe("applyFieldMapping", () => {+ // Sample observation data for testing+ const sampleObservation = {+ input: {+ messages: [+ { role: "system", content: "You are a helpful assistant" },+ { role: "user", content: "What is 2+2?" },+ ],+ model: "gpt-4",+ temperature: 0.7,+ },+ output: {+ choices: [{ message: { role: "assistant", content: "4" } }],+ usage: { total_tokens: 50 },+ },+ metadata: {+ user_id: "user-123",+ session_id: "session-456",+ tags: ["math", "simple"],+ },+ };++ describe("isJsonPath", () => {+ it("should return true for strings starting with $", () => {+ expect(isJsonPath("$")).toBe(true);+ expect(isJsonPath("$.field")).toBe(true);+ expect(isJsonPath("$.nested.path")).toBe(true);+ expect(isJsonPath("$[0]")).toBe(true);+ });++ it("should return false for strings not starting with $", () => {+ expect(isJsonPath("field")).toBe(false);+ expect(isJsonPath("")).toBe(false);+ expect(isJsonPath("literal value")).toBe(false);+ expect(isJsonPath(" $")).toBe(false);+ });+ });++ describe("testJsonPath", () => {+ it("should return success for valid JSON paths", () => {+ const result = testJsonPath({+ jsonPath: "$.messages[0].content",+ data: sampleObservation.input,+ });+ expect(result.success).toBe(true);+ expect(result.error).toBeUndefined();+ });++ it("should return success for root path", () => {+ const result = testJsonPath({+ jsonPath: "$",+ data: sampleObservation.input,+ });+ expect(result.success).toBe(true);+ });++ it("should handle string data (auto-parse JSON)", () => {+ const result = testJsonPath({+ jsonPath: "$.key",+ data: '{"key": "value"}',+ });+ expect(result.success).toBe(true);+ });+ });++ describe("evaluateJsonPath", () => {+ it("should extract nested values using JSON path", () => {+ expect(+ evaluateJsonPath(sampleObservation.input, "$.messages[0].content"),+ ).toBe("You are a helpful assistant");++ expect(+ evaluateJsonPath(sampleObservation.input, "$.messages[1].content"),+ ).toBe("What is 2+2?");+ });++ it("should return the root object for $ path", () => {+ const result = evaluateJsonPath(sampleObservation.input, "$");+ expect(result).toEqual(sampleObservation.input);+ });++ it("should extract simple fields", () => {+ expect(evaluateJsonPath(sampleObservation.input, "$.model")).toBe(+ "gpt-4",+ );+ expect(evaluateJsonPath(sampleObservation.input, "$.temperature")).toBe(+ 0.7,+ );+ });++ it("should return undefined for non-existent paths", () => {+ expect(+ evaluateJsonPath(sampleObservation.input, "$.nonExistent"),+ ).toBeUndefined();+ expect(+ evaluateJsonPath(sampleObservation.input, "$.messages[99]"),+ ).toBeUndefined();+ });++ it("should handle string data (auto-parse JSON)", () => {+ const jsonString = '{"nested": {"value": 42}}';+ expect(evaluateJsonPath(jsonString, "$.nested.value")).toBe(42);+ });++ it("should return undefined for invalid JSON paths gracefully", () => {+ expect(+ evaluateJsonPath(sampleObservation.input, "invalid"),+ ).toBeUndefined();+ });++ it("should extract array elements", () => {+ expect(evaluateJsonPath(sampleObservation.metadata, "$.tags[0]")).toBe(+ "math",+ );+ expect(evaluateJsonPath(sampleObservation.metadata, "$.tags[1]")).toBe(+ "simple",+ );+ });+ });++ describe("applyFieldMappingConfig - full mode", () => {+ it("should return full source field for 'full' mode", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: { mode: "full" },+ defaultSourceField: "input",+ });++ expect(result).toEqual(sampleObservation.input);+ });++ it("should return full output for 'full' mode with output as default", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: { mode: "full" },+ defaultSourceField: "output",+ });++ expect(result).toEqual(sampleObservation.output);+ });++ it("should return full metadata for 'full' mode with metadata as default", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: { mode: "full" },+ defaultSourceField: "metadata",+ });++ expect(result).toEqual(sampleObservation.metadata);+ });+ });++ describe("applyFieldMappingConfig - none mode", () => {+ it("should return null for 'none' mode", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: { mode: "none" },+ defaultSourceField: "input",+ });++ expect(result).toBeNull();+ });+ });++ describe("applyFieldMappingConfig - custom root mode", () => {+ it("should extract value using JSON path in root mode", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "input",+ jsonPath: "$.messages[1].content",+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toBe("What is 2+2?");+ });++ it("should allow extracting from different source field", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "output",+ jsonPath: "$.choices[0].message.content",+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toBe("4");+ });++ it("should return undefined for non-existent path", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "input",+ jsonPath: "$.nonExistent.path",+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toBeUndefined();+ });++ it("should fallback to default source field if no custom config", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "root",+ },+ },+ defaultSourceField: "metadata",+ });++ expect(result).toEqual(sampleObservation.metadata);+ });+ });++ describe("applyFieldMappingConfig - custom keyValueMap mode (flat keys)", () => {+ it("should build object from key-value entries with JSON paths", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "response",+ sourceField: "output",+ value: "$.choices[0].message.content",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ prompt: "What is 2+2?",+ response: "4",+ });+ });++ it("should handle literal string values (not starting with $)", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "type",+ sourceField: "input",+ value: "conversation",+ },+ {+ id: "2",+ key: "version",+ sourceField: "input",+ value: "1.0",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ type: "conversation",+ version: "1.0",+ });+ });++ it("should mix JSON paths and literal values", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "category",+ sourceField: "input",+ value: "math",+ },+ {+ id: "3",+ key: "user",+ sourceField: "metadata",+ value: "$.user_id",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ prompt: "What is 2+2?",+ category: "math",+ user: "user-123",+ });+ });+ });++ describe("applyFieldMappingConfig - custom keyValueMap mode (dot notation / nested keys)", () => {+ it("should build nested objects using dot notation keys", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "context.user_id",+ sourceField: "metadata",+ value: "$.user_id",+ },+ {+ id: "2",+ key: "context.session_id",+ sourceField: "metadata",+ value: "$.session_id",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ context: {+ user_id: "user-123",+ session_id: "session-456",+ },+ });+ });++ it("should handle deeply nested dot notation", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "a.b.c.d",+ sourceField: "input",+ value: "$.model",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ a: {+ b: {+ c: {+ d: "gpt-4",+ },+ },+ },+ });+ });++ it("should merge multiple nested paths under the same parent", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "context.user_id",+ sourceField: "metadata",+ value: "$.user_id",+ },+ {+ id: "3",+ key: "context.session_id",+ sourceField: "metadata",+ value: "$.session_id",+ },+ {+ id: "4",+ key: "model_info.name",+ sourceField: "input",+ value: "$.model",+ },+ {+ id: "5",+ key: "model_info.temperature",+ sourceField: "input",+ value: "$.temperature",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ prompt: "What is 2+2?",+ context: {+ user_id: "user-123",+ session_id: "session-456",+ },+ model_info: {+ name: "gpt-4",+ temperature: 0.7,+ },+ });+ });++ it("should handle mix of flat and nested keys", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "context.user",+ sourceField: "metadata",+ value: "$.user_id",+ },+ {+ id: "3",+ key: "version",+ sourceField: "input",+ value: "1.0",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ prompt: "What is 2+2?",+ context: {+ user: "user-123",+ },+ version: "1.0",+ });+ });++ it("should handle literal values with dot notation keys", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "settings.theme",+ sourceField: "input",+ value: "dark",+ },+ {+ id: "2",+ key: "settings.language",+ sourceField: "input",+ value: "en",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ settings: {+ theme: "dark",+ language: "en",+ },+ });+ });++ it("should skip entries with empty/falsy values except empty string", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "empty_string",+ sourceField: "input",+ value: "", // Empty string should be included+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ prompt: "What is 2+2?",+ empty_string: "",+ });+ });++ it("should overwrite parent if nested key comes after flat key with same prefix", () => {+ // This tests the edge case where a flat key is set first, then a nested key tries to use it+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "context",+ sourceField: "input",+ value: "some-value",+ },+ {+ id: "2",+ key: "context.nested",+ sourceField: "input",+ value: "nested-value",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ // The nested key should overwrite the flat value+ expect(result).toEqual({+ context: {+ nested: "nested-value",+ },+ });+ });+ });++ describe("applyFullMapping", () => {+ it("should apply mapping to all three fields", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ ],+ },+ },+ },+ expectedOutput: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "output",+ jsonPath: "$.choices[0].message.content",+ },+ },+ },+ metadata: { mode: "none" },+ },+ });++ expect(result).toEqual({+ input: { prompt: "What is 2+2?" },+ expectedOutput: "4",+ metadata: null,+ });+ });++ it("should apply full mode for all fields", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: { mode: "full" },+ expectedOutput: { mode: "full" },+ metadata: { mode: "full" },+ },+ });++ expect(result).toEqual({+ input: sampleObservation.input,+ expectedOutput: sampleObservation.output,+ metadata: sampleObservation.metadata,+ });+ });++ it("should handle schema-compliant mapping with nested keys", () => {+ // Simulates mapping for a schema like:+ // { prompt: string, context: { user_id: string, session_id: string } }+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "context.user_id",+ sourceField: "metadata",+ value: "$.user_id",+ },+ {+ id: "3",+ key: "context.session_id",+ sourceField: "metadata",+ value: "$.session_id",+ },+ ],+ },+ },+ },+ expectedOutput: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "output",+ jsonPath: "$.choices[0].message.content",+ },+ },+ },+ metadata: { mode: "none" },+ },+ });++ expect(result).toEqual({+ input: {+ prompt: "What is 2+2?",+ context: {+ user_id: "user-123",+ session_id: "session-456",+ },+ },+ expectedOutput: "4",+ metadata: null,+ });+ });+ });++ describe("generateJsonPathSuggestions", () => {+ it("should generate suggestions for object properties", () => {+ const suggestions = generateJsonPathSuggestions({ a: 1, b: 2 });+ expect(suggestions).toContain("$.a");+ expect(suggestions).toContain("$.b");+ });++ it("should generate suggestions for nested objects", () => {+ const suggestions = generateJsonPathSuggestions({+ nested: { child: "value" },+ });+ expect(suggestions).toContain("$.nested");+ expect(suggestions).toContain("$.nested.child");+ });++ it("should generate suggestions for arrays", () => {+ const suggestions = generateJsonPathSuggestions({+ items: [{ name: "first" }],+ });+ expect(suggestions).toContain("$.items");+ expect(suggestions).toContain("$.items[0]");+ expect(suggestions).toContain("$.items[*]");+ expect(suggestions).toContain("$.items[0].name");+ });++ it("should return empty array for null/undefined", () => {+ expect(generateJsonPathSuggestions(null)).toEqual([]);+ expect(generateJsonPathSuggestions(undefined)).toEqual([]);+ });++ it("should handle complex nested structure", () => {+ const suggestions = generateJsonPathSuggestions(sampleObservation.input);+ expect(suggestions).toContain("$.messages");+ expect(suggestions).toContain("$.messages[0]");+ expect(suggestions).toContain("$.messages[0].role");+ expect(suggestions).toContain("$.messages[0].content");+ expect(suggestions).toContain("$.model");+ expect(suggestions).toContain("$.temperature");+ });+ });++ describe("edge cases", () => {+ it("should handle null observation fields", () => {+ const obsWithNull = {+ input: null,+ output: { value: "test" },+ metadata: null,+ };++ const result = applyFieldMappingConfig({+ observation: obsWithNull,+ config: { mode: "full" },+ defaultSourceField: "input",+ });++ expect(result).toBeNull();+ });++ it("should handle undefined paths gracefully", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "nonexistent",+ sourceField: "input",+ value: "$.does.not.exist",+ },+ ],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual({+ nonexistent: undefined,+ });+ });++ it("should handle empty entries array by returning default source", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [],+ },+ },+ },+ defaultSourceField: "input",+ });++ expect(result).toEqual(sampleObservation.input);+ });++ it("should handle no custom config by returning default source", () => {+ const result = applyFieldMappingConfig({+ observation: sampleObservation,+ config: {+ mode: "custom",+ },+ defaultSourceField: "metadata",+ });++ expect(result).toEqual(sampleObservation.metadata);+ });+ });+});diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex ef3f94b47e..5984c30ba1 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -29,6 +29,8 @@ import { prisma } from "@langfuse/shared/src/db";import { randomUUID } from "node:crypto";import { processClickhouseScoreDelete } from "../scores/processClickhouseScoreDelete";import { getObservationStream } from "../database-read-stream/observation-stream";+import { processAddObservationsToDataset } from "./processAddObservationsToDataset";+import { ObservationAddToDatasetConfigSchema } from "@langfuse/shared";const CHUNK_SIZE = 1000;const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {@@ -312,6 +314,50 @@ export const handleBatchActionJob = async (logger.info(`Batch action job completed, projectId: ${batchActionJob.payload.projectId}, ${count} elements`,);+ } else if (actionId === "observation-add-to-dataset") {+ const { projectId, query, cutoffCreatedAt, config, batchActionId } =+ batchActionEvent;++ // Parse and validate config+ const parsedConfig = ObservationAddToDatasetConfigSchema.parse(config);++ // Get observation stream+ const dbReadStream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ searchQuery: query.searchQuery ?? undefined,+ searchType: query.searchType ?? ["id" as const],+ });++ // Collect all observations+ const observations: Array<{+ id: string;+ traceId: string;+ input: unknown;+ output: unknown;+ metadata: unknown;+ }> = [];++ for await (const record of dbReadStream) {+ if (record?.id) {+ observations.push({+ id: record.id,+ traceId: record.traceId,+ input: record.input,+ output: record.output,+ metadata: record.metadata,+ });+ }+ }++ // Process observations and add to dataset+ await processAddObservationsToDataset({+ projectId,+ batchActionId: batchActionId as string,+ config: parsedConfig,+ observations,+ });}logger.info(diff --git a/worker/src/features/batchAction/processAddObservationsToDataset.ts b/worker/src/features/batchAction/processAddObservationsToDataset.tsnew file mode 100644index 0000000000..ffab8c4de4--- /dev/null+++ b/worker/src/features/batchAction/processAddObservationsToDataset.ts@@ -0,0 +1,180 @@+import { logger, traceException } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { createManyDatasetItems } from "@langfuse/shared/src/server";+import {+ applyFullMapping,+ BatchActionStatus,+ type ObservationAddToDatasetConfig,+} from "@langfuse/shared";++// Chunk size for batch processing. Smaller than the default 1000 because:+// 1. Each observation requires JSON path evaluation and mapping transformation+// 2. Dataset item validation with schema checking is CPU-intensive+// 3. Smaller chunks provide more frequent progress updates to the UI+const CHUNK_SIZE = 100;++type ObservationForMapping = {+ id: string;+ traceId: string;+ input: unknown;+ output: unknown;+ metadata: unknown;+};++async function processChunk(params: {+ projectId: string;+ datasetId: string;+ mapping: ObservationAddToDatasetConfig["mapping"];+ observations: ObservationForMapping[];+}): Promise<{ processed: number; failed: number; errors: string[] }> {+ const { projectId, datasetId, mapping, observations } = params;++ const items = observations.map((obs) => {+ const mapped = applyFullMapping({+ observation: {+ input: obs.input,+ output: obs.output,+ metadata: obs.metadata,+ },+ mapping,+ });++ return {+ datasetId,+ input: mapped.input,+ expectedOutput: mapped.expectedOutput ?? undefined,+ metadata: mapped.metadata ?? undefined,+ sourceTraceId: obs.traceId,+ sourceObservationId: obs.id,+ };+ });++ try {+ const result = await createManyDatasetItems({+ projectId,+ items,+ normalizeOpts: { sanitizeControlChars: true },+ validateOpts: { normalizeUndefinedToNull: true },+ allowPartialSuccess: true, // Allow partial success for bulk operations+ });++ if (!result.success) {+ // All items failed+ return {+ processed: 0,+ failed: items.length,+ errors: result.validationErrors.map(+ (e) =>+ `Item ${e.itemIndex}: ${e.field} - ${e.errors.map((err) => err.message).join(", ")}`,+ ),+ };+ }++ // Success (possibly partial)+ const errors = result.validationErrors+ ? result.validationErrors.map(+ (e) =>+ `Item ${e.itemIndex}: ${e.field} - ${e.errors.map((err) => err.message).join(", ")}`,+ )+ : [];++ return {+ processed: result.successCount,+ failed: result.failedCount,+ errors,+ };+ } catch (error) {+ logger.error("Failed to create dataset items in chunk", error);+ traceException(error);+ return {+ processed: 0,+ failed: items.length,+ errors: [+ `Failed to create chunk: ${error instanceof Error ? error.message : "Unknown error"}`,+ ],+ };+ }+}++export async function processAddObservationsToDataset(params: {+ projectId: string;+ batchActionId: string;+ config: ObservationAddToDatasetConfig;+ observations: ObservationForMapping[];+}): Promise<void> {+ const { projectId, batchActionId, config, observations } = params;+ const { datasetId, mapping } = config;++ // Update status to PROCESSING+ await prisma.batchAction.update({+ where: { id: batchActionId },+ data: {+ status: BatchActionStatus.Processing,+ totalCount: observations.length,+ },+ });++ let processed = 0;+ let failed = 0;+ const allErrors: string[] = [];++ // Process in chunks+ for (let i = 0; i < observations.length; i += CHUNK_SIZE) {+ const chunk = observations.slice(i, i + CHUNK_SIZE);++ const result = await processChunk({+ projectId,+ datasetId,+ mapping,+ observations: chunk,+ });++ processed += result.processed;+ failed += result.failed;++ if (result.errors.length > 0) {+ // Limit error accumulation to prevent massive log strings+ allErrors.push(...result.errors.slice(0, 10));+ }++ // Update progress periodically (every 5 chunks or at the end)+ if (i % (CHUNK_SIZE * 5) === 0 || i + CHUNK_SIZE >= observations.length) {+ await prisma.batchAction.update({+ where: { id: batchActionId },+ data: { processedCount: processed, failedCount: failed },+ });+ }+ }++ // Determine final status+ const finalStatus =+ failed === 0+ ? BatchActionStatus.Completed+ : processed === 0+ ? BatchActionStatus.Failed+ : BatchActionStatus.Partial;++ // Aggregate error summary+ const errorSummary =+ allErrors.length > 0+ ? `${failed} items failed validation. Sample errors:\n${allErrors.slice(0, 20).join("\n")}`+ : null;++ // Update final status+ await prisma.batchAction.update({+ where: { id: batchActionId },+ data: {+ status: finalStatus,+ finishedAt: new Date(),+ processedCount: processed,+ failedCount: failed,+ log: errorSummary,+ },+ });++ logger.info(`Completed observation-add-to-dataset action ${batchActionId}`, {+ processed,+ failed,+ finalStatus,+ });+}