🪢 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: webhook for prompt version changes (#7012)
Max Deichmannb26362cbcabd
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonnew file mode 100644index 0000000000..4e032ebbb8--- /dev/null+++ b/.claude/settings.local.json@@ -0,0 +1,9 @@+{+ "permissions": {+ "allow": [+ "Bash(find:*)",+ "Bash(rg:*)"+ ],+ "deny": []+ }+}\ No newline at end of filediff --git a/.cursor/rules/global.mdc b/.cursor/rules/global.mdcnew file mode 100644index 0000000000..f236c4ba07--- /dev/null+++ b/.cursor/rules/global.mdc@@ -0,0 +1,20 @@+---+description:+globs:+alwaysApply: true+---+## Project setup+- This project is a Turborepo monorepo+- We build two containers, web (./web) and worker (./worker)+- We have shared code between these two in the shared package (./packages/shared). For that package, we have different entry points [package.json](mdc:packages/shared/package.json).+++## Domain layer+The most important domain objects are in [observations.ts](mdc:packages/shared/src/domain/observations.ts), [traces.ts](mdc:packages/shared/src/domain/traces.ts), [scores.ts](mdc:packages/shared/src/domain/scores.ts).+++## Database schema+We use Postgres and Clickhouse.+- The postgres schema is in [schema.prisma](mdc:packages/shared/prisma/schema.prisma)+- The clickhouse schema is in [0001_traces.up.sql](mdc:packages/shared/clickhouse/migrations/clustered/0001_traces.up.sql), [0002_observations.up.sql](mdc:packages/shared/clickhouse/migrations/clustered/0002_observations.up.sql), [0003_scores.up.sql](mdc:packages/shared/clickhouse/migrations/clustered/0003_scores.up.sql)+diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b78307e624..74774341db 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -149,8 +149,8 @@ Requirements- Username: `[email protected]`- Password: `password`-To get comprehensive example data, you can use the `seed` command:+```shpnpm run db:seed:examples```@@ -228,30 +228,36 @@ The `.env.test` file only overrides the set values and falls back on `.env` forTests automatically create the PostgreSQL test database if it doesn't exist and clean up data between runs.### Tests in the `web` package (public API)-We're using Jest with in the `web` package. Therefore, if you want to provide an argument to the test runner, do it directly without an intermittent ` -- `.++We're using Jest with in the `web` package. Therefore, if you want to provide an argument to the test runner, do it directly without an intermittent `--`.There are three types of unit tests:+- `test-sync`- `test-async`- `test-client`To run a specific test, for example the test: `"should handle special characters in prompt names"` in `prompts.v2.servertest.ts`, run:+```shcd web # or with --filter=webpnpm test-sync --testPathPattern="prompts\.v2\.servertest" --testNamePattern="should handle special characters in prompt names"```To run all tests:+```shpnpm run test```Run interactively in watch mode (not recommended!)+```shpnpm run test:watch```### Tests in the `worker` package+For the `worker` package, we're using `vitest` to run unit tests.```shdiff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 74ac09cb1f..73003895c5 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -115,6 +115,17 @@ export const DashboardWidgetChartType = {PIVOT_TABLE: "PIVOT_TABLE"} as const;export type DashboardWidgetChartType = (typeof DashboardWidgetChartType)[keyof typeof DashboardWidgetChartType];+export const ActionType = {+ WEBHOOK: "WEBHOOK"+} as const;+export type ActionType = (typeof ActionType)[keyof typeof ActionType];+export const ActionExecutionStatus = {+ COMPLETED: "COMPLETED",+ ERROR: "ERROR",+ PENDING: "PENDING",+ CANCELLED: "CANCELLED"+} as const;+export type ActionExecutionStatus = (typeof ActionExecutionStatus)[keyof typeof ActionExecutionStatus];export type Account = {id: string;user_id: string;@@ -133,6 +144,14 @@ export type Account = {refresh_token_expires_in: number | null;created_at: number | null;};+export type Action = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ type: ActionType;+ config: unknown;+};export type AnnotationQueue = {id: string;name: string;@@ -187,6 +206,30 @@ export type AuditLog = {before: string | null;after: string | null;};+export type Automation = {+ id: string;+ name: string;+ trigger_id: string;+ action_id: string;+ created_at: Generated<Timestamp>;+ project_id: string;+};+export type AutomationExecution = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ source_id: string;+ automation_id: string;+ trigger_id: string;+ action_id: string;+ project_id: string;+ status: Generated<ActionExecutionStatus>;+ input: unknown;+ output: unknown | null;+ started_at: Timestamp | null;+ finished_at: Timestamp | null;+ error: string | null;+};export type BackgroundMigration = {id: string;name: string;@@ -683,6 +726,16 @@ export type TraceSession = {public: Generated<boolean>;environment: Generated<string>;};+export type Trigger = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ eventSource: string;+ eventActions: string[];+ filter: unknown | null;+ status: Generated<JobConfigState>;+};export type User = {id: string;name: string | null;@@ -702,10 +755,13 @@ export type VerificationToken = {};export type DB = {Account: Account;+ actions: Action;annotation_queue_items: AnnotationQueueItem;annotation_queues: AnnotationQueue;api_keys: ApiKey;audit_logs: AuditLog;+ automation_executions: AutomationExecution;+ automations: Automation;background_migrations: BackgroundMigration;batch_exports: BatchExport;billing_meter_backups: BillingMeterBackup;@@ -747,6 +803,7 @@ export type DB = {trace_media: TraceMedia;trace_sessions: TraceSession;traces: LegacyPrismaTrace;+ triggers: Trigger;users: User;verification_tokens: VerificationToken;};diff --git a/packages/shared/prisma/migrations/20250704170658_add_automations/migration.sql b/packages/shared/prisma/migrations/20250704170658_add_automations/migration.sqlnew file mode 100644index 0000000000..7f39e55d95--- /dev/null+++ b/packages/shared/prisma/migrations/20250704170658_add_automations/migration.sql@@ -0,0 +1,111 @@+-- CreateEnum+CREATE TYPE "ActionType" AS ENUM ('WEBHOOK');++-- CreateEnum+CREATE TYPE "ActionExecutionStatus" AS ENUM ('COMPLETED', 'ERROR', 'PENDING', 'CANCELLED');++-- CreateTable+CREATE TABLE "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,+ "type" "ActionType" NOT NULL,+ "config" JSONB NOT NULL,++ CONSTRAINT "actions_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "triggers" (+ "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,+ "eventSource" TEXT NOT NULL,+ "eventActions" TEXT[],+ "filter" JSONB,+ "status" "JobConfigState" NOT NULL DEFAULT 'ACTIVE',++ CONSTRAINT "triggers_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "automations" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "trigger_id" TEXT NOT NULL,+ "action_id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,++ CONSTRAINT "automations_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "automation_executions" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "source_id" TEXT NOT NULL,+ "automation_id" TEXT NOT NULL,+ "trigger_id" TEXT NOT NULL,+ "action_id" TEXT NOT NULL,+ "project_id" TEXT NOT NULL,+ "status" "ActionExecutionStatus" NOT NULL DEFAULT 'PENDING',+ "input" JSONB NOT NULL,+ "output" JSONB,+ "started_at" TIMESTAMP(3),+ "finished_at" TIMESTAMP(3),+ "error" TEXT,++ CONSTRAINT "automation_executions_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "actions_project_id_idx" ON "actions"("project_id");++-- CreateIndex+CREATE INDEX "triggers_project_id_idx" ON "triggers"("project_id");++-- CreateIndex+CREATE INDEX "automations_project_id_action_id_trigger_id_idx" ON "automations"("project_id", "action_id", "trigger_id");++-- CreateIndex+CREATE INDEX "automations_project_id_name_idx" ON "automations"("project_id", "name");++-- CreateIndex+CREATE INDEX "automation_executions_trigger_id_idx" ON "automation_executions"("trigger_id");++-- CreateIndex+CREATE INDEX "automation_executions_action_id_idx" ON "automation_executions"("action_id");++-- CreateIndex+CREATE INDEX "automation_executions_project_id_idx" ON "automation_executions"("project_id");++-- AddForeignKey+ALTER TABLE "actions" ADD CONSTRAINT "actions_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "triggers" ADD CONSTRAINT "triggers_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automations" ADD CONSTRAINT "automations_trigger_id_fkey" FOREIGN KEY ("trigger_id") REFERENCES "triggers"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automations" ADD CONSTRAINT "automations_action_id_fkey" FOREIGN KEY ("action_id") REFERENCES "actions"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automations" ADD CONSTRAINT "automations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automation_executions" ADD CONSTRAINT "automation_executions_automation_id_fkey" FOREIGN KEY ("automation_id") REFERENCES "automations"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automation_executions" ADD CONSTRAINT "automation_executions_trigger_id_fkey" FOREIGN KEY ("trigger_id") REFERENCES "triggers"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automation_executions" ADD CONSTRAINT "automation_executions_action_id_fkey" FOREIGN KEY ("action_id") REFERENCES "actions"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "automation_executions" ADD CONSTRAINT "automation_executions_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/migrations/migration_lock.toml b/packages/shared/prisma/migrations/migration_lock.tomlindex 648c57fd59..044d57cdb0 100644--- a/packages/shared/prisma/migrations/migration_lock.toml+++ b/packages/shared/prisma/migrations/migration_lock.toml@@ -1,3 +1,3 @@# Please do not edit this file manually# It should be added in your version-control system (e.g., Git)-provider = "postgresql"\ No newline at end of file+provider = "postgresql"diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex c488abf506..42958bb733 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -157,6 +157,10 @@ model Project {Dashboard Dashboard[]DashboardWidget DashboardWidget[]TableViewPreset TableViewPreset[]+ actions Action[]+ triggers Trigger[]+ automationExecutions AutomationExecution[]+ Automation Automation[]DefaultLlmModel DefaultLlmModel[]@@index([orgId])@@ -1214,3 +1218,109 @@ model TableViewPreset {@@unique([projectId, tableName, name])@@map("table_view_presets")}++model Action {+ 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)++ type ActionType++ // Configuration specific to each action type+ config Json // Structured JSON for different action types+ // For WEBHOOK: { version: "1.0", url: "...", method: "POST", headers: {...}, secretId: "..." }+ // For ANNOTATION_QUEUE: { version: "1.0", queueId: "..." }++ automations Automation[]+ automationExecutions AutomationExecution[]++ @@index([projectId])+ @@map("actions")+}++model Trigger {+ 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)++ // When should this trigger fire+ eventSource String // trace, prompt, etc.+ eventActions String[] // created, updated, deleted+ filter Json? // Filter conditions (format: { field: "name", operator: "equals", value: "my_trace" })++ // Additional attributes+ status JobConfigState @default(ACTIVE) @map("status")++ // Link to executions+ automationExecutions AutomationExecution[]+ automations Automation[]++ @@index([projectId])+ @@map("triggers")+}++model Automation {+ id String @id @default(cuid())+ name String @map("name")+ trigger Trigger @relation(fields: [triggerId], references: [id], onDelete: Cascade)+ triggerId String @map("trigger_id")+ action Action @relation(fields: [actionId], references: [id], onDelete: Cascade)+ actionId String @map("action_id")+ createdAt DateTime @default(now()) @map("created_at")+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ AutomationExecution AutomationExecution[]++ @@index([projectId, actionId, triggerId])+ @@index([projectId, name])+ @@map("automations")+}++enum ActionType {+ WEBHOOK+ // More action types can be added as needed+}++enum ActionExecutionStatus {+ COMPLETED+ ERROR+ PENDING+ CANCELLED+}++model AutomationExecution {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ sourceId String @map("source_id")++ automationId String @map("automation_id")+ automation Automation @relation(fields: [automationId], references: [id], onDelete: Cascade)++ triggerId String @map("trigger_id")+ trigger Trigger @relation(fields: [triggerId], references: [id], onDelete: Cascade)++ actionId String @map("action_id")+ action Action @relation(fields: [actionId], references: [id], onDelete: Cascade)++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ status ActionExecutionStatus @default(PENDING) @map("status")+ input Json @map("input")+ output Json? @map("output")+ startedAt DateTime? @map("started_at")+ finishedAt DateTime? @map("finished_at")+ error String? @map("error")++ @@index([triggerId])+ @@index([actionId])+ @@index([projectId])+ @@map("automation_executions")+}diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.tsnew file mode 100644index 0000000000..b88727e36a--- /dev/null+++ b/packages/shared/src/domain/automations.ts@@ -0,0 +1,83 @@+import { Action, Trigger } from "@prisma/client";+import { FilterState } from "../types";+import { z } from "zod/v4";++export enum TriggerEventSource {+ // eslint-disable-next-line no-unused-vars+ Prompt = "prompt",+}++export const EventActionSchema = z.enum(["created", "updated", "deleted"]);++export type TriggerEventAction = z.infer<typeof EventActionSchema>;++export const TriggerEventSourceSchema = z.enum([TriggerEventSource.Prompt]);++export type TriggerDomain = Omit<+ Trigger,+ "filter" | "eventSource" | "eventActions"+> & {+ filter: FilterState;+ eventSource: TriggerEventSource;+ eventActions: TriggerEventAction[];+};++export type AutomationDomain = {+ id: string;+ name: string;+ trigger: TriggerDomain;+ action: ActionDomain;+};++export type ActionDomain = Omit<Action, "config"> & {+ config: SafeWebhookActionConfig;+};++export type ActionDomainWithSecrets = Omit<Action, "config"> & {+ config: WebhookActionConfigWithSecrets;+};++export const ActionTypeSchema = z.enum(["WEBHOOK"]);++export const AvailableWebhookApiSchema = z.record(+ z.enum(["prompt"]),+ z.enum(["v1"]),+);++export const WebhookActionConfigSchema = z.object({+ type: z.literal("WEBHOOK"),+ url: z.url(),+ headers: z.record(z.string(), z.string()),+ apiVersion: AvailableWebhookApiSchema,+ secretKey: z.string(),+ displaySecretKey: z.string(),+});++export const SafeWebhookActionConfigSchema = WebhookActionConfigSchema.omit({+ secretKey: true,+});++export type SafeWebhookActionConfig = z.infer<+ typeof SafeWebhookActionConfigSchema+>;++export const WebhookActionCreateSchema = WebhookActionConfigSchema.omit({+ secretKey: true,+ displaySecretKey: true,+});++export const ActionConfigSchema = z.discriminatedUnion("type", [+ WebhookActionConfigSchema,+]);++export const ActionCreateSchema = z.discriminatedUnion("type", [+ WebhookActionCreateSchema,+]);++export type ActionTypes = z.infer<typeof ActionTypeSchema>;+export type ActionConfig = z.infer<typeof ActionConfigSchema>;+export type ActionCreate = z.infer<typeof ActionCreateSchema>;++export type WebhookActionConfigWithSecrets = z.infer<+ typeof WebhookActionConfigSchema+>;diff --git a/packages/shared/src/domain/index.ts b/packages/shared/src/domain/index.tsindex 0e7c66017b..aba76fd349 100644--- a/packages/shared/src/domain/index.ts+++ b/packages/shared/src/domain/index.ts@@ -2,3 +2,6 @@ export * from "./observations";export * from "./traces";export * from "./scores";export * from "./table-view-presets";+export * from "./automations";+export * from "./webhooks";+export * from "./prompts";diff --git a/packages/shared/src/domain/prompts.ts b/packages/shared/src/domain/prompts.tsnew file mode 100644index 0000000000..86b1243a3e--- /dev/null+++ b/packages/shared/src/domain/prompts.ts@@ -0,0 +1,21 @@+import { z } from "zod/v4";+import { jsonSchemaNullable } from "../utils/zod";++export const PromptDomainSchema = z.object({+ id: z.string(),+ name: z.string(),+ version: z.number(),+ createdAt: z.date(),+ updatedAt: z.date(),+ createdBy: z.string(),+ isActive: z.boolean().nullable(),+ type: z.string().default("text"),+ tags: z.array(z.string()).default([]),+ labels: z.array(z.string()).default([]),+ prompt: jsonSchemaNullable,+ config: jsonSchemaNullable,+ projectId: z.string(),+ commitMessage: z.string().nullable(),+});++export type PromptDomain = z.infer<typeof PromptDomainSchema>;diff --git a/packages/shared/src/domain/webhooks.ts b/packages/shared/src/domain/webhooks.tsnew file mode 100644index 0000000000..622c8a324d--- /dev/null+++ b/packages/shared/src/domain/webhooks.ts@@ -0,0 +1,37 @@+import { z } from "zod/v4";+import { jsonSchema } from "../utils/zod";+import { EventActionSchema } from "./automations";++export const WebhookDefaultHeaders = {+ "Content-Type": "application/json",+ "User-Agent": "Langfuse/1.0",+};++export const WebhookOutboundBaseSchema = z.object({+ id: z.string(),+ timestamp: z.coerce.date(),+ type: z.literal("prompt-version"),+ apiVersion: z.literal("v1"),+ action: EventActionSchema,+});++export const PromptWebhookOutboundSchema = z+ .object({+ prompt: z.object({+ id: z.string(),+ name: z.string(),+ version: z.number(),+ projectId: z.string(),+ labels: z.array(z.string()),+ prompt: jsonSchema.nullable(),+ type: z.string(),+ config: z.record(z.string(), z.any()),+ commitMessage: z.string().nullable(),+ tags: z.array(z.string()),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ }),+ })+ .and(WebhookOutboundBaseSchema);++export type PromptWebhookOutput = z.infer<typeof PromptWebhookOutboundSchema>;diff --git a/packages/shared/src/encryption/encryption.ts b/packages/shared/src/encryption/encryption.tsnew file mode 100644index 0000000000..e1d2939343--- /dev/null+++ b/packages/shared/src/encryption/encryption.ts@@ -0,0 +1,60 @@+import crypto from "crypto";+import { env } from "../env";++const ENCRYPTION_KEY: string | undefined = env.ENCRYPTION_KEY; // Must be 256 bits (32 bytes, 64 hex characters)+const IV_LENGTH: number = 12; // For AES-GCM, this is always 12++// Alternatively: openssl rand -hex 32+export function keyGen() {+ return crypto.randomBytes(32).toString("hex");+}++/**+ * Encrypts the given plain text using AES-256-GCM algorithm.+ *+ * @param {string} plainText - The text to encrypt.+ * @returns {string} The encrypted data in hex format, including IV and authentication tag.+ */+export function encrypt(plainText: string): string {+ if (!ENCRYPTION_KEY) {+ throw new Error("Missing environment variable: `ENCRYPTION_KEY`");+ }+ const iv = crypto.randomBytes(IV_LENGTH); // Directly use Buffer returned by randomBytes+ const cipher = crypto.createCipheriv(+ "aes-256-gcm",+ Buffer.from(ENCRYPTION_KEY, "hex"),+ iv,+ );+ let encrypted = cipher.update(plainText, "utf8", "hex");+ encrypted += cipher.final("hex");+ const authTag = cipher.getAuthTag();++ // Return iv, encrypted data, and authTag as hex, combined in one line+ return iv.toString("hex") + ":" + encrypted + ":" + authTag.toString("hex");+}++export function decrypt(text: string): string {+ if (!ENCRYPTION_KEY) {+ throw new Error("Missing environment variable: `ENCRYPTION_KEY`");+ }+ const [ivHex, encryptedHex, authTagHex] = text.split(":");+ if (!ivHex || !encryptedHex || !authTagHex) {+ throw new Error("Invalid or corrupted cipher format");+ }++ const iv = Buffer.from(ivHex, "hex");+ const encryptedText = Buffer.from(encryptedHex, "hex");+ const authTag = Buffer.from(authTagHex, "hex");++ const decipher = crypto.createDecipheriv(+ "aes-256-gcm",+ Buffer.from(ENCRYPTION_KEY, "hex"),+ iv,+ );+ decipher.setAuthTag(authTag);++ let decrypted = decipher.update(encryptedText, undefined, "utf8");+ decrypted += decipher.final("utf8");++ return decrypted.toString();+}diff --git a/packages/shared/src/encryption/index.ts b/packages/shared/src/encryption/index.tsindex e1d2939343..d08115a90e 100644--- a/packages/shared/src/encryption/index.ts+++ b/packages/shared/src/encryption/index.ts@@ -1,60 +1,2 @@-import crypto from "crypto";-import { env } from "../env";--const ENCRYPTION_KEY: string | undefined = env.ENCRYPTION_KEY; // Must be 256 bits (32 bytes, 64 hex characters)-const IV_LENGTH: number = 12; // For AES-GCM, this is always 12--// Alternatively: openssl rand -hex 32-export function keyGen() {- return crypto.randomBytes(32).toString("hex");-}--/**- * Encrypts the given plain text using AES-256-GCM algorithm.- *- * @param {string} plainText - The text to encrypt.- * @returns {string} The encrypted data in hex format, including IV and authentication tag.- */-export function encrypt(plainText: string): string {- if (!ENCRYPTION_KEY) {- throw new Error("Missing environment variable: `ENCRYPTION_KEY`");- }- const iv = crypto.randomBytes(IV_LENGTH); // Directly use Buffer returned by randomBytes- const cipher = crypto.createCipheriv(- "aes-256-gcm",- Buffer.from(ENCRYPTION_KEY, "hex"),- iv,- );- let encrypted = cipher.update(plainText, "utf8", "hex");- encrypted += cipher.final("hex");- const authTag = cipher.getAuthTag();-- // Return iv, encrypted data, and authTag as hex, combined in one line- return iv.toString("hex") + ":" + encrypted + ":" + authTag.toString("hex");-}--export function decrypt(text: string): string {- if (!ENCRYPTION_KEY) {- throw new Error("Missing environment variable: `ENCRYPTION_KEY`");- }- const [ivHex, encryptedHex, authTagHex] = text.split(":");- if (!ivHex || !encryptedHex || !authTagHex) {- throw new Error("Invalid or corrupted cipher format");- }-- const iv = Buffer.from(ivHex, "hex");- const encryptedText = Buffer.from(encryptedHex, "hex");- const authTag = Buffer.from(authTagHex, "hex");-- const decipher = crypto.createDecipheriv(- "aes-256-gcm",- Buffer.from(ENCRYPTION_KEY, "hex"),- iv,- );- decipher.setAuthTag(authTag);-- let decrypted = decipher.update(encryptedText, undefined, "utf8");- decrypted += decipher.final("utf8");-- return decrypted.toString();-}+export * from "./encryption";+export * from "./signature";diff --git a/packages/shared/src/encryption/signature.ts b/packages/shared/src/encryption/signature.tsnew file mode 100644index 0000000000..3c7bb73b05--- /dev/null+++ b/packages/shared/src/encryption/signature.ts@@ -0,0 +1,42 @@+import crypto from "crypto";++// Generate a webhook secret key+export function generateWebhookSecret(): {+ secretKey: string;+ displaySecretKey: string;+} {+ // Generate 32 random bytes and encode as hex (64 characters)+ const rawSecret = crypto.randomBytes(32).toString("hex");+ const secretKey = `lf-whsec_${rawSecret}`;+ return { secretKey, displaySecretKey: getDisplaySecretKey(secretKey) };+}++// Create display version of webhook secret+export function getDisplaySecretKey(secretKey: string): string {+ if (!secretKey || secretKey.length < 12) {+ // whsec_ + at least 4 chars+ return "****";+ }++ return `lf-whsec_...${secretKey.slice(-4)}`;+}++// Generate HMAC-SHA256 signature for webhook payload+export function generateWebhookSignature(+ payload: string,+ timestamp: number,+ secret: string,+) {+ const signedPayload = `${timestamp}.${payload}`;+ return crypto+ .createHmac("sha256", secret)+ .update(signedPayload, "utf8")+ .digest("hex");+}++export function createSignatureHeader(payload: string, secret: string): string {+ const timestamp = Math.floor(Date.now() / 1000);+ const signature = generateWebhookSignature(payload, timestamp, secret);+ return `t=${timestamp},v1=${signature}`;+}+diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex b0b426135c..81b77ef22d 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -17,6 +17,7 @@ export * from "./utils/prompts";export * from "./features/entitlements/plans";export * from "./interfaces/rate-limits";export * from "./tableDefinitions/typeHelpers";+export * from "./domain/webhooks";// llm apiexport * from "./server/llm/types";@@ -46,7 +47,13 @@ export * from "./features/prompts/parsePromptDependencyTags";export * from "./features/prompts/validation";export * from "./features/prompts/types";export * from "./features/prompts/constants";-export { compileChatMessages, compileChatMessagesWithIds, isPlaceholder, type MessagePlaceholderValues, type PromptMessage as ServerPromptMessage } from "./server/llm/compileChatMessages";+export {+ compileChatMessages,+ compileChatMessagesWithIds,+ isPlaceholder,+ type MessagePlaceholderValues,+ type PromptMessage as ServerPromptMessage,+} from "./server/llm/compileChatMessages";// export db types onlyexport * from "@prisma/client";diff --git a/packages/shared/src/server/automations/webhooks.ts b/packages/shared/src/server/automations/webhooks.tsnew file mode 100644index 0000000000..f2becb2976--- /dev/null+++ b/packages/shared/src/server/automations/webhooks.ts@@ -0,0 +1,251 @@+import { Job, Processor } from "bullmq";+import { backOff } from "exponential-backoff";+import {+ ActionExecutionStatus,+ JobConfigState,+} from "../../../prisma/generated/types";+import {+ PromptWebhookOutboundSchema,+ WebhookDefaultHeaders,+} from "../../domain";+import { prisma } from "../../db";+import { TQueueJobTypes, QueueName, WebhookInput } from "../queues";+import {+ getActionByIdWithSecrets,+ getAutomationById,+ getConsecutiveAutomationFailures,+} from "../repositories";+import { logger } from "..";+import { createSignatureHeader } from "../../encryption/signature";+import { decrypt } from "../../encryption";+import { InternalServerError, LangfuseNotFoundError } from "../../errors";++export const webhookProcessor: Processor = async (+ job: Job<TQueueJobTypes[QueueName.WebhookQueue]>,+) => {+ try {+ return await executeWebhook(job.data.payload);+ } catch (error) {+ logger.error("Error executing WebhookJob", error);+ throw error;+ }+};++// TODO: Webhook outgoing API versioning+export const executeWebhook = async (input: WebhookInput) => {+ const executionStart = new Date();++ const { projectId, automationId, executionId } = input;+ let httpStatus: number | undefined;+ let responseBody: string | undefined;++ try {+ logger.debug(`Executing webhook for automation ${automationId}`);++ const automation = await getAutomationById({+ projectId,+ automationId,+ });++ if (!automation) {+ throw new LangfuseNotFoundError(`Automation ${automationId} not found`);+ }++ const actionConfig = await getActionByIdWithSecrets({+ projectId,+ actionId: automation.action.id,+ });++ if (!actionConfig) {+ throw new Error("Action config not found");+ }++ if (actionConfig.config.type !== "WEBHOOK") {+ throw new InternalServerError("Action config is not a webhook");+ }++ // TypeScript now knows actionConfig.config is WebhookActionConfig+ const webhookConfig = actionConfig.config;++ const validatedPayload = PromptWebhookOutboundSchema.safeParse({+ id: input.executionId,+ timestamp: new Date(),+ type: input.payload.type,+ apiVersion: "v1",+ action: input.payload.action,+ prompt: input.payload.prompt,+ });++ if (!validatedPayload.success) {+ throw new InternalServerError(+ `Invalid webhook payload: ${validatedPayload.error.message}`,+ );+ }++ // Prepare webhook payload with prompt always last+ const { prompt, ...otherFields } = validatedPayload.data;+ const webhookPayload = JSON.stringify({+ ...otherFields,+ prompt,+ });++ // Prepare headers with signature if secret exists+ const requestHeaders: Record<string, string> = {+ ...WebhookDefaultHeaders,+ ...webhookConfig.headers,+ };++ if (!webhookConfig.secretKey) {+ logger.warn(+ `Webhook config for action ${automation.action.id} has no secret key, failing webhook execution`,+ );+ throw new InternalServerError(+ "Webhook config has no secret key, failing webhook execution",+ );+ }++ if (webhookConfig.secretKey) {+ try {+ const decryptedSecret = decrypt(webhookConfig.secretKey);++ const signature = createSignatureHeader(+ webhookPayload,+ decryptedSecret,+ );+ requestHeaders["x-langfuse-signature"] = signature;+ } catch (error) {+ logger.error(+ "Failed to decrypt webhook secret or generate signature",+ error,+ );+ throw new InternalServerError("Failed to generate webhook signature");+ }+ }++ await backOff(+ async () => {+ logger.debug(+ `Sending webhook to ${webhookConfig.url} with payload ${JSON.stringify(+ webhookPayload,+ )} and headers ${JSON.stringify(requestHeaders)}`,+ );+ const res = await fetch(webhookConfig.url, {+ method: "POST",+ body: webhookPayload,+ headers: requestHeaders,+ });++ httpStatus = res.status;+ responseBody = await res.text();++ if (res.status !== 200) {+ logger.warn(+ `Webhook does not return 200: failed with status ${res.status} for url ${webhookConfig.url} and project ${projectId}`,+ );+ throw new Error(+ `Webhook does not return 200: failed with status ${res.status} for url ${webhookConfig.url} and project ${projectId}`,+ );+ }+ },+ {+ numOfAttempts: 4, // no retries for webhook calls via BullMQ+ },+ );++ // Update action execution status on success+ await prisma.automationExecution.update({+ where: {+ projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ id: executionId,+ },+ data: {+ status: ActionExecutionStatus.COMPLETED,+ startedAt: executionStart,+ finishedAt: new Date(),+ output: {+ httpStatus,+ responseBody: responseBody?.substring(0, 1000), // Limit response body size+ },+ },+ });++ logger.debug(+ `Webhook executed successfully for action ${automation.action.id}`,+ );+ } catch (error) {+ logger.error("Error executing webhook", error);++ const automation = await getAutomationById({+ projectId,+ automationId,+ });++ if (!automation) {+ throw new LangfuseNotFoundError(`Automation ${automationId} not found`);+ }++ const shouldRetryJob =+ error instanceof LangfuseNotFoundError ||+ error instanceof InternalServerError;++ if (shouldRetryJob) {+ logger.warn(+ `Retrying bullmq for webhook job for action ${automation.action.id}`,+ );+ throw error;+ }++ // Update action execution status and check if we should disable trigger+ await prisma.$transaction(async (tx) => {+ // Update execution status+ await tx.automationExecution.update({+ where: {+ id: executionId,+ projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ },+ data: {+ status: ActionExecutionStatus.ERROR,+ startedAt: executionStart,+ finishedAt: new Date(),+ error: error instanceof Error ? error.message : "Unknown error",+ output: httpStatus+ ? {+ httpStatus,+ responseBody: responseBody?.substring(0, 1000),+ }+ : undefined,+ },+ });++ // Check consecutive failures from execution history+ const consecutiveFailures = await getConsecutiveAutomationFailures({+ automationId,+ projectId,+ });++ logger.info(+ `Consecutive failures: ${consecutiveFailures} for trigger ${automation.trigger.id} in project ${projectId}`,+ );++ // Check if trigger should be disabled (this is the 5th failure, looking for 4 in the past.)+ if (consecutiveFailures >= 4) {+ await tx.trigger.update({+ where: { id: automation.trigger.id, projectId },+ data: { status: JobConfigState.INACTIVE },+ });++ logger.warn(+ `Automation ${automation.trigger.id} disabled after ${consecutiveFailures} consecutive failures in project ${projectId}`,+ );+ }+ });++ logger.debug(+ `Webhook failed for action ${automation.action.id} in project ${projectId}`,+ );+ }+};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 615f62ddb2..edead2017b 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -3,6 +3,7 @@ export * from "./services/email/organizationInvitation/sendMembershipInvitationEexport * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";export * from "./services/PromptService";+export * from "./services/PromptService/types";export * from "./services/traces-ui-table-service";export * from "./services/InMemoryFilterService";export * from "./auth/apiKeys";@@ -27,6 +28,7 @@ export * from "./redis/traceUpsert";export * from "./redis/createEvalQueue";export * from "./redis/cloudUsageMeteringQueue";export * from "./redis/getQueue";+export * from "./redis/webhookQueue";export * from "./redis/traceDelete";export * from "./redis/projectDelete";export * from "./redis/scoreDelete";@@ -44,6 +46,7 @@ export * from "./redis/coreDataS3ExportQueue";export * from "./redis/meteringDataPostgresExportQueue";export * from "./redis/experimentCreateQueue";export * from "./redis/dlqRetryQueue";+export * from "./redis/entityChangeQueue";export * from "./auth/types";export * from "./queues";export * from "./orderByToPrisma";@@ -64,5 +67,7 @@ export * from "./clickhouse/measureAndReturn";export * from "./data-deletion/ingestionFileDeletion";export * from "./s3";+export * from "./automations/webhooks";+// test utilsexport * from "./test-utils";diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex b286c5e705..807f6f1a41 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -6,6 +6,8 @@ import {BatchActionType,} from "../features/batchAction/types";import { BatchTableNames } from "../interfaces/tableNames";+import { EventActionSchema } from "../domain";+import { PromptDomainSchema } from "../domain/prompts";export const IngestionEvent = z.object({data: z.object({@@ -129,6 +131,33 @@ export const DeadLetterRetryQueueEventSchema = z.object({timestamp: z.date(),});+export const WebhookOutboundEnvelopeSchema = z.object({+ prompt: PromptDomainSchema,+ action: EventActionSchema,+ type: z.literal("prompt-version"),+});++export const WebhookInputSchema = z.object({+ projectId: z.string(),+ automationId: z.string(),+ executionId: z.string(),+ payload: WebhookOutboundEnvelopeSchema,+});++export const EntityChangeEventSchema = z.discriminatedUnion("entityType", [+ z.object({+ entityType: z.literal("prompt-version"),+ projectId: z.string(),+ promptId: z.string(),+ action: EventActionSchema,+ prompt: PromptDomainSchema,+ }),+ // Add other entity types here in the future+]);++export type WebhookInput = z.infer<typeof WebhookInputSchema>;+export type EntityChangeEventType = z.infer<typeof EntityChangeEventSchema>;+export type CreateEvalQueueEventType = z.infer<typeof CreateEvalQueueEventSchema>;@@ -161,6 +190,8 @@ export type DeadLetterRetryQueueEventType = z.infer<typeof DeadLetterRetryQueueEventSchema>;+export type WebhookQueueEventType = z.infer<typeof WebhookInputSchema>;+export enum QueueName {TraceUpsert = "trace-upsert", // Ingestion pipeline adds events on each Trace upsertTraceDelete = "trace-delete",@@ -184,6 +215,8 @@ export enum QueueName {CreateEvalQueue = "create-eval-queue",ScoreDelete = "score-delete",DeadLetterRetryQueue = "dead-letter-retry-queue",+ WebhookQueue = "webhook-queue",+ EntityChangeQueue = "entity-change-queue",}export enum QueueJobs {@@ -209,6 +242,8 @@ export enum QueueJobs {CreateEvalJob = "create-eval-job",ScoreDelete = "score-delete",DeadLetterRetryJob = "dead-letter-retry-job",+ WebhookJob = "webhook-job",+ EntityChangeJob = "entity-change-job",}export type TQueueJobTypes = {@@ -308,4 +343,16 @@ export type TQueueJobTypes = {payload: DeadLetterRetryQueueEventType;name: QueueJobs.DeadLetterRetryJob;};+ [QueueName.WebhookQueue]: {+ timestamp: Date;+ id: string;+ payload: WebhookInput;+ name: QueueJobs.WebhookJob;+ };+ [QueueName.EntityChangeQueue]: {+ timestamp: Date;+ id: string;+ payload: EntityChangeEventType;+ name: QueueJobs.EntityChangeJob;+ };};diff --git a/packages/shared/src/server/redis/entityChangeQueue.ts b/packages/shared/src/server/redis/entityChangeQueue.tsnew file mode 100644index 0000000000..34e019605c--- /dev/null+++ b/packages/shared/src/server/redis/entityChangeQueue.ts@@ -0,0 +1,50 @@+import { Queue } from "bullmq";+import { QueueName, TQueueJobTypes } from "../queues";+import {+ createNewRedisInstance,+ getQueuePrefix,+ redisQueueRetryOptions,+} from "./redis";+import { logger } from "../logger";++export class EntityChangeQueue {+ private static instance: Queue<+ TQueueJobTypes[QueueName.EntityChangeQueue]+ > | null = null;++ public static getInstance(): Queue<+ TQueueJobTypes[QueueName.EntityChangeQueue]+ > | null {+ if (EntityChangeQueue.instance) return EntityChangeQueue.instance;++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ EntityChangeQueue.instance = newRedis+ ? new Queue<TQueueJobTypes[QueueName.EntityChangeQueue]>(+ QueueName.EntityChangeQueue,+ {+ connection: newRedis,+ prefix: getQueuePrefix(QueueName.EntityChangeQueue),+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100_000,+ attempts: 5,+ backoff: {+ type: "exponential",+ delay: 5000,+ },+ },+ },+ )+ : null;++ EntityChangeQueue.instance?.on("error", (err) => {+ logger.error("EntityChangeQueue error", err);+ });++ return EntityChangeQueue.instance;+ }+}diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex f2f9b72db4..f278bb86a9 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -21,6 +21,8 @@ import { BatchActionQueue } from "./batchActionQueue";import { CreateEvalQueue } from "./createEvalQueue";import { ScoreDeleteQueue } from "./scoreDelete";import { DeadLetterRetryQueue } from "./dlqRetryQueue";+import { WebhookQueue } from "./webhookQueue";+import { EntityChangeQueue } from "./entityChangeQueue";// IngestionQueue is sharded and requires a sharding key// Use IngestionQueue.getInstance({ shardName: queueName }) directly instead@@ -70,8 +72,13 @@ export function getQueue(return ScoreDeleteQueue.getInstance();case QueueName.DeadLetterRetryQueue:return DeadLetterRetryQueue.getInstance();+ case QueueName.WebhookQueue:+ return WebhookQueue.getInstance();+ case QueueName.EntityChangeQueue:+ return EntityChangeQueue.getInstance();default: {- const exhaustiveCheckDefault: never = queueName; // eslint-disable-line no-case-declarations, no-unused-vars+ // eslint-disable-next-line no-case-declarations, no-unused-vars+ const exhaustiveCheckDefault: never = queueName;throw new Error(`Queue ${queueName} not found`);}}diff --git a/packages/shared/src/server/redis/webhookQueue.ts b/packages/shared/src/server/redis/webhookQueue.tsnew file mode 100644index 0000000000..bf59ccecae--- /dev/null+++ b/packages/shared/src/server/redis/webhookQueue.ts@@ -0,0 +1,45 @@+import { QueueName, TQueueJobTypes } from "../queues";+import { Queue } from "bullmq";+import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";+import { logger } from "../logger";++export class WebhookQueue {+ private static instance: Queue<+ TQueueJobTypes[QueueName.WebhookQueue]+ > | null = null;++ public static getInstance(): Queue<+ TQueueJobTypes[QueueName.WebhookQueue]+ > | null {+ if (WebhookQueue.instance) return WebhookQueue.instance;++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ WebhookQueue.instance = newRedis+ ? new Queue<TQueueJobTypes[QueueName.WebhookQueue]>(+ QueueName.WebhookQueue,+ {+ connection: newRedis,+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100_000,+ attempts: 5,+ backoff: {+ type: "exponential",+ delay: 5000,+ },+ },+ },+ )+ : null;++ WebhookQueue.instance?.on("error", (err) => {+ logger.error("WebhookQueue error", err);+ });++ return WebhookQueue.instance;+ }+}diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.tsnew file mode 100644index 0000000000..a637245d4d--- /dev/null+++ b/packages/shared/src/server/repositories/automation-repository.ts@@ -0,0 +1,242 @@+import {+ Action,+ ActionExecutionStatus,+ JobConfigState,+ prisma,+ Trigger,+} from "../../db";+import {+ TriggerEventSource,+ WebhookActionConfigWithSecrets,+ TriggerDomain,+ TriggerEventAction,+ ActionDomain,+ AutomationDomain,+ SafeWebhookActionConfig,+} from "../../domain/automations";+import { FilterState } from "../../types";++export const getActionByIdWithSecrets = async ({+ projectId,+ actionId,+}: {+ projectId: string;+ actionId: string;+}) => {+ const actionConfig = await prisma.action.findFirst({+ where: {+ id: actionId,+ projectId,+ },+ });++ if (!actionConfig) {+ return null;+ }++ const config = actionConfig.config as WebhookActionConfigWithSecrets;+ return {+ ...actionConfig,+ config: {+ type: config.type,+ url: config.url,+ headers: config.headers,+ apiVersion: config.apiVersion,+ displaySecretKey: config.displaySecretKey,+ secretKey: config.secretKey,+ },+ };+};++export const getActionById = async ({+ projectId,+ actionId,+}: {+ projectId: string;+ actionId: string;+}): Promise<ActionDomain | null> => {+ const actionConfig = await prisma.action.findFirst({+ where: {+ id: actionId,+ projectId,+ },+ });++ if (!actionConfig) {+ return null;+ }++ const actionDomain = convertActionToDomain(actionConfig);++ return actionDomain;+};++export type TriggerDomainWithActions = TriggerDomain & { actionIds: string[] };++export const getTriggerConfigurations = async ({+ projectId,+ eventSource,+ status,+}: {+ projectId: string;+ eventSource: TriggerEventSource;+ status: JobConfigState;+}): Promise<TriggerDomainWithActions[]> => {+ const triggers = await prisma.trigger.findMany({+ where: {+ projectId,+ eventSource,+ status,+ },+ include: {+ automations: {+ include: {+ action: true,+ },+ },+ },+ });++ const triggerConfigurations = triggers.map((trigger) => ({+ ...convertTriggerToDomain(trigger),+ actionIds: trigger.automations.map((automation) => automation.action.id),+ }));++ return triggerConfigurations;+};++const convertTriggerToDomain = (trigger: Trigger): TriggerDomain => {+ return {+ ...trigger,+ eventActions: (trigger.eventActions || []) as TriggerEventAction[],+ filter: (trigger.filter || []) as FilterState,+ eventSource: trigger.eventSource as TriggerEventSource,+ };+};++const convertActionToDomain = (action: Action): ActionDomain => {+ const config = action.config as WebhookActionConfigWithSecrets;+ return {+ ...action,+ config: {+ type: config.type,+ url: config.url,+ headers: config.headers,+ apiVersion: config.apiVersion,+ displaySecretKey: config.displaySecretKey,+ } as SafeWebhookActionConfig,+ };+};++export const getAutomationById = async ({+ projectId,+ automationId,+}: {+ projectId: string;+ automationId: string;+}): Promise<AutomationDomain | null> => {+ const automation = await prisma.automation.findFirst({+ where: {+ id: automationId,+ projectId,+ },+ include: {+ action: true,+ trigger: true,+ },+ });++ if (!automation) {+ return null;+ }++ return {+ id: automation.id,+ name: automation.name,+ trigger: convertTriggerToDomain(automation.trigger),+ action: convertActionToDomain(automation.action),+ };+};++export const getAutomations = async ({+ projectId,+ triggerId,+ actionId,+}: {+ projectId: string;+ triggerId?: string;+ actionId?: string;+}): Promise<AutomationDomain[]> => {+ const automations = await prisma.automation.findMany({+ where: {+ projectId,+ ...(triggerId ? { triggerId } : {}),+ ...(actionId ? { actionId } : {}),+ },+ include: {+ action: true,+ trigger: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ return automations.map((automation) => ({+ id: automation.id,+ name: automation.name,+ trigger: convertTriggerToDomain(automation.trigger),+ action: convertActionToDomain(automation.action),+ }));+};++export const getConsecutiveAutomationFailures = async ({+ automationId,+ projectId,+}: {+ automationId: string;+ projectId: string;+}): Promise<number> => {+ // First get the automation to extract triggerId and actionId+ const automation = await prisma.automation.findFirst({+ where: {+ id: automationId,+ projectId,+ },+ });++ if (!automation) {+ return 0;+ }++ const { triggerId, actionId } = automation;+ const executions = await prisma.automationExecution.findMany({+ where: {+ triggerId,+ actionId,+ projectId,+ status: {+ in: [ActionExecutionStatus.ERROR, ActionExecutionStatus.COMPLETED],+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ take: 20,+ select: {+ status: true,+ },+ });++ let consecutiveFailures = 0;+ for (const execution of executions) {+ if (execution.status === ActionExecutionStatus.ERROR) {+ consecutiveFailures++;+ } else if (execution.status === ActionExecutionStatus.COMPLETED) {+ break; // Stop counting when we hit a successful execution+ }+ // Skip PENDING/CANCELLED executions in the count+ }++ return consecutiveFailures;+};diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 600902e68e..63882595c6 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -12,3 +12,4 @@ export * from "./trace-sessions";export * from "./scores-utils";export * from "./blobStorageLog";export * from "./environments";+export * from "./automation-repository";diff --git a/packages/shared/src/server/services/InMemoryFilterService.ts b/packages/shared/src/server/services/InMemoryFilterService.tsindex 8c3522caa1..95bad03f58 100644--- a/packages/shared/src/server/services/InMemoryFilterService.ts+++ b/packages/shared/src/server/services/InMemoryFilterService.ts@@ -15,6 +15,9 @@ export class InMemoryFilterService {filter: FilterState,fieldMapper: (data: T, column: string) => unknown, // eslint-disable-line no-unused-vars): boolean {+ logger.debug(+ `Evaluating filter ${JSON.stringify(filter)} for data ${JSON.stringify(data)}`,+ );try {// If no filters, data matchesif (!filter || filter.length === 0) {diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.tsindex 5dc2262ed6..b9ea8cf9d9 100644--- a/packages/shared/src/tableDefinitions/index.ts+++ b/packages/shared/src/tableDefinitions/index.ts@@ -4,3 +4,4 @@ export * from "./mapObservationsTable";export * from "./mapTracesTable";export * from "./mapDashboards";export * from "./mapScoresTable";+export * from "./promptsTable";diff --git a/web/src/server/api/definitions/promptsTable.ts b/packages/shared/src/tableDefinitions/promptsTable.tssimilarity index 82%rename from web/src/server/api/definitions/promptsTable.tsrename to packages/shared/src/tableDefinitions/promptsTable.tsindex 9fd49c6456..7c56fdd373 100644--- a/web/src/server/api/definitions/promptsTable.ts+++ b/packages/shared/src/tableDefinitions/promptsTable.ts@@ -1,9 +1,6 @@-import {- type ColumnDefinition,- PromptType,- type SingleValueOption,- formatColumnOptions,-} from "@langfuse/shared";+import { PromptType } from "../features/prompts/types";+import { formatColumnOptions } from "./typeHelpers";+import { ColumnDefinition, SingleValueOption } from "./types";export const promptsTableCols: ColumnDefinition[] = [{@@ -77,3 +74,7 @@ export function promptsTableColsWithOptions(return col;});}++export function webhookActionFilterOptions(): ColumnDefinition[] {+ return promptsTableCols.filter((col) => col.id === "name");+}diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex dda9069287..14e1d5fffb 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -24,6 +24,7 @@ export type FilterOption = {value: string;count?: number;displayValue?: string; // FIX: Temporary workaround: Used to display a different value than the actual value since multiSelect doesn't support key-value pairs+ description?: string;};export type TableName =diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 936d8485c6..0f9e5f8722 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -60,7 +60,7 @@ importers:version: 14.2.30(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])zod:specifier: ^3.25.62version: 3.25.62@@ -112,7 +112,7 @@ importers:version: 7.12.0([email protected])([email protected])'@vercel/style-guide':specifier: ^6.0.0- version: 6.0.0(@next/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))+ version: 6.0.0(@next/[email protected])([email protected])([email protected](@types/[email protected]))([email protected])([email protected])([email protected](@types/[email protected]))eslint-config-next:specifier: ^14.2.15version: 14.2.15([email protected])([email protected])@@ -234,7 +234,7 @@ importers:version: 4.1.1next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])nodemailer:specifier: ^6.9.15version: 6.9.15@@ -634,7 +634,7 @@ importers:version: 14.2.30(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])next-query-params:specifier: ^5.0.1version: 5.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]))([email protected]))@@ -758,7 +758,7 @@ importers:'@testing-library/jest-dom':specifier: ^6.4.6- version: 6.4.6(@jest/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))+ version: 6.4.6(@jest/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))([email protected](@types/[email protected]))'@testing-library/react':specifier: ^15.0.7@@ -14337,7 +14337,7 @@ snapshots:'@antfu/install-pkg': 0.4.1'@antfu/utils': 0.7.10'@iconify/types': 2.0.0- debug: 4.4.0+ debug: 4.4.1kolorist: 1.8.0local-pkg: 0.5.0mlly: 1.7.1@@ -14354,26 +14354,12 @@ snapshots:optionalDependencies:'@types/node': 20.14.8- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@inquirer/core': 10.1.0(@types/[email protected])- '@inquirer/type': 3.0.1(@types/[email protected])- '@types/node': 20.10.5- optional: true-'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/core': 10.1.0(@types/[email protected])'@inquirer/type': 3.0.1(@types/[email protected])'@types/node': 20.11.29- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@inquirer/core': 10.1.0(@types/[email protected])- '@inquirer/type': 3.0.1(@types/[email protected])- '@types/node': 20.14.8- optional: true-'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/core': 10.1.13(@types/[email protected])@@ -14381,21 +14367,6 @@ snapshots:optionalDependencies:'@types/node': 20.14.8- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@inquirer/figures': 1.0.8- '@inquirer/type': 3.0.4(@types/[email protected])- ansi-escapes: 4.3.2- cli-width: 4.1.0- mute-stream: 2.0.0- signal-exit: 4.1.0- strip-ansi: 6.0.1- wrap-ansi: 6.2.0- yoctocolors-cjs: 2.1.2- transitivePeerDependencies:- - '@types/node'- optional: true-'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/figures': 1.0.8@@ -14410,21 +14381,6 @@ snapshots:transitivePeerDependencies:- '@types/node'- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@inquirer/figures': 1.0.8- '@inquirer/type': 3.0.4(@types/[email protected])- ansi-escapes: 4.3.2- cli-width: 4.1.0- mute-stream: 2.0.0- signal-exit: 4.1.0- strip-ansi: 6.0.1- wrap-ansi: 6.2.0- yoctocolors-cjs: 2.1.2- transitivePeerDependencies:- - '@types/node'- optional: true-'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/figures': 1.0.12@@ -14522,34 +14478,14 @@ snapshots:optionalDependencies:'@types/node': 20.14.8- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@types/node': 20.10.5- optional: true-'@inquirer/[email protected](@types/[email protected])':dependencies:'@types/node': 20.11.29- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@types/node': 20.14.8- optional: true-- '@inquirer/[email protected](@types/[email protected])':- optionalDependencies:- '@types/node': 20.10.5- optional: true-'@inquirer/[email protected](@types/[email protected])':optionalDependencies:'@types/node': 20.11.29- '@inquirer/[email protected](@types/[email protected])':- optionalDependencies:- '@types/node': 20.14.8- optional: true-'@inquirer/[email protected](@types/[email protected])':optionalDependencies:'@types/node': 20.14.8@@ -15097,7 +15033,7 @@ snapshots:'@next-auth/[email protected](@prisma/[email protected]([email protected]([email protected]))([email protected]))([email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]))':dependencies:- next-auth: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ next-auth: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@next/[email protected]': {}@@ -17744,7 +17680,7 @@ snapshots:lz-string: 1.5.0pretty-format: 27.5.1- '@testing-library/[email protected](@jest/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))':+ '@testing-library/[email protected](@jest/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))([email protected](@types/[email protected]))':dependencies:'@adobe/css-tools': 4.4.0'@babel/runtime': 7.24.7@@ -17758,7 +17694,7 @@ snapshots:'@jest/globals': 29.7.0'@types/jest': 29.5.12jest: 29.7.0(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))- vitest: 2.1.2(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ vitest: 2.1.2(@types/[email protected])'@testing-library/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -18417,7 +18353,7 @@ snapshots:'@ungap/[email protected]': {}- '@vercel/[email protected](@next/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))':+ '@vercel/[email protected](@next/[email protected])([email protected])([email protected](@types/[email protected]))([email protected])([email protected])([email protected](@types/[email protected]))':dependencies:'@babel/core': 7.24.3'@babel/eslint-parser': 7.24.1(@babel/[email protected])([email protected])@@ -18425,19 +18361,19 @@ snapshots:'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/parser': 7.12.0([email protected])([email protected])eslint-config-prettier: 9.1.0([email protected])- eslint-import-resolver-alias: 1.1.2([email protected])+ eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])eslint-plugin-eslint-comments: 3.2.0([email protected])- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])- eslint-plugin-jest: 27.9.0(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-plugin-jest: 27.9.0(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected]))([email protected])eslint-plugin-jsx-a11y: 6.8.0([email protected])- eslint-plugin-playwright: 1.5.4([email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))([email protected])+ eslint-plugin-playwright: 1.5.4([email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected]))([email protected]))([email protected])eslint-plugin-react: 7.34.1([email protected])eslint-plugin-react-hooks: 4.6.0([email protected])eslint-plugin-testing-library: 6.2.0([email protected])([email protected])eslint-plugin-tsdoc: 0.2.17eslint-plugin-unicorn: 51.0.1([email protected])- eslint-plugin-vitest: 0.3.26(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))+ eslint-plugin-vitest: 0.3.26(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected]))prettier-plugin-packagejson: 2.4.12([email protected])optionalDependencies:'@next/eslint-plugin-next': 14.2.15@@ -18458,33 +18394,31 @@ snapshots:chai: 5.1.1tinyrainbow: 1.2.0- '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))':+ '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))':dependencies:'@vitest/spy': 2.1.2estree-walker: 3.0.3magic-string: 0.30.11optionalDependencies:- msw: 2.6.5(@types/[email protected])([email protected])- vite: 5.2.14(@types/[email protected])([email protected])- optional: true+ msw: 2.6.5(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])([email protected])- '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))':+ '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected]))':dependencies:'@vitest/spy': 2.1.2estree-walker: 3.0.3magic-string: 0.30.11optionalDependencies:- msw: 2.6.5(@types/[email protected])([email protected])- vite: 5.2.14(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])+ optional: true- '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))':+ '@vitest/[email protected](@vitest/[email protected])([email protected](@types/[email protected]))':dependencies:'@vitest/spy': 2.1.2estree-walker: 3.0.3magic-string: 0.30.11optionalDependencies:- msw: 2.6.5(@types/[email protected])([email protected])- vite: 5.2.14(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])optional: true'@vitest/[email protected]':@@ -18691,7 +18625,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.1transitivePeerDependencies:- supports-color@@ -19566,7 +19500,7 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected]):dependencies:'@jest/types': 29.6.3chalk: 4.1.2@@ -20380,7 +20314,7 @@ snapshots:eslint: 8.57.0eslint-import-resolver-node: 0.3.9eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])eslint-plugin-jsx-a11y: 6.8.0([email protected])eslint-plugin-react: 7.34.1([email protected])eslint-plugin-react-hooks: 4.6.0([email protected])@@ -20397,7 +20331,7 @@ snapshots:[email protected]([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]))([email protected]):dependencies:eslint: 8.57.0- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])eslint-plugin-n: 16.6.2([email protected])eslint-plugin-promise: 6.4.0([email protected])@@ -20407,9 +20341,9 @@ snapshots:eslint-plugin-turbo: 2.5.4([email protected])([email protected])turbo: 2.5.4+ [email protected]([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])):dependencies:- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])dependencies:@@ -20424,8 +20358,8 @@ snapshots:debug: 4.3.7([email protected])enhanced-resolve: 5.17.1eslint: 8.57.0- eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])fast-glob: 3.3.3get-tsconfig: 4.8.1is-core-module: 2.15.1@@ -20442,7 +20376,7 @@ snapshots:enhanced-resolve: 5.17.1eslint: 8.57.0eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])- eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])fast-glob: 3.3.3get-tsconfig: 4.8.1is-core-module: 2.15.1@@ -20453,25 +20387,25 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected]):dependencies:debug: 3.2.7optionalDependencies:'@typescript-eslint/parser': 7.12.0([email protected])([email protected])eslint: 8.57.0eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):dependencies:debug: 3.2.7optionalDependencies:'@typescript-eslint/parser': 7.12.0([email protected])([email protected])eslint: 8.57.0eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])+ eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -20488,7 +20422,34 @@ snapshots:eslint: 8.57.0ignore: 5.3.2- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]):+ dependencies:+ array-includes: 3.1.7+ array.prototype.findlastindex: 1.2.4+ array.prototype.flat: 1.3.2+ array.prototype.flatmap: 1.3.2+ debug: 3.2.7+ doctrine: 2.1.0+ eslint: 8.57.0+ eslint-import-resolver-node: 0.3.9+ eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ hasown: 2.0.2+ is-core-module: 2.15.1+ is-glob: 4.0.3+ minimatch: 3.1.2+ object.fromentries: 2.0.8+ object.groupby: 1.0.3+ object.values: 1.2.0+ semver: 6.3.1+ tsconfig-paths: 3.15.0+ optionalDependencies:+ '@typescript-eslint/parser': 7.12.0([email protected])([email protected])+ transitivePeerDependencies:+ - eslint-import-resolver-typescript+ - eslint-import-resolver-webpack+ - supports-color++ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]):dependencies:array-includes: 3.1.7array.prototype.findlastindex: 1.2.4@@ -20515,13 +20476,13 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected]))([email protected]):dependencies:'@typescript-eslint/utils': 5.62.0([email protected])([email protected])eslint: 8.57.0optionalDependencies:'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])- jest: 29.7.0(@types/[email protected])([email protected])+ jest: 29.7.0(@types/[email protected])transitivePeerDependencies:- supports-color- typescript@@ -20563,12 +20524,12 @@ snapshots:- [email protected]([email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected]))([email protected]):+ [email protected]([email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected]))([email protected]))([email protected]):dependencies:eslint: 8.57.0globals: 13.24.0optionalDependencies:- eslint-plugin-jest: 27.9.0(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ eslint-plugin-jest: 27.9.0(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected]))([email protected])[email protected](@types/[email protected])([email protected]([email protected]))([email protected])([email protected]):dependencies:@@ -20651,13 +20612,13 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])):+ [email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected](@types/[email protected])):dependencies:'@typescript-eslint/utils': 7.3.1([email protected])([email protected])eslint: 8.57.0optionalDependencies:'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])- vitest: 2.1.2(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ vitest: 2.1.2(@types/[email protected])transitivePeerDependencies:- supports-color- typescript@@ -20855,7 +20816,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.1get-stream: 5.2.0yauzl: 2.10.0optionalDependencies:@@ -21440,7 +21401,7 @@ snapshots:dependencies:agent-base: 7.1.3- debug: 4.4.0+ debug: 4.4.1transitivePeerDependencies:- supports-color@@ -21461,7 +21422,7 @@ snapshots:dependencies:agent-base: 7.1.3- debug: 4.4.0+ debug: 4.4.1transitivePeerDependencies:- supports-color@@ -21836,7 +21797,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.1istanbul-lib-coverage: 3.2.2source-map: 0.6.1transitivePeerDependencies:@@ -21918,13 +21879,13 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected]):dependencies:'@jest/core': 29.7.0([email protected])([email protected](@types/[email protected])([email protected]))'@jest/test-result': 29.7.0'@jest/types': 29.6.3chalk: 4.1.2- create-jest: 29.7.0(@types/[email protected])([email protected])+ create-jest: 29.7.0(@types/[email protected])exit: 0.1.2import-local: 3.1.0jest-config: 29.7.0(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))@@ -22248,12 +22209,12 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected]):dependencies:'@jest/core': 29.7.0([email protected])([email protected](@types/[email protected])([email protected]))'@jest/types': 29.6.3import-local: 3.1.0- jest-cli: 29.7.0(@types/[email protected])([email protected])+ jest-cli: 29.7.0(@types/[email protected])transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -23050,7 +23011,7 @@ snapshots:dependencies:'@types/debug': 4.1.8- debug: 4.4.0+ debug: 4.4.1decode-named-character-reference: 1.0.2devlop: 1.1.0micromark-core-commonmark: 2.0.1@@ -23161,32 +23122,6 @@ snapshots:optionalDependencies:msgpackr-extract: 3.0.3- dependencies:- '@bundled-es-modules/cookie': 2.0.1- '@bundled-es-modules/statuses': 1.0.1- '@bundled-es-modules/tough-cookie': 0.1.6- '@inquirer/confirm': 5.0.2(@types/[email protected])- '@mswjs/interceptors': 0.37.1- '@open-draft/deferred-promise': 2.2.0- '@open-draft/until': 2.1.0- '@types/cookie': 0.6.0- '@types/statuses': 2.0.5- chalk: 4.1.2- graphql: 16.9.0- headers-polyfill: 4.0.3- is-node-process: 1.2.0- outvariant: 1.4.3- path-to-regexp: 6.3.0- strict-event-emitter: 0.5.1- type-fest: 4.27.0- yargs: 17.7.2- optionalDependencies:- typescript: 5.4.5- transitivePeerDependencies:- - '@types/node'- optional: true-dependencies:'@bundled-es-modules/cookie': 2.0.1@@ -23212,32 +23147,6 @@ snapshots:transitivePeerDependencies:- '@types/node'- dependencies:- '@bundled-es-modules/cookie': 2.0.1- '@bundled-es-modules/statuses': 1.0.1- '@bundled-es-modules/tough-cookie': 0.1.6- '@inquirer/confirm': 5.0.2(@types/[email protected])- '@mswjs/interceptors': 0.37.1- '@open-draft/deferred-promise': 2.2.0- '@open-draft/until': 2.1.0- '@types/cookie': 0.6.0- '@types/statuses': 2.0.5- chalk: 4.1.2- graphql: 16.9.0- headers-polyfill: 4.0.3- is-node-process: 1.2.0- outvariant: 1.4.3- path-to-regexp: 6.3.0- strict-event-emitter: 0.5.1- type-fest: 4.27.0- yargs: 17.7.2- optionalDependencies:- typescript: 5.4.5- transitivePeerDependencies:- - '@types/node'- optional: true-@@ -23266,7 +23175,7 @@ snapshots:dependencies:type-fest: 2.19.0- [email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):+ [email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):dependencies:'@babel/runtime': 7.26.0'@panva/hkdf': 1.1.1@@ -25759,12 +25668,12 @@ snapshots:'@egjs/hammerjs': 2.0.17component-emitter: 1.3.1+ [email protected](@types/[email protected]):dependencies:cac: 6.7.14debug: 4.3.7([email protected])pathe: 1.1.2- vite: 5.2.14(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])transitivePeerDependencies:- '@types/node'- less@@ -25792,12 +25701,12 @@ snapshots:- supports-color- terser+ [email protected](@types/[email protected]):dependencies:cac: 6.7.14debug: 4.3.7([email protected])pathe: 1.1.2- vite: 5.2.14(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])transitivePeerDependencies:- '@types/node'- less@@ -25809,7 +25718,7 @@ snapshots:- terseroptional: true+ [email protected](@types/[email protected]):dependencies:esbuild: 0.20.2postcss: 8.5.3@@ -25817,7 +25726,6 @@ snapshots:optionalDependencies:'@types/node': 20.10.5fsevents: 2.3.3- terser: 5.43.1optional: true@@ -25830,7 +25738,7 @@ snapshots:fsevents: 2.3.3terser: 5.43.1+ [email protected](@types/[email protected]):dependencies:esbuild: 0.20.2postcss: 8.5.3@@ -25838,13 +25746,12 @@ snapshots:optionalDependencies:'@types/node': 20.14.8fsevents: 2.3.3- terser: 5.43.1optional: true- [email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]):+ [email protected](@types/[email protected]):dependencies:'@vitest/expect': 2.1.2- '@vitest/mocker': 2.1.2(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))'@vitest/pretty-format': 2.1.2'@vitest/runner': 2.1.2'@vitest/snapshot': 2.1.2@@ -25859,12 +25766,11 @@ snapshots:tinyexec: 0.3.0tinypool: 1.0.1tinyrainbow: 1.2.0- vite: 5.2.14(@types/[email protected])([email protected])- vite-node: 2.1.2(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])+ vite-node: 2.1.2(@types/[email protected])why-is-node-running: 2.3.0optionalDependencies:'@types/node': 20.10.5- jsdom: 20.0.3transitivePeerDependencies:- less- lightningcss@@ -25910,10 +25816,10 @@ snapshots:- supports-color- terser- [email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected]):+ [email protected](@types/[email protected]):dependencies:'@vitest/expect': 2.1.2- '@vitest/mocker': 2.1.2(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected]))'@vitest/pretty-format': 2.1.2'@vitest/runner': 2.1.2'@vitest/snapshot': 2.1.2@@ -25928,12 +25834,11 @@ snapshots:tinyexec: 0.3.0tinypool: 1.0.1tinyrainbow: 1.2.0- vite: 5.2.14(@types/[email protected])([email protected])- vite-node: 2.1.2(@types/[email protected])([email protected])+ vite: 5.2.14(@types/[email protected])+ vite-node: 2.1.2(@types/[email protected])why-is-node-running: 2.3.0optionalDependencies:'@types/node': 20.14.8- jsdom: 20.0.3transitivePeerDependencies:- less- lightningcss@@ -26229,4 +26134,4 @@ snapshots:- [email protected]: {}+ [email protected]: {}\ No newline at end of filediff --git a/turbo.json b/turbo.jsonindex 914bd99207..5d36d8c90c 100644--- a/turbo.json+++ b/turbo.json@@ -1,25 +1,14 @@{"$schema": "https://turbo.build/schema.json",- "globalDependencies": [- ".env"- ],+ "globalDependencies": [".env"],"envMode": "loose","tasks": {"build": {- "dependsOn": [- "db:generate",- "^build"- ],- "outputs": [- "dist/**",- ".next/**",- "!.next/cache/**"- ]+ "dependsOn": ["db:generate", "^build"],+ "outputs": ["dist/**", ".next/**", "!.next/cache/**"]},"start": {- "dependsOn": [- "^start"- ]+ "dependsOn": ["^start"]},"db:migrate": {"cache": false@@ -32,41 +21,27 @@"dev": {"cache": false,"persistent": true,- "dependsOn": [- "db:generate",- "@langfuse/shared#build"- ]+ "dependsOn": ["db:generate", "@langfuse/shared#build"]},"dev:worker": {"cache": false,"persistent": true,- "dependsOn": [- "db:generate",- "@langfuse/shared#build"- ]+ "dependsOn": ["db:generate", "@langfuse/shared#build"]},"dev:web": {"cache": false,"persistent": true,- "dependsOn": [- "db:generate",- "@langfuse/shared#build"- ]+ "dependsOn": ["db:generate", "@langfuse/shared#build"]},"db:generate": {"cache": false,- "dependsOn": [- "^db:generate"- ]+ "dependsOn": ["^db:generate"]},"lint": {"cache": false},"test": {- "dependsOn": [- "^test",- "db:generate"- ]+ "dependsOn": ["^test", "db:generate"]}}}diff --git a/web/package.json b/web/package.jsonindex 99f453a57a..97513b50ab 100644--- a/web/package.json+++ b/web/package.json@@ -14,9 +14,9 @@"prettier": "prettier --write ./src *.{ts,js}","clean": "rm -rf node_modules","start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",- "test": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --silent false --verbose false --runInBand --detectOpenHandles --selectProjects async-server",- "test-sync": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --silent false --verbose false --runInBand --detectOpenHandles --selectProjects sync-server",- "test-client": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --silent false --verbose false --runInBand --detectOpenHandles --selectProjects client",+ "test": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --detectOpenHandles --selectProjects async-server",+ "test-sync": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --detectOpenHandles --selectProjects sync-server",+ "test-client": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --detectOpenHandles --selectProjects client","test:watch": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --watch --runInBand","test:e2e": "dotenv -e ../.env.test -e ../.env -- playwright test --reporter=line","test:e2e:server": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --runInBand --detectOpenHandles --verbose --selectProjects e2e-server"diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/async/automations-trpc.servertest.tsnew file mode 100644index 0000000000..4003fef801--- /dev/null+++ b/web/src/__tests__/async/automations-trpc.servertest.ts@@ -0,0 +1,992 @@+/** @jest-environment node */+/* eslint-disable @typescript-eslint/no-unsafe-member-access */++import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import type { Session } from "next-auth";+import { v4 } from "uuid";+import { ActionExecutionStatus, JobConfigState } from "@langfuse/shared";+import { encrypt } from "@langfuse/shared/encryption";+import { generateWebhookSecret } from "@langfuse/shared/encryption";++const __orgIds: string[] = [];++async function prepare() {+ const { project, org } = await createOrgProjectAndApiKey();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: org.id,+ name: org.name,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ projects: [+ {+ id: project.id,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: project.name,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: "cloud:hobby",+ },+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ __orgIds.push(org.id);++ return { project, org, session, ctx, caller };+}++describe("automations trpc", () => {+ afterAll(async () => {+ await prisma.organization.deleteMany({+ where: {+ id: { in: __orgIds },+ },+ });+ });++ describe("automations.getAutomations", () => {+ it("should retrieve all automations for a project", async () => {+ const { project, caller } = await prepare();++ // Create test prompt+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt",+ version: 1,+ type: "text",+ prompt: { text: "Hello world" },+ createdBy: "test-user",+ },+ });++ // Create test trigger+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ // Create test action+ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Test Automation",+ },+ });++ const response = await caller.automations.getAutomations({+ projectId: project.id,+ });++ expect(response).toHaveLength(1);+ expect(response[0]).toMatchObject({+ name: "Test Automation",+ trigger: expect.objectContaining({+ id: trigger.id,+ eventSource: "prompt",+ eventActions: ["created"],+ status: JobConfigState.ACTIVE,+ }),+ action: expect.objectContaining({+ id: action.id,+ type: "WEBHOOK",+ config: expect.objectContaining({+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ displaySecretKey,+ }),+ }),+ });++ expect(response[0].action.config).not.toHaveProperty("secretKey");+ });++ it("should return empty array when no automations exist", async () => {+ const { project, caller } = await prepare();++ const response = await caller.automations.getAutomations({+ projectId: project.id,+ });++ expect(response).toEqual([]);+ });++ it("should return empty array for user with read access but no automations", async () => {+ const { project, session } = await prepare();++ // Create a session with limited permissions (VIEWER can read but not create)+ const limitedSession: Session = {+ ...session,+ user: {+ ...session.user!,+ admin: false,+ organizations: [+ {+ ...session.user!.organizations[0],+ role: "MEMBER",+ projects: [+ {+ ...session.user!.organizations[0].projects[0],+ role: "VIEWER", // VIEWER role can read automations but not create/update/delete+ },+ ],+ },+ ],+ },+ };++ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });++ const response = await limitedCaller.automations.getAutomations({+ projectId: project.id,+ });++ expect(response).toEqual([]);+ });+ });++ describe("automations.getAutomation", () => {+ it("should retrieve a specific automation", async () => {+ const { project, caller } = await prepare();++ // Create test trigger and action+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Specific Automation",+ },+ });++ const response = await caller.automations.getAutomation({+ projectId: project.id,+ automationId: automation.id,+ });++ expect(response).toMatchObject({+ name: "Specific Automation",+ trigger: expect.objectContaining({+ id: trigger.id,+ }),+ action: expect.objectContaining({+ id: action.id,+ }),+ });++ // check that the action does not have a secret key in the config+ expect(response.action.config).not.toHaveProperty("secretKey");+ expect(response.action.config).toHaveProperty("displaySecretKey");+ expect(response.action.config.url).toBe("https://example.com/webhook");+ expect(response.action.config.headers).toEqual({+ "Content-Type": "application/json",+ });+ expect(response.action.config.apiVersion).toEqual({ prompt: "v1" });+ expect(response.action.config.type).toBe("WEBHOOK");+ expect(response.action.config.displaySecretKey).toBe(displaySecretKey);+ });++ it("should throw error when automation not found", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.automations.getAutomation({+ projectId: project.id,+ automationId: "non-existent-automation",+ }),+ ).rejects.toThrow(+ `Automation with id non-existent-automation not found.`,+ );+ });+ });++ describe("automations.createAutomation", () => {+ it("should create a new webhook automation", async () => {+ const { project, caller } = await prepare();++ // Create test prompt+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt",+ version: 1,+ type: "text",+ prompt: { text: "Hello world" },+ createdBy: "test-user",+ },+ });++ const response = await caller.automations.createAutomation({+ projectId: project.id,+ name: "New Webhook Automation",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "WEBHOOK",+ actionConfig: {+ type: "WEBHOOK",+ url: "https://example.com/new-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ });++ expect(response.trigger).toMatchObject({+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ status: JobConfigState.ACTIVE,+ });++ expect(response.action).toMatchObject({+ projectId: project.id,+ type: "WEBHOOK",+ config: expect.objectContaining({+ type: "WEBHOOK",+ url: "https://example.com/new-webhook",+ }),+ });++ expect(response.webhookSecret).toBeDefined();+ expect(typeof response.webhookSecret).toBe("string");++ // Verify the automation link was created+ const automation = await prisma.automation.findFirst({+ where: {+ triggerId: response.trigger.id,+ actionId: response.action.id,+ },+ });++ expect(automation).toMatchObject({+ name: "New Webhook Automation",+ });+ });++ it("should throw error when user lacks automations:CUD access", async () => {+ const { project, session } = await prepare();++ // Create a session with limited permissions+ const limitedSession: Session = {+ ...session,+ user: {+ ...session.user!,+ admin: false,+ organizations: [+ {+ ...session.user!.organizations[0],+ role: "MEMBER",+ projects: [+ {+ ...session.user!.organizations[0].projects[0],+ role: "VIEWER", // VIEWER role doesn't have automations:CUD scope+ },+ ],+ },+ ],+ },+ };++ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });++ await expect(+ limitedCaller.automations.createAutomation({+ projectId: project.id,+ name: "Unauthorized Automation",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "WEBHOOK",+ actionConfig: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: {},+ apiVersion: { prompt: "v1" },+ },+ }),+ ).rejects.toThrow("User does not have access to this resource or action");+ });++ it("should validate required fields", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.automations.createAutomation({+ projectId: project.id,+ name: "", // Empty name should fail+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "WEBHOOK",+ actionConfig: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: {},+ apiVersion: { prompt: "v1" },+ },+ }),+ ).rejects.toThrow("Name is required");+ });+ });++ describe("automations.updateAutomation", () => {+ it("should update an existing automation", async () => {+ const { project, caller } = await prepare();++ // Create initial automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Original Name",+ },+ });++ const response = await caller.automations.updateAutomation({+ projectId: project.id,+ automationId: automation.id,+ name: "Updated Name",+ eventSource: "prompt",+ eventAction: ["created", "updated"],+ filter: [],+ status: JobConfigState.INACTIVE,+ actionType: "WEBHOOK",+ actionConfig: {+ type: "WEBHOOK",+ url: "https://example.com/updated-webhook",+ headers: { "Content-Type": "application/json", "X-Custom": "value" },+ apiVersion: { prompt: "v1" },+ },+ });++ expect(response.trigger).toMatchObject({+ id: trigger.id,+ eventActions: ["created", "updated"],+ status: JobConfigState.INACTIVE,+ });++ expect(response.action.id).toBe(action.id);+ expect(response.action.type).toBe("WEBHOOK");+ expect(response.action.config).toMatchObject({+ type: "WEBHOOK",+ url: "https://example.com/updated-webhook",+ headers: {+ "Content-Type": "application/json",+ "X-Custom": "value",+ },+ });++ // Note: secretKey might be present in update response but shouldn't be in read operations+ // The important test is that it doesn't appear in getAutomations/getAutomation responses++ // Verify the automation name was updated+ const updatedAutomation = await prisma.automation.findFirst({+ where: {+ id: automation.id,+ },+ });++ expect(updatedAutomation?.name).toBe("Updated Name");+ });+ });++ describe("automations.deleteAutomation", () => {+ it("should delete an automation and all related data", async () => {+ const { project, caller } = await prepare();++ // Create automation with executions+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "To Be Deleted",+ },+ });++ // Create some executions+ await prisma.automationExecution.create({+ data: {+ id: v4(),+ automationId: automation.id,+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ status: ActionExecutionStatus.COMPLETED,+ sourceId: v4(),+ input: { test: "data" },+ },+ });++ await prisma.automationExecution.create({+ data: {+ id: v4(),+ automationId: automation.id,+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ status: ActionExecutionStatus.ERROR,+ sourceId: v4(),+ input: { test: "data" },+ error: "Test error",+ },+ });++ // Verify data exists before deletion+ const beforeTrigger = await prisma.trigger.findUnique({+ where: { id: trigger.id },+ });+ const beforeAction = await prisma.action.findUnique({+ where: { id: action.id },+ });+ const beforeExecutions = await prisma.automationExecution.findMany({+ where: { triggerId: trigger.id, actionId: action.id },+ });+ const beforeAutomation = await prisma.automation.findFirst({+ where: { id: automation.id },+ });++ expect(beforeTrigger).not.toBeNull();+ expect(beforeAction).not.toBeNull();+ expect(beforeExecutions).toHaveLength(2);+ expect(beforeAutomation).not.toBeNull();++ // Delete the automation+ await caller.automations.deleteAutomation({+ projectId: project.id,+ automationId: automation.id,+ });++ // Verify all data is deleted+ const afterTrigger = await prisma.trigger.findUnique({+ where: { id: trigger.id },+ });+ const afterAction = await prisma.action.findUnique({+ where: { id: action.id },+ });+ const afterExecutions = await prisma.automationExecution.findMany({+ where: { triggerId: trigger.id, actionId: action.id },+ });+ const afterAutomation = await prisma.automation.findFirst({+ where: { id: automation.id },+ });++ expect(afterTrigger).toBeNull();+ expect(afterAction).toBeNull();+ expect(afterExecutions).toHaveLength(0);+ expect(afterAutomation).toBeNull();+ });+ });++ describe("automations.getAutomationExecutions", () => {+ it("should retrieve execution history with pagination", async () => {+ const { project, caller } = await prepare();++ // Create automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Test Automation",+ },+ });++ // Create multiple executions+ const executions = [];+ for (let i = 0; i < 5; i++) {+ const execution = await prisma.automationExecution.create({+ data: {+ id: v4(),+ automationId: automation.id,+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ status:+ i % 2 === 0+ ? ActionExecutionStatus.COMPLETED+ : ActionExecutionStatus.ERROR,+ sourceId: v4(),+ input: { iteration: i },+ output: i % 2 === 0 ? { result: "success" } : undefined,+ error: i % 2 === 1 ? `Error ${i}` : null,+ },+ });+ executions.push(execution);+ }++ const response = await caller.automations.getAutomationExecutions({+ projectId: project.id,+ automationId: automation.id,+ page: 0,+ limit: 3,+ });++ expect(response.executions).toHaveLength(3);+ expect(response.totalCount).toBe(5);+ expect(response.executions[0].createdAt.getTime()).toBeGreaterThanOrEqual(+ response.executions[1].createdAt.getTime(),+ ); // Should be ordered by createdAt desc+ });++ it("should handle pagination correctly", async () => {+ const { project, caller } = await prepare();++ // Create automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Test Automation",+ },+ });++ // Create 10 executions+ for (let i = 0; i < 10; i++) {+ await prisma.automationExecution.create({+ data: {+ id: v4(),+ automationId: automation.id,+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ status: ActionExecutionStatus.COMPLETED,+ sourceId: v4(),+ input: { iteration: i },+ },+ });+ }++ // Test first page+ const page1 = await caller.automations.getAutomationExecutions({+ projectId: project.id,+ automationId: automation.id,+ page: 0,+ limit: 5,+ });++ expect(page1.executions).toHaveLength(5);+ expect(page1.totalCount).toBe(10);++ // Test second page+ const page2 = await caller.automations.getAutomationExecutions({+ projectId: project.id,+ automationId: automation.id,+ page: 1,+ limit: 5,+ });++ expect(page2.executions).toHaveLength(5);+ expect(page2.totalCount).toBe(10);++ // Verify different executions+ const page1Ids = page1.executions.map((e) => e.id);+ const page2Ids = page2.executions.map((e) => e.id);+ expect(page1Ids).not.toEqual(page2Ids);+ });+ });++ describe("automations.getCountOfConsecutiveFailures", () => {+ it("should return consecutive failure count", async () => {+ const { project, caller } = await prepare();++ // Create automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.INACTIVE, // Disabled due to failures+ },+ });++ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Test Automation",+ },+ });++ // Create consecutive failed executions+ for (let i = 0; i < 3; i++) {+ await prisma.automationExecution.create({+ data: {+ id: v4(),+ automationId: automation.id,+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ status: ActionExecutionStatus.ERROR,+ sourceId: v4(),+ input: { iteration: i },+ error: `Failure ${i}`,+ createdAt: new Date(Date.now() - (3 - i) * 60000), // Space them out+ },+ });+ }++ const response = await caller.automations.getCountOfConsecutiveFailures({+ projectId: project.id,+ automationId: automation.id,+ });++ expect(response.count).toBe(3);+ });+ });++ describe("automations.regenerateWebhookSecret", () => {+ it("should regenerate webhook secret for existing action", async () => {+ const { project, caller } = await prepare();++ // Create webhook action+ const {+ secretKey: originalSecretKey,+ displaySecretKey: originalDisplaySecretKey,+ } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(originalSecretKey),+ displaySecretKey: originalDisplaySecretKey,+ },+ },+ });++ const response = await caller.automations.regenerateWebhookSecret({+ projectId: project.id,+ actionId: action.id,+ });++ expect(response.webhookSecret).toBeDefined();+ expect(response.displaySecretKey).toBeDefined();+ expect(response.webhookSecret).not.toBe(originalSecretKey);+ expect(response.displaySecretKey).not.toBe(originalDisplaySecretKey);+ expect(response.displaySecretKey).toMatch(/^lf-whsec_\.\.\.[a-f0-9]{4}$/);++ // Verify the action was updated in the database+ const updatedAction = await prisma.action.findUnique({+ where: { id: action.id },+ });++ expect(updatedAction?.config).toMatchObject({+ displaySecretKey: response.displaySecretKey,+ });+ });++ it("should throw error when action not found", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.automations.regenerateWebhookSecret({+ projectId: project.id,+ actionId: "non-existent-action",+ }),+ ).rejects.toThrow(`Action with id non-existent-action not found.`);+ });++ it("should handle missing webhook action gracefully", async () => {+ const { project, caller } = await prepare();++ // Test with non-existent action ID - this will trigger the validation+ const actionId = v4();+ await expect(+ caller.automations.regenerateWebhookSecret({+ projectId: project.id,+ actionId,+ }),+ ).rejects.toThrow(`Action with id ${actionId} not found.`);+ });++ it("should throw error when user lacks automations:CUD access", async () => {+ const { project, session } = await prepare();++ // Create webhook action+ const { secretKey, displaySecretKey } = generateWebhookSecret();+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ // Create a session with limited permissions+ const limitedSession: Session = {+ ...session,+ user: {+ ...session.user!,+ admin: false,+ organizations: [+ {+ ...session.user!.organizations[0],+ role: "MEMBER",+ projects: [+ {+ ...session.user!.organizations[0].projects[0],+ role: "VIEWER", // VIEWER role doesn't have automations:CUD scope+ },+ ],+ },+ ],+ },+ };++ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });++ await expect(+ limitedCaller.automations.regenerateWebhookSecret({+ projectId: project.id,+ actionId: action.id,+ }),+ ).rejects.toThrow("User does not have access to this resource or action");+ });+ });+});diff --git a/web/src/__tests__/async/evals-trpc.servertest.ts b/web/src/__tests__/async/evals-trpc.servertest.tsindex 8c1273dbf4..b7b9ce5987 100644--- a/web/src/__tests__/async/evals-trpc.servertest.ts+++ b/web/src/__tests__/async/evals-trpc.servertest.ts@@ -25,6 +25,7 @@ async function prepare() {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},projects: [{id: project.id,@@ -32,6 +33,7 @@ async function prepare() {retentionDays: 30,deletedAt: null,name: project.name,+ metadata: {},},],},diff --git a/web/src/__tests__/async/prompts-trpc.servertest.ts b/web/src/__tests__/async/prompts-trpc.servertest.tsnew file mode 100644index 0000000000..e4ac368c7a--- /dev/null+++ b/web/src/__tests__/async/prompts-trpc.servertest.ts@@ -0,0 +1,620 @@+import { disconnectQueues } from "@/src/__tests__/test-utils";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import type { Session } from "next-auth";+import { v4 } from "uuid";+import waitForExpect from "wait-for-expect";++async function prepare() {+ const { project, org } = await createOrgProjectAndApiKey();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: org.id,+ name: org.name,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ projects: [+ {+ id: project.id,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: project.name,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: "cloud:hobby",+ },+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ return { project, org, session, ctx, caller };+}++describe("prompts trpc", () => {+ afterAll(async () => {+ await disconnectQueues();+ });+ describe("prompts.setLabels", () => {+ it("should set labels on a prompt and remove them from other versions", async () => {+ const { project, caller } = await prepare();++ // Create trigger for prompt updates+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["updated"],+ filter: [],+ status: "ACTIVE",+ },+ });++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-labels-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Labels Automation",+ },+ });++ // Create test prompts with different versions+ const prompt1 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt",+ version: 1,+ type: "text",+ prompt: { text: "Hello world v1" },+ createdBy: "test-user",+ labels: ["production"],+ },+ });++ const prompt2 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt",+ version: 2,+ type: "text",+ prompt: { text: "Hello world v2" },+ createdBy: "test-user",+ labels: ["latest"],+ },+ });++ // Set "production" label on prompt2, which should remove it from prompt1+ await caller.prompts.setLabels({+ projectId: project.id,+ promptId: prompt2.id,+ labels: ["production", "latest"],+ });++ // Verify that prompt1 no longer has the "production" label+ const updatedPrompt1 = await prisma.prompt.findUnique({+ where: { id: prompt1.id },+ });+ expect(updatedPrompt1?.labels).not.toContain("production");++ // Verify that prompt2 has both labels+ const updatedPrompt2 = await prisma.prompt.findUnique({+ where: { id: prompt2.id },+ });+ expect(updatedPrompt2?.labels).toEqual(+ expect.arrayContaining(["production", "latest"]),+ );++ await waitForExpect(async () => {+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ },+ });++ expect(executions).toHaveLength(2);+ expect(executions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ sourceId: prompt1.id,+ status: "PENDING",+ }),+ expect.objectContaining({+ sourceId: prompt2.id,+ status: "PENDING",+ }),+ ]),+ );+ });+ });+ });++ describe("prompts.updateTags", () => {+ it("should update tags on all versions of a prompt", async () => {+ const { project, caller } = await prepare();++ // Create trigger for prompt updates+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["updated"],+ filter: [],+ status: "ACTIVE",+ },+ });++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-labels-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Tags Automation",+ },+ });++ // Create test prompts with different versions but same name+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-tags",+ version: 1,+ type: "text",+ prompt: { text: "Hello world v1" },+ createdBy: "test-user",+ tags: ["old-tag"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-tags",+ version: 2,+ type: "text",+ prompt: { text: "Hello world v2" },+ createdBy: "test-user",+ tags: ["old-tag"],+ },+ });++ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-tags",+ version: 3,+ type: "text",+ prompt: { text: "Hello world v3" },+ createdBy: "test-user",+ tags: ["old-tag"],+ },+ });++ // Update tags for all versions of the prompt+ await caller.prompts.updateTags({+ projectId: project.id,+ name: "test-prompt-tags",+ tags: ["new-tag", "updated-tag"],+ });++ // Verify that all versions now have the new tags+ const updatedPrompts = await prisma.prompt.findMany({+ where: {+ projectId: project.id,+ name: "test-prompt-tags",+ },+ orderBy: { version: "asc" },+ });++ expect(updatedPrompts).toHaveLength(3);+ updatedPrompts.forEach((prompt) => {+ expect(prompt.tags).toEqual(+ expect.arrayContaining(["new-tag", "updated-tag"]),+ );+ expect(prompt.tags).not.toContain("old-tag");+ });++ await waitForExpect(async () => {+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ },+ });+ expect(executions).toHaveLength(3);+ expect(executions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ sourceId: updatedPrompts[0].id,+ status: "PENDING",+ }),+ expect.objectContaining({+ sourceId: updatedPrompts[1].id,+ status: "PENDING",+ }),+ expect.objectContaining({+ sourceId: updatedPrompts[2].id,+ status: "PENDING",+ }),+ ]),+ );+ });+ });+ });++ describe("prompts.delete", () => {+ it("should delete all versions of a prompt", async () => {+ const { project, caller } = await prepare();++ // Create trigger for prompt deletions+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["deleted"],+ filter: [],+ status: "ACTIVE",+ },+ });++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-delete-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Delete Automation",+ },+ });++ // Create test prompts with multiple versions+ const prompt1 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-delete",+ version: 1,+ type: "text",+ prompt: { text: "Hello world v1" },+ createdBy: "test-user",+ },+ });++ const prompt2 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-delete",+ version: 2,+ type: "text",+ prompt: { text: "Hello world v2" },+ createdBy: "test-user",+ },+ });++ // Delete all versions of the prompt+ await caller.prompts.delete({+ projectId: project.id,+ promptName: "test-prompt-delete",+ });++ // Verify prompts are deleted+ const remainingPrompts = await prisma.prompt.findMany({+ where: {+ projectId: project.id,+ name: "test-prompt-delete",+ },+ });+ expect(remainingPrompts).toHaveLength(0);+ await waitForExpect(async () => {+ // Verify automation executions were created for both deleted prompts+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ },+ });++ expect(executions).toHaveLength(2);+ expect(executions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ sourceId: prompt1.id,+ status: "PENDING",+ }),+ expect.objectContaining({+ sourceId: prompt2.id,+ status: "PENDING",+ }),+ ]),+ );+ });+ });+ });++ describe("prompts.deleteVersion", () => {+ it("should delete a specific version of a prompt", async () => {+ const { project, caller } = await prepare();++ // Create trigger for prompt deletions+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["deleted"],+ filter: [],+ status: "ACTIVE",+ },+ });++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-delete-version-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Delete Version Automation",+ },+ });++ // Create test prompts with multiple versions+ const prompt1 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-delete-version",+ version: 1,+ type: "text",+ prompt: { text: "Hello world v1" },+ createdBy: "test-user",+ },+ });++ const prompt2 = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt-delete-version",+ version: 2,+ type: "text",+ prompt: { text: "Hello world v2" },+ createdBy: "test-user",+ },+ });++ // Delete only version 1+ await caller.prompts.deleteVersion({+ projectId: project.id,+ promptVersionId: prompt1.id,+ });++ // Verify only version 1 is deleted+ const remainingPrompts = await prisma.prompt.findMany({+ where: {+ projectId: project.id,+ name: "test-prompt-delete-version",+ },+ });+ expect(remainingPrompts).toHaveLength(1);+ expect(remainingPrompts[0].id).toBe(prompt2.id);++ await waitForExpect(async () => {+ // Verify automation execution was created for the deleted prompt+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ },+ });++ expect(executions).toHaveLength(1);+ expect(executions[0]).toEqual(+ expect.objectContaining({+ sourceId: prompt1.id,+ status: "PENDING",+ }),+ );+ });+ });+ });++ describe("prompts.duplicatePrompt", () => {+ it("should duplicate a prompt and trigger webhook automation", async () => {+ const { project, caller } = await prepare();++ // Create trigger for prompt creation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: "ACTIVE",+ },+ });++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-duplicate-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Duplicate Automation",+ },+ });++ // Create original prompt to duplicate+ const originalPrompt = await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "original-prompt",+ version: 1,+ type: "text",+ prompt: "Hello world original",+ createdBy: "test-user",+ labels: ["production"],+ tags: ["original"],+ },+ });++ // Duplicate the prompt+ const duplicatedPrompt = await caller.prompts.duplicatePrompt({+ projectId: project.id,+ promptId: originalPrompt.id,+ name: "duplicated-prompt",+ isSingleVersion: true,+ });++ expect(duplicatedPrompt).toMatchObject({+ name: "duplicated-prompt",+ version: 1,+ type: "text",+ prompt: "Hello world original",+ labels: expect.arrayContaining(["production", "latest"]),+ tags: ["original"],+ });++ // Verify the duplicated prompt exists in database+ const dbPrompt = await prisma.prompt.findUnique({+ where: { id: duplicatedPrompt.id },+ });+ expect(dbPrompt).not.toBeNull();+ expect(dbPrompt?.name).toBe("duplicated-prompt");++ await waitForExpect(async () => {+ // Verify automation execution was created for the duplicated prompt+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ },+ });++ expect(executions).toHaveLength(1);+ expect(executions[0]).toEqual(+ expect.objectContaining({+ sourceId: duplicatedPrompt.id,+ status: "PENDING",+ }),+ );+ });+ });+ });+});diff --git a/web/src/__tests__/async/prompts.v2.servertest.ts b/web/src/__tests__/async/prompts.v2.servertest.tsindex f29e591f24..f88c432454 100644--- a/web/src/__tests__/async/prompts.v2.servertest.ts+++ b/web/src/__tests__/async/prompts.v2.servertest.ts@@ -1,14 +1,14 @@/** @jest-environment node */import { prisma } from "@langfuse/shared/src/db";-import { makeAPICall } from "@/src/__tests__/test-utils";+import { disconnectQueues, makeAPICall } from "@/src/__tests__/test-utils";import { v4 as uuidv4, v4 } from "uuid";import {PromptSchema,- PromptType,type ValidatedPrompt,type ChatMessage,type Prompt,+ PromptType,} from "@langfuse/shared";import { parsePromptDependencyTags } from "@langfuse/shared";import { generateId, nanoid } from "ai";@@ -21,6 +21,7 @@ import {ChatMessageType,} from "@langfuse/shared/src/server";import { randomUUID } from "node:crypto";+import waitForExpect from "wait-for-expect";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const baseURI = "/api/public/v2/prompts";@@ -39,6 +40,7 @@ type CreatePromptInDBParams = {createdAt?: Date;updatedAt?: Date;};+const createPromptInDB = async (params: CreatePromptInDBParams) => {return await prisma.prompt.create({data: {@@ -60,6 +62,50 @@ const createPromptInDB = async (params: CreatePromptInDBParams) => {});};+const setupTriggerAndAction = async (projectId: string) => {+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: projectId,+ eventSource: "prompt",+ eventActions: ["updated"],+ filter: [],+ status: "ACTIVE",+ },+ });+ trigger.id;++ // Create webhook action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: projectId,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/prompt-labels-webhook",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ },+ },+ });+ action.id;++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: projectId,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Prompt Labels Automation",+ },+ });+ return {+ actionId: action.id,+ triggerId: trigger.id,+ };+};+const testPromptEquality = (promptParams: CreatePromptInDBParams,prompt: Prompt,@@ -79,6 +125,9 @@ const testPromptEquality = (};describe("/api/public/v2/prompts API Endpoint", () => {+ afterAll(async () => {+ await disconnectQueues();+ });describe("when fetching a prompt", () => {it("should return a 401 if key is invalid", async () => {const projectId = uuidv4();@@ -423,21 +472,22 @@ describe("/api/public/v2/prompts API Endpoint", () => {expect(response.status).toBe(207);// Delay to allow for async processing- await new Promise((resolve) => setTimeout(resolve, 500));-- const dbGeneration = await getObservationById({- id: generationId,- projectId,- });+ await waitForExpect(async () => {+ const dbGeneration = await getObservationById({+ id: generationId,+ projectId,+ });- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.promptId).toBe(promptId);- });+ expect(dbGeneration?.id).toBe(generationId);+ expect(dbGeneration?.promptId).toBe(promptId);+ }, 8000);+ }, 10000);});describe("when creating a prompt", () => {it("should create and fetch a chat prompt", async () => {- const { auth } = await createOrgProjectAndApiKey();+ const { auth, projectId } = await createOrgProjectAndApiKey();+ const { actionId, triggerId } = await setupTriggerAndAction(projectId);const promptName = "prompt-name" + nanoid();const chatMessages = [{ role: "system", content: "You are a bot" },@@ -475,7 +525,21 @@ describe("/api/public/v2/prompts API Endpoint", () => {expect(validatedPrompt.createdBy).toBe("API");expect(validatedPrompt.config).toEqual({});expect(validatedPrompt.commitMessage).toBe("chore: setup initial prompt");- });++ await waitForExpect(async () => {+ // check that the action execution is created+ const actionExecution = await prisma.automationExecution.findFirst({+ where: {+ projectId,+ triggerId,+ actionId,+ },+ });+ expect(actionExecution).not.toBeNull();+ expect(actionExecution?.status).toBe("PENDING");+ expect(actionExecution?.sourceId).toBe(validatedPrompt.id);+ });+ }, 10000);it("should create and fetch a chat prompt with message placeholders", async () => {const { auth } = await createOrgProjectAndApiKey();@@ -1539,10 +1603,20 @@ describe("/api/public/v2/prompts API Endpoint", () => {});describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {+ let triggerId: string;+ let actionId: string;++ afterAll(async () => {+ await disconnectQueues();+ });+it("should update the labels of a prompt", async () => {const { projectId: newProjectId, auth: newAuth } =await createOrgProjectAndApiKey();+ const { actionId: newActionId, triggerId: newTriggerId } =+ await setupTriggerAndAction(newProjectId);+const originalPrompt = await prisma.prompt.create({data: {name: "prompt-1",@@ -1573,12 +1647,31 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {expect(updatedPrompt?.labels).toContain("production");expect(updatedPrompt?.labels).toContain("new-label");expect(updatedPrompt?.labels).toHaveLength(2);++ // check that the action execution is created+ await waitForExpect(async () => {+ const actionExecution = await prisma.automationExecution.findFirst({+ where: {+ projectId: newProjectId,+ triggerId: newTriggerId,+ actionId: newActionId,+ },+ });+ expect(actionExecution).not.toBeNull();+ expect(actionExecution?.status).toBe("PENDING");+ expect(actionExecution?.sourceId).toBe(originalPrompt.id);+ });});it("should remove label from previous version when adding to new version", async () => {const { projectId: newProjectId, auth: newAuth } =await createOrgProjectAndApiKey();+ const { actionId: newActionId, triggerId: newTriggerId } =+ await setupTriggerAndAction(newProjectId);+ actionId = newActionId;+ triggerId = newTriggerId;+// Create version 1 with "production" labelawait prisma.prompt.create({data: {@@ -1636,6 +1729,32 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {},});expect(promptV1?.labels).toEqual([]);++ await waitForExpect(async () => {+ const actionExecution = await prisma.automationExecution.findFirst({+ where: {+ projectId: newProjectId,+ triggerId,+ actionId,+ sourceId: promptV2?.id,+ },+ });+ expect(actionExecution).not.toBeNull();+ expect(actionExecution?.status).toBe("PENDING");+ expect(actionExecution?.sourceId).toBe(promptV2?.id);++ const actionExecution2 = await prisma.automationExecution.findFirst({+ where: {+ projectId: newProjectId,+ triggerId,+ actionId,+ sourceId: promptV1?.id,+ },+ });+ expect(actionExecution2).not.toBeNull();+ expect(actionExecution2?.status).toBe("PENDING");+ expect(actionExecution2?.sourceId).toBe(promptV1?.id);+ });});it("trying to set 'latest' label results in 400 error", async () => {diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 8db758025e..827a4ddfd2 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -148,8 +148,8 @@ describe("/api/public/traces API Endpoint", () => {expect(trace.version).toBe("2.0.0");expect(trace.projectId).toBe(projectId);expect(trace.latency).toBe(100);- expect(trace.observations.length).toBe(2);- expect(trace.scores.length).toBe(0);+ expect(trace.observations?.length).toBe(2);+ expect(trace.scores?.length).toBe(0);expect(trace.timestamp).toBe(timestamp.toISOString());});@@ -242,8 +242,8 @@ describe("/api/public/traces API Endpoint", () => {expect(traces.body.data.length).toBe(1);const trace = traces.body.data[0];expect(trace.projectId).toBe(projectId);- expect(trace.observations.length).toBe(1);- expect(trace.scores.length).toBe(1);+ expect(trace.observations?.length).toBe(1);+ expect(trace.scores?.length).toBe(1);});it("should fetch traces with trace scores only", async () => {@@ -302,9 +302,9 @@ describe("/api/public/traces API Endpoint", () => {expect(traces.body.data.length).toBe(1);const trace = traces.body.data[0];expect(trace.projectId).toBe(projectId);- expect(trace.observations.length).toBe(1);+ expect(trace.observations?.length).toBe(1);// Despite having the correct environment, the session score is not included in the response- expect(trace.scores.length).toBe(1);+ expect(trace.scores?.length).toBe(1);});it("should fetch all traces filtered by a tag", async () => {diff --git a/web/src/__tests__/prompts.v1.servertest.ts b/web/src/__tests__/prompts.v1.servertest.tsindex 046dc8304c..ff529e15eb 100644--- a/web/src/__tests__/prompts.v1.servertest.ts+++ b/web/src/__tests__/prompts.v1.servertest.ts@@ -3,10 +3,10 @@import { prisma } from "@langfuse/shared/src/db";import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";import { v4 as uuidv4, v4 } from "uuid";-import { type Prompt } from "@langfuse/shared";+import { type Prompt, PromptType, } from "@langfuse/shared";import {LegacyPromptSchema,- PromptType,+type LegacyValidatedPrompt,} from "@langfuse/shared";import { getObservationById } from "@langfuse/shared/src/server";diff --git a/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts b/web/src/__tests__/server/api/tables/prompts-ui.servertest.tsindex 4a00012d68..0d09b8537d 100644--- a/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts+++ b/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts@@ -1,4 +1,7 @@-import { createObservationsCh } from "@langfuse/shared/src/server";+import {+ createObservation,+ createObservationsCh,+} from "@langfuse/shared/src/server";import { pruneDatabase } from "@/src/__tests__/test-utils";import {getObservationMetricsForPrompts,@@ -14,7 +17,7 @@ describe("UI Prompts Table", () => {});it("should count the observations which belong to a prompt", async () => {- const observation = {+ const observation = createObservation({id: v4(),project_id: projectId,trace_id: v4(),@@ -51,7 +54,7 @@ describe("UI Prompts Table", () => {prompt_version: 1,end_time: Date.now(),completion_start_time: Date.now(),- };+ });const secondObservation = {...observation,@@ -89,7 +92,7 @@ describe("UI Prompts Table", () => {});it("should correctly calculate prompt metrics", async () => {- const observation = {+ const observation = createObservation({id: v4(),project_id: projectId,trace_id: v4(),@@ -126,20 +129,20 @@ describe("UI Prompts Table", () => {prompt_id: "some-prompt-id",end_time: Date.now(),completion_start_time: Date.now(),- };+ });- const secondObservation = {+ const secondObservation = createObservation({...observation,id: v4(),prompt_version: 2,usage_details: { input: 42, output: 5654 },- };- const thirdObservation = {+ });+ const thirdObservation = createObservation({...observation,id: v4(),prompt_version: 2,cost_details: { input: 234, output: 755 },- };+ });await createObservationsCh([observation,secondObservation,diff --git a/web/src/__tests__/teardown.ts b/web/src/__tests__/teardown.tsindex 9a9eac7e5b..3399e4c273 100644--- a/web/src/__tests__/teardown.ts+++ b/web/src/__tests__/teardown.ts@@ -1,5 +1,6 @@export default async function teardown() {const { redis, logger } = await import("@langfuse/shared/src/server");+logger.debug(`Redis status ${redis?.status}`);if (!redis) {return;diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex c4026bad35..57cdef1eb1 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -3,6 +3,10 @@ import { prisma } from "@langfuse/shared/src/db";import {clickhouseClient,createBasicAuthHeader,+ getQueue,+ IngestionQueue,+ logger,+ QueueName,} from "@langfuse/shared/src/server";import { type z } from "zod/v4";@@ -76,7 +80,6 @@ export const ensureTestDatabaseExists = async () => {// ClickHouse uses default database (no setup needed)};-export const pruneDatabase = async () => {if (!env.DATABASE_URL.includes("localhost:5432")) {throw new Error("You cannot prune database unless running on localhost.");@@ -96,6 +99,41 @@ export const pruneDatabase = async () => {await truncateClickhouseTables();};+export const getQueues = () => {+ const queues: string[] = Object.values(QueueName);+ queues.push(...IngestionQueue.getShardNames());++ const listOfQueuesToIgnore = [+ QueueName.DataRetentionQueue,+ QueueName.BlobStorageIntegrationQueue,+ QueueName.DeadLetterRetryQueue,+ QueueName.PostHogIntegrationQueue,+ ];++ return queues+ .filter(+ (queueName) => !listOfQueuesToIgnore.includes(queueName as QueueName),+ )+ .map((queueName) =>+ queueName.startsWith(QueueName.IngestionQueue)+ ? IngestionQueue.getInstance({ shardName: queueName })+ : getQueue(queueName as Exclude<QueueName, QueueName.IngestionQueue>),+ );+};++export const disconnectQueues = async () => {+ await Promise.all(+ getQueues().map(async (queue) => {+ if (queue) {+ try {+ queue.disconnect();+ } catch (error) {+ logger.error(`Error disconnecting queue ${queue.name}: ${error}`);+ }+ }+ }),+ );+};export const truncateClickhouseTables = async () => {if (!env.CLICKHOUSE_URL?.includes("localhost:8123")) {diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex 98ef27072a..6a7a5cc9d5 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -41,9 +41,17 @@ export function JSONView(props: {? 100_000_000 // if null, show all (100M chars): (props.collapseStringsAfterLength ?? 500);- const handleOnCopy = () => {+ const handleOnCopy = (event?: React.MouseEvent<HTMLButtonElement>) => {+ if (event) {+ event.preventDefault();+ }const textToCopy = stringifyJsonNode(parsedJson);void copyTextToClipboard(textToCopy);++ // Keep focus on the copy button to prevent focus shifting+ if (event) {+ event.currentTarget.focus();+ }};const handleOnValueChange = () => {@@ -158,7 +166,8 @@ export function CodeView(props: {const [isCopied, setIsCopied] = useState(false);const [isCollapsed, setCollapsed] = useState(props.defaultCollapsed);- const handleCopy = () => {+ const handleCopy = (event: React.MouseEvent<HTMLButtonElement>) => {+ event.preventDefault();setIsCopied(true);const content =typeof props.content === "string"@@ -166,6 +175,9 @@ export function CodeView(props: {: (props.content?.join("\n") ?? "");void copyTextToClipboard(content);setTimeout(() => setIsCopied(false), 1000);++ // Keep focus on the copy button to prevent focus shifting+ event.currentTarget.focus();};const handleShowAll = () => setCollapsed(!isCollapsed);@@ -178,9 +190,9 @@ export function CodeView(props: {props.scrollable && "max-h-full min-h-0",)}>- <div className="my-1 flex flex-shrink-0 items-center justify-between pl-1">+ <>{props.title ? (- <>+ <div className="my-1 flex flex-shrink-0 items-center justify-between pl-1"><div className="text-sm font-medium">{props.title}</div><Buttonvariant="ghost"@@ -194,9 +206,9 @@ export function CodeView(props: {<Copy className="h-3 w-3" />)}</Button>- </>+ </div>) : undefined}- </div>+ </><divclassName={cn("relative flex flex-col gap-2 rounded-md border",diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsxindex 7a99970bb7..5ab1c3bb7c 100644--- a/web/src/components/ui/MarkdownJsonView.tsx+++ b/web/src/components/ui/MarkdownJsonView.tsx@@ -17,7 +17,7 @@ import { cn } from "@/src/utils/tailwind";type MarkdownJsonViewHeaderProps = {title: string;handleOnValueChange: () => void;- handleOnCopy: () => void;+ handleOnCopy: (event?: React.MouseEvent<HTMLButtonElement>) => void;canEnableMarkdown?: boolean;controlButtons?: React.ReactNode;};@@ -57,9 +57,9 @@ export function MarkdownJsonViewHeader({variant="ghost"size="icon-xs"type="button"- onClick={() => {+ onClick={(event) => {setIsCopied(true);- handleOnCopy();+ handleOnCopy(event);setTimeout(() => setIsCopied(false), 1000);}}className="-mr-2 hover:bg-border"diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex aa1e8e7763..763f49e062 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -33,6 +33,8 @@ export type AuditableResource =| "batchExport"| "stripeCheckoutSession"| "batchAction"+ | "automation"+ | "action"// legacy resources| "membership";diff --git a/web/src/features/automations/components/AutomationDetails.tsx b/web/src/features/automations/components/AutomationDetails.tsxnew file mode 100644index 0000000000..def72fdd41--- /dev/null+++ b/web/src/features/automations/components/AutomationDetails.tsx@@ -0,0 +1,182 @@+import React, { useState } from "react";+import { api } from "@/src/utils/api";+import { Button } from "@/src/components/ui/button";+import { Edit } from "lucide-react";+import { AutomationForm } from "./automationForm";+import { AutomationExecutionsTable } from "./AutomationExecutionsTable";+import { AutomationFailureBanner } from "./AutomationFailureBanner";+import {+ type AutomationDomain,+ JobConfigState,+ type TriggerEventSource,+} from "@langfuse/shared";+import {+ TabsBar,+ TabsBarContent,+ TabsBarList,+ TabsBarTrigger,+} from "@/src/components/ui/tabs-bar";+import { type FilterState } from "@langfuse/shared";+import Header from "@/src/components/layouts/header";+import { SettingsTableCard } from "@/src/components/layouts/settings-table-card";+import { DeleteAutomationButton } from "./DeleteAutomationButton";+import { useQueryParam, StringParam, withDefault } from "use-query-params";++interface AutomationDetailsProps {+ projectId: string;+ automationId: string;+ onEditSuccess?: () => void;+ onEdit?: (automation: AutomationDomain) => void;+ onDelete?: () => void;+}++export const AutomationDetails: React.FC<AutomationDetailsProps> = ({+ projectId,+ automationId,+ onEditSuccess,+ onEdit,+ onDelete,+}) => {+ const [isEditing, setIsEditing] = useState(false);+ const [activeTab, setActiveTab] = useQueryParam(+ "tab",+ withDefault(StringParam, "executions"),+ );++ const { data: automation, isLoading } =+ api.automations.getAutomation.useQuery(+ {+ projectId,+ automationId,+ },+ {+ enabled: !!projectId && !!automationId,+ },+ );++ const handleEdit = () => {+ if (onEdit && automation) {+ onEdit(automation);+ } else {+ setIsEditing(true);+ }+ };++ const handleCancelEdit = () => {+ setIsEditing(false);+ };++ const handleSaveEdit = () => {+ setIsEditing(false);+ onEditSuccess?.();+ };++ if (isLoading) {+ return <div className="py-4 text-center">Loading webhook details...</div>;+ }++ if (!automation) {+ return (+ <div className="py-4 text-center text-muted-foreground">+ Webhook not found.+ </div>+ );+ }++ const automationForForm: AutomationDomain = {+ id: automation.id,+ name: automation.name,+ trigger: {+ ...automation.trigger,+ eventSource: automation.trigger.eventSource as TriggerEventSource,+ filter: automation.trigger.filter as FilterState,+ eventActions: automation.trigger.eventActions,+ },+ action: {+ ...automation.action,+ config: automation.action.config as {+ type: "WEBHOOK";+ url: string;+ headers: Record<string, string>;+ apiVersion: Record<"prompt", "v1">;+ displaySecretKey: string;+ },+ },+ };++ return (+ <div className="flex flex-col gap-6">+ {isEditing ? (+ <AutomationForm+ projectId={projectId}+ onSuccess={handleSaveEdit}+ onCancel={handleCancelEdit}+ automation={automationForForm}+ isEditing={true}+ />+ ) : (+ <>+ <Header+ title={automation.name}+ status={+ automation.trigger.status === JobConfigState.ACTIVE+ ? "active"+ : "inactive"+ }+ actionButtons={+ <div className="flex gap-2">+ <Button variant="outline" onClick={handleEdit}>+ <Edit className="mr-2 h-4 w-4" />+ Edit+ </Button>+ <DeleteAutomationButton+ projectId={projectId}+ automationId={automationId}+ variant="button"+ onSuccess={onDelete}+ />+ </div>+ }+ />++ <AutomationFailureBanner+ projectId={projectId}+ automationId={automationId}+ />++ <TabsBar+ value={activeTab}+ onValueChange={setActiveTab}+ className="w-full"+ >+ <TabsBarList>+ <TabsBarTrigger value="executions">+ Execution History+ </TabsBarTrigger>+ <TabsBarTrigger value="configuration">+ Configuration+ </TabsBarTrigger>+ </TabsBarList>++ <TabsBarContent value="executions" className="mt-6">+ <SettingsTableCard>+ <AutomationExecutionsTable+ projectId={projectId}+ automationId={automationId}+ />+ </SettingsTableCard>+ </TabsBarContent>++ <TabsBarContent value="configuration" className="mt-6">+ <AutomationForm+ projectId={projectId}+ automation={automationForForm}+ isEditing={false}+ />+ </TabsBarContent>+ </TabsBar>+ </>+ )}+ </div>+ );+};diff --git a/web/src/features/automations/components/AutomationExecutionsTable.tsx b/web/src/features/automations/components/AutomationExecutionsTable.tsxnew file mode 100644index 0000000000..fe0b0c91e6--- /dev/null+++ b/web/src/features/automations/components/AutomationExecutionsTable.tsx@@ -0,0 +1,179 @@+import React from "react";+import { api } from "@/src/utils/api";+import { DataTable } from "@/src/components/table/data-table";+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { StatusBadge } from "@/src/components/layouts/status-badge";+import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";+import { useQueryParams, withDefault, NumberParam } from "use-query-params";+import { formatDistanceToNow } from "date-fns";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";++type ActionExecutionRow = {+ id: string;+ status: string;+ sourceId: string;+ input: any;+ output: any;+ error: string | null;+ createdAt: string;+ startedAt: string | null;+ duration: number | null;+};++interface AutomationExecutionsTableProps {+ projectId: string;+ automationId: string;+}++export const AutomationExecutionsTable: React.FC<+ AutomationExecutionsTableProps+> = ({ projectId, automationId }) => {+ const [paginationState, setPaginationState] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });++ const [rowHeight, setRowHeight] = useRowHeightLocalStorage(+ "automation-executions",+ "s",+ );++ const { data, isLoading, isError, error } =+ api.automations.getAutomationExecutions.useQuery({+ projectId,+ automationId,+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ });++ const columns: LangfuseColumnDef<ActionExecutionRow>[] = [+ {+ accessorKey: "status",+ header: "Status",+ id: "status",+ cell: ({ row }) => {+ const status = row.getValue("status") as string;+ return <StatusBadge type={status.toLowerCase()} />;+ },+ },+ {+ accessorKey: "startedAt",+ header: "Started",+ id: "startedAt",+ cell: ({ row }) => {+ const value = row.getValue("startedAt") as string | null;+ if (!value) return <span className="text-muted-foreground">-</span>;+ const date = new Date(value);+ return (+ <div className="flex flex-col">+ <span className="text-xs">+ {formatDistanceToNow(date, { addSuffix: true })}+ </span>+ <span className="text-xs text-muted-foreground">+ {date.toLocaleString()}+ </span>+ </div>+ );+ },+ },+ {+ accessorKey: "duration",+ header: "Duration",+ id: "duration",+ cell: ({ row }) => {+ const duration = row.getValue("duration") as number | null;+ if (!duration) return <span className="text-muted-foreground">-</span>;+ return (+ <span className="text-nowrap">{formatIntervalSeconds(duration)}</span>+ );+ },+ },+ {+ accessorKey: "input",+ header: "Input",+ id: "input",+ cell: ({ row }) => {+ const value = row.getValue("input");+ return <IOTableCell data={value} />;+ },+ },+ {+ accessorKey: "output",+ header: "Output",+ id: "output",+ cell: ({ row }) => {+ const value = row.getValue("output");+ if (!value) return <span className="text-muted-foreground">-</span>;+ return <IOTableCell data={value} />;+ },+ },+ {+ accessorKey: "error",+ header: "Error",+ id: "error",+ cell: ({ row }) => {+ const value = row.getValue("error") as string | null;+ if (!value) return <span className="text-muted-foreground">-</span>;+ return (+ <div className="max-w-xs">+ <span className="break-words text-xs text-red-600">{value}</span>+ </div>+ );+ },+ },+ ];++ const rows: ActionExecutionRow[] = React.useMemo(() => {+ return (+ data?.executions.map((execution) => ({+ id: execution.id,+ status: execution.status,+ sourceId: execution.sourceId,+ input: execution.input,+ output: execution.output,+ error: execution.error,+ createdAt: execution.createdAt.toISOString(),+ startedAt: execution.startedAt?.toISOString() || null,+ duration: execution.finishedAt+ ? (execution.finishedAt.getTime() -+ (execution.startedAt?.getTime() ?? 0)) /+ 1000+ : null,+ })) || []+ );+ }, [data]);++ if (isError) {+ return (+ <div className="py-4 text-center text-red-600">+ Error loading execution history: {error?.message}+ </div>+ );+ }++ return (+ <>+ <DataTableToolbar+ columns={columns}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ />+ <DataTable+ columns={columns}+ data={{+ isLoading,+ isError,+ data: rows,+ }}+ pagination={{+ totalCount: data?.totalCount ?? 0,+ onChange: setPaginationState,+ state: paginationState,+ }}+ rowHeight={rowHeight}+ />+ </>+ );+};diff --git a/web/src/features/automations/components/AutomationFailureBanner.tsx b/web/src/features/automations/components/AutomationFailureBanner.tsxnew file mode 100644index 0000000000..d080663e90--- /dev/null+++ b/web/src/features/automations/components/AutomationFailureBanner.tsx@@ -0,0 +1,52 @@+import React from "react";+import { AlertTriangle, X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Alert, AlertDescription } from "@/src/components/ui/alert";+import { api } from "@/src/utils/api";++interface AutomationFailureBannerProps {+ projectId: string;+ automationId: string;+}++export const AutomationFailureBanner: React.FC<+ AutomationFailureBannerProps+> = ({ projectId, automationId }) => {+ const [dismissed, setDismissed] = React.useState(false);++ const { data: failureData } =+ api.automations.getCountOfConsecutiveFailures.useQuery({+ projectId,+ automationId,+ });++ if (dismissed || !failureData || failureData.count < 5) {+ return null;+ }++ return (+ <Alert variant="destructive" className="mb-4">+ <AlertTriangle className="h-4 w-4" />+ <AlertDescription className="flex items-center justify-between">+ <div className="flex-1">+ <strong>+ This automation was automatically disabled due to at least{" "}+ {failureData.count} consecutive webhook failures.+ </strong>+ <div className="mt-2 text-sm">+ Check the execution history below, fix any issues with your webhook+ endpoint, then reactivate the automation.+ </div>+ </div>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setDismissed(true)}+ className="ml-4 h-6 w-6 p-0"+ >+ <X className="h-4 w-4" />+ </Button>+ </AlertDescription>+ </Alert>+ );+};diff --git a/web/src/features/automations/components/AutomationSidebar.tsx b/web/src/features/automations/components/AutomationSidebar.tsxnew file mode 100644index 0000000000..d2c744a608--- /dev/null+++ b/web/src/features/automations/components/AutomationSidebar.tsx@@ -0,0 +1,117 @@+import React from "react";+import { api } from "@/src/utils/api";+import { JobConfigState, type AutomationDomain } from "@langfuse/shared";+import { cn } from "@/src/utils/tailwind";+import { StatusBadge } from "@/src/components/layouts/status-badge";++interface AutomationSidebarProps {+ projectId: string;+ selectedAutomation?: { automationId: string };+ onAutomationSelect: (automation: AutomationDomain) => void;+}++export const AutomationSidebar: React.FC<AutomationSidebarProps> = ({+ projectId,+ selectedAutomation,+ onAutomationSelect,+}) => {+ const { data: automations, isLoading } =+ api.automations.getAutomations.useQuery({+ projectId,+ });++ const sidebarWidth = "w-40 sm:w-64";++ if (isLoading) {+ return (+ <div+ className={cn(+ "flex h-full flex-col border-r bg-muted/10",+ sidebarWidth,+ )}+ >+ <div className="p-4 text-center text-sm text-muted-foreground">+ Loading webhooks...+ </div>+ </div>+ );+ }++ if (!automations || automations.length === 0) {+ return (+ <div+ className={cn(+ "flex h-full flex-col border-r bg-muted/10",+ sidebarWidth,+ )}+ >+ <div className="p-4 text-center text-sm text-muted-foreground">+ No webhooks configured. Create your first webhook to automate+ workflows.+ </div>+ </div>+ );+ }++ return (+ <div+ className={cn(+ "flex min-h-[60vh] flex-col border-r bg-muted/10",+ sidebarWidth,+ )}+ >+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="px-4 pt-4">+ <div className="space-y-2">+ {automations.map((automation) => {+ const isSelected =+ selectedAutomation?.automationId === automation.id;++ return (+ <div+ key={automation.id}+ className={cn(+ "group relative rounded-lg border p-3 transition-colors hover:bg-background/50",+ isSelected+ ? "border-primary bg-primary/5"+ : "border-border bg-background/20",+ )}+ >+ <div+ className="cursor-pointer"+ onClick={() => onAutomationSelect(automation)}+ >+ <div className="space-y-2">+ {/* Top row: Name and Active badge */}+ <div className="flex items-center justify-between gap-2">+ <h4 className="truncate text-sm font-medium leading-tight">+ {automation.name}+ </h4>+ {automation.trigger.status === JobConfigState.ACTIVE ? (+ <StatusBadge type={"active"} />+ ) : (+ <StatusBadge type={"inactive"} />+ )}+ </div>++ {/* Bottom row: eventSource -> automation type */}+ <p className="text-xs text-muted-foreground">+ <span className="font-mono">+ {automation.trigger.eventSource}+ </span>+ {" → "}+ {automation.action.type === "WEBHOOK"+ ? "Webhook"+ : "Annotation Queue"}+ </p>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/web/src/features/automations/components/DeleteAutomationButton.tsx b/web/src/features/automations/components/DeleteAutomationButton.tsxnew file mode 100644index 0000000000..782f719521--- /dev/null+++ b/web/src/features/automations/components/DeleteAutomationButton.tsx@@ -0,0 +1,99 @@+import { useState } from "react";+import { Button } from "@/src/components/ui/button";+import { Trash } from "lucide-react";+import { api } from "@/src/utils/api";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";++interface DeleteAutomationButtonProps {+ projectId: string;+ automationId: string;+ onSuccess?: () => void;+ variant?: "icon" | "button"; // "icon" for list view, "button" for form view+}++export const DeleteAutomationButton: React.FC<DeleteAutomationButtonProps> = ({+ projectId,+ automationId,+ onSuccess,+ variant = "icon",+}) => {+ const [isOpen, setIsOpen] = useState(false);+ const utils = api.useUtils();+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "automations:CUD",+ });++ const deleteAutomationMutation = api.automations.deleteAutomation.useMutation(+ {+ onSuccess: () => {+ showSuccessToast({+ title: "Automation deleted",+ description: "The automation has been deleted successfully.",+ });++ if (onSuccess) {+ onSuccess();+ }++ void utils.automations.invalidate();+ },+ },+ );++ return (+ <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>+ <PopoverTrigger asChild>+ {variant === "icon" ? (+ <Button+ variant="ghost"+ size="sm"+ className="h-8 w-8 p-0"+ disabled={!hasAccess}+ >+ <Trash className="h-4 w-4" />+ <span className="sr-only">Delete</span>+ </Button>+ ) : (+ <Button+ type="button"+ variant="outline"+ className="flex items-center border-light-red"+ disabled={!hasAccess}+ >+ <span className="text-dark-red">Delete</span>+ </Button>+ )}+ </PopoverTrigger>+ <PopoverContent>+ <h2 className="text-md mb-3 font-semibold">Please confirm</h2>+ <p className="mb-3 text-sm">+ This action permanently deletes this automation. This cannot be+ undone.+ </p>+ <div className="flex justify-end space-x-4">+ <Button+ type="button"+ variant="destructive"+ loading={deleteAutomationMutation.isLoading}+ onClick={() => {+ void deleteAutomationMutation.mutateAsync({+ projectId,+ automationId,+ });+ setIsOpen(false);+ }}+ >+ Delete Automation+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/web/src/features/automations/components/WebhookButton.tsx b/web/src/features/automations/components/WebhookButton.tsxnew file mode 100644index 0000000000..571c79958f--- /dev/null+++ b/web/src/features/automations/components/WebhookButton.tsx@@ -0,0 +1,28 @@+import { ActionButton } from "@/src/components/ActionButton";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { Zap } from "lucide-react";+import { type ButtonProps } from "@/src/components/ui/button";++export const WebhookButton = ({+ projectId,+ ...buttonProps+}: {+ projectId: string;+} & ButtonProps) => {+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "automations:read",+ });++ return (+ <ActionButton+ href={`/project/${projectId}/automations`}+ icon={<Zap className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasAccess}+ title="Webhooks"+ {...buttonProps}+ >+ <span className="hidden md:ml-1 md:inline">Webhooks</span>+ </ActionButton>+ );+};diff --git a/web/src/features/automations/components/WebhookSecretRender.tsx b/web/src/features/automations/components/WebhookSecretRender.tsxnew file mode 100644index 0000000000..c64eaf0d0f--- /dev/null+++ b/web/src/features/automations/components/WebhookSecretRender.tsx@@ -0,0 +1,22 @@+import React from "react";+import { CodeView } from "@/src/components/ui/CodeJsonViewer";++export const WebhookSecretRender = ({+ webhookSecret,+}: {+ webhookSecret: string;+}) => {+ return (+ <>+ <div className="mb-4">+ <div className="text-md font-semibold">Webhook Secret</div>+ <div className="my-2 text-sm">+ This secret can only be viewed once. You can regenerate it in the+ automation settings if needed. Use this secret to verify webhook+ signatures in your endpoint.+ </div>+ <CodeView content={webhookSecret} defaultCollapsed={false} />+ </div>+ </>+ );+};diff --git a/web/src/features/automations/components/actions/ActionHandlerRegistry.ts b/web/src/features/automations/components/actions/ActionHandlerRegistry.tsnew file mode 100644index 0000000000..35dc92391c--- /dev/null+++ b/web/src/features/automations/components/actions/ActionHandlerRegistry.ts@@ -0,0 +1,39 @@+import { type ActionType } from "@langfuse/shared";+import { type FieldValues } from "react-hook-form";+import { type BaseActionHandler } from "./BaseActionHandler";+import { WebhookActionHandler } from "./WebhookActionHandler";++export class ActionHandlerRegistry {+ private static handlers: Map<ActionType, BaseActionHandler<FieldValues>> =+ new Map();++ static {+ // Initialize handlers in static block+ this.handlers.set("WEBHOOK", new WebhookActionHandler());+ }++ static getHandler<T extends FieldValues = FieldValues>(+ actionType: ActionType,+ ): BaseActionHandler<T> {+ const handler = this.handlers.get(actionType);+ if (!handler) {+ throw new Error(`No handler registered for action type: ${actionType}`);+ }+ return handler as BaseActionHandler<T>;+ }++ static getAllActionTypes(): ActionType[] {+ return Array.from(this.handlers.keys());+ }++ static registerHandler<T extends FieldValues>(+ actionType: ActionType,+ handler: BaseActionHandler<T>,+ ) {+ this.handlers.set(actionType, handler as BaseActionHandler<FieldValues>);+ }++ static hasHandler(actionType: ActionType): boolean {+ return this.handlers.has(actionType);+ }+}diff --git a/web/src/features/automations/components/actions/BaseActionHandler.ts b/web/src/features/automations/components/actions/BaseActionHandler.tsnew file mode 100644index 0000000000..f91f911f91--- /dev/null+++ b/web/src/features/automations/components/actions/BaseActionHandler.ts@@ -0,0 +1,35 @@+import { type UseFormReturn, type FieldValues } from "react-hook-form";+import {+ type ActionDomain,+ type ActionType,+ type AutomationDomain,+ type SafeWebhookActionConfig,+} from "@langfuse/shared";++export interface BaseActionHandler<+ TFormData extends FieldValues = FieldValues,+> {+ actionType: ActionType;++ // Get default values for this action type+ getDefaultValues(automation?: AutomationDomain): TFormData;++ // Validate the form data for this action type+ validateFormData(formData: TFormData): {+ isValid: boolean;+ errors?: string[];+ };++ // Build the action config for API submission+ buildActionConfig(+ formData: TFormData,+ ): Omit<SafeWebhookActionConfig, "displaySecretKey">;++ // Render the action form UI - using any for form to allow flexibility+ renderForm(props: {+ form: UseFormReturn<any>;+ disabled: boolean;+ projectId: string;+ action?: ActionDomain;+ }): React.ReactNode;+}diff --git a/web/src/features/automations/components/actions/WebhookActionForm.tsx b/web/src/features/automations/components/actions/WebhookActionForm.tsxnew file mode 100644index 0000000000..92e321f3a9--- /dev/null+++ b/web/src/features/automations/components/actions/WebhookActionForm.tsx@@ -0,0 +1,438 @@+import { Input } from "@/src/components/ui/input";+import { Button } from "@/src/components/ui/button";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { X, Plus, RefreshCw } from "lucide-react";+import { useFieldArray, type UseFormReturn } from "react-hook-form";+import { z } from "zod/v4";+import {+ type ActionDomain,+ type ActionDomainWithSecrets,+ AvailableWebhookApiSchema,+ WebhookDefaultHeaders,+} from "@langfuse/shared";+import { api } from "@/src/utils/api";+import { useState } from "react";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { WebhookSecretRender } from "../WebhookSecretRender";+import { CodeView } from "@/src/components/ui/CodeJsonViewer";++export const webhookSchema = z.object({+ url: z.url(),+ headers: z.array(+ z.object({+ name: z.string().refine(+ (name) => {+ if (!name.trim()) return true; // Allow empty names (will be filtered out)+ const defaultHeaderKeys = Object.keys(WebhookDefaultHeaders);+ return !defaultHeaderKeys.includes(name.trim().toLowerCase());+ },+ {+ message:+ "This header is automatically added by Langfuse and cannot be customized",+ },+ ),+ value: z.string(),+ }),+ ),+ apiVersion: AvailableWebhookApiSchema,+});++export type WebhookFormValues = z.infer<typeof webhookSchema>;++interface WebhookActionFormProps {+ form: UseFormReturn<any>;+ disabled: boolean;+ projectId: string;+ action?: ActionDomain | ActionDomainWithSecrets;+}++export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({+ form,+ disabled,+ projectId,+ action,+}) => {+ const {+ fields: headerFields,+ append: appendHeader,+ remove: removeHeader,+ } = useFieldArray({+ control: form.control,+ name: "webhook.headers",+ });++ // Get default header keys to filter them out+ const defaultHeaderKeys = Object.keys(WebhookDefaultHeaders);++ // Filter out default headers from the user-editable headers+ const customHeaderFields = headerFields.filter((field, index) => {+ const headerName = form.watch(`webhook.headers.${index}.name`);+ return !defaultHeaderKeys.includes(headerName?.toLowerCase());+ });++ // Function to add a new header pair+ const addHeader = () => {+ appendHeader({ name: "", value: "" });+ };++ return (+ <div className="space-y-4">+ <FormField+ control={form.control}+ name="webhook.url"+ rules={{ required: "Webhook URL is required" }}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="flex items-center">+ Webhook URL <span className="ml-1 text-destructive">*</span>+ </FormLabel>+ <FormControl>+ <Input+ placeholder="https://example.com/webhook"+ {...field}+ disabled={disabled}+ />+ </FormControl>+ <FormDescription>+ The HTTP URL to call when the trigger fires. We will send a POST+ request to this URL. Only HTTPS URLs are allowed for security.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="webhook.apiVersion.prompt"+ render={({ field }) => (+ <FormItem>+ <FormLabel>API Version</FormLabel>+ <Select+ onValueChange={field.onChange}+ value={field.value}+ disabled={disabled}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select API version" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="v1">v1</SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ The API version to use for the webhook payload format when prompt+ events are triggered.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <div>+ <FormLabel>Headers</FormLabel>++ {/* Default Headers Section */}+ <div className="mb-4">+ <FormDescription className="mb-2">+ Default headers (automatically added by Langfuse):+ </FormDescription>+ {Object.entries({+ ...WebhookDefaultHeaders,+ "x-langfuse-signature": `t=<timestamp>,v1=<signature>`,+ }).map(([key, value]) => (+ <div key={key} className="mb-2 grid grid-cols-[1fr,1fr,auto] gap-2">+ <FormItem>+ <FormControl>+ <Input value={key} disabled={true} className="bg-muted/50" />+ </FormControl>+ </FormItem>+ <FormItem>+ <FormControl>+ <Input+ value={value}+ disabled={true}+ className="bg-muted/50"+ />+ </FormControl>+ </FormItem>+ <div className="w-10" />{" "}+ {/* Spacer to align with editable headers */}+ </div>+ ))}+ </div>++ {/* Custom Headers Section */}+ <FormDescription className="mb-2">+ Optional custom headers to include in the webhook request:+ </FormDescription>++ {customHeaderFields.map((field) => {+ // Find the original index in the headerFields array+ const originalIndex = headerFields.findIndex(+ (f) => f.id === field.id,+ );+ return (+ <div+ key={field.id}+ className="mb-2 grid grid-cols-[1fr,1fr,auto] gap-2"+ >+ <FormField+ control={form.control}+ name={`webhook.headers.${originalIndex}.name`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ placeholder="Header Name"+ {...field}+ disabled={disabled}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name={`webhook.headers.${originalIndex}.value`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ placeholder="Value"+ {...field}+ disabled={disabled}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={() => removeHeader(originalIndex)}+ disabled={disabled}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ );+ })}++ <Button+ type="button"+ variant="outline"+ onClick={addHeader}+ disabled={disabled}+ className="mt-2"+ >+ <Plus className="mr-1 h-4 w-4" />+ Add Custom Header+ </Button>+ </div>++ {/* Webhook Secret Section */}+ <div>+ <FormLabel>Webhook Secret</FormLabel>+ <FormDescription className="mb-2">+ Use this secret to verify webhook signatures for security. The secret+ is automatically included in the x-langfuse-signature header.+ </FormDescription>++ {action?.id ? (+ <div className="rounded-md border p-3">+ <div className="flex items-center gap-2">+ <div className="flex-1">+ <CodeView+ className="bg-muted/50"+ content={action.config.displaySecretKey}+ defaultCollapsed={false}+ />+ </div>+ <div className="flex gap-2">+ <RegenerateWebhookSecretButton+ projectId={projectId}+ action={action}+ />+ </div>+ </div>+ <div className="mt-1 text-xs text-muted-foreground">+ Secret is encrypted and can only be viewed when generated or+ regenerated+ </div>+ </div>+ ) : (+ <div className="rounded-md border bg-muted/50 p-3 text-sm text-muted-foreground">+ Webhook secret will be generated when the automation is created.+ </div>+ )}+ </div>+ </div>+ );+};++export const RegenerateWebhookSecretButton = ({+ projectId,+ action,+}: {+ projectId: string;+ action: ActionDomain | ActionDomainWithSecrets;+}) => {+ const [showConfirmPopover, setShowConfirmPopover] = useState(false);+ const [showRegenerateDialog, setShowRegenerateDialog] = useState(false);+ const [regeneratedSecret, setRegeneratedSecret] = useState<string | null>(+ null,+ );++ const utils = api.useUtils();+ const regenerateSecretMutation =+ api.automations.regenerateWebhookSecret.useMutation({+ onSuccess: (data) => {+ setRegeneratedSecret(data.webhookSecret);+ setShowRegenerateDialog(true);+ utils.automations.invalidate();+ },+ });++ // Function to regenerate webhook secret+ const handleRegenerateSecret = async () => {+ if (!action?.id) return;+ try {+ await regenerateSecretMutation.mutateAsync({+ projectId,+ actionId: action.id,+ });+ setShowConfirmPopover(false);+ } catch (error) {+ console.error("Failed to regenerate webhook secret:", error);+ }+ };++ return (+ <>+ <Popover open={showConfirmPopover} onOpenChange={setShowConfirmPopover}>+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="outline"+ size="default"+ disabled={regenerateSecretMutation.isLoading}+ >+ <RefreshCw+ className={`mr-2 h-4 w-4 ${regenerateSecretMutation.isLoading ? "animate-spin" : ""}`}+ />+ Regenerate+ </Button>+ </PopoverTrigger>+ <PopoverContent>+ <h2 className="text-md mb-3 font-semibold">Please confirm</h2>+ <p className="mb-3 max-w-sm text-sm">+ This action will invalidate the current webhook secret and generate+ a new one. Any existing integrations using the old secret will stop+ working until updated.+ </p>+ <div className="flex justify-end space-x-4">+ <Button+ type="button"+ variant="outline"+ onClick={() => setShowConfirmPopover(false)}+ disabled={regenerateSecretMutation.isLoading}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ loading={regenerateSecretMutation.isLoading}+ onClick={handleRegenerateSecret}+ >+ Regenerate Secret+ </Button>+ </div>+ </PopoverContent>+ </Popover>++ {/* Regenerate Secret Dialog */}+ <Dialog+ open={showRegenerateDialog}+ onOpenChange={setShowRegenerateDialog}+ >+ <DialogContent className="max-w-4xl">+ <DialogHeader>+ <DialogTitle>Webhook Secret Regenerated</DialogTitle>+ <DialogDescription>+ Your webhook secret has been regenerated. Please copy the new+ secret below - it will only be shown once.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ {regeneratedSecret && (+ <WebhookSecretRender webhookSecret={regeneratedSecret} />+ )}+ </DialogBody>+ <DialogFooter>+ <Button+ onClick={() => {+ setShowRegenerateDialog(false);+ setRegeneratedSecret(null);+ }}+ >+ {"I've saved the secret"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+};++// Function to convert the array of header objects to a Record for API+export const formatWebhookHeaders = (+ headers: { name: string; value: string }[],+): Record<string, string> => {+ const headersObject: Record<string, string> = {};+ const defaultHeaderKeys = Object.keys(WebhookDefaultHeaders);++ headers.forEach((header) => {+ if (header.name.trim() && header.value.trim()) {+ // Exclude default headers - they will be added automatically by the API+ if (!defaultHeaderKeys.includes(header.name.trim().toLowerCase())) {+ headersObject[header.name.trim()] = header.value.trim();+ }+ }+ });++ return headersObject;+};diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsxnew file mode 100644index 0000000000..992ffeee9b--- /dev/null+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx@@ -0,0 +1,167 @@+import React from "react";+import { type UseFormReturn } from "react-hook-form";+import { type BaseActionHandler } from "./BaseActionHandler";+import { WebhookActionForm, formatWebhookHeaders } from "./WebhookActionForm";+import {+ type AutomationDomain,+ AvailableWebhookApiSchema,+ WebhookDefaultHeaders,+ type SafeWebhookActionConfig,+ type ActionDomain,+} from "@langfuse/shared";+import { z } from "zod/v4";++// Define the form schema for webhook actions+const WebhookActionFormSchema = z.object({+ webhook: z.object({+ url: z.string().url("Invalid URL"),+ headers: z+ .array(+ z.object({+ name: z.string(),+ value: z.string(),+ }),+ )+ .default([]),+ apiVersion: AvailableWebhookApiSchema.default({ prompt: "v1" }),+ }),+});++type WebhookActionFormData = z.infer<typeof WebhookActionFormSchema>;++// Define a type for header pairs+type HeaderPair = {+ name: string;+ value: string;+};++export class WebhookActionHandler+ implements BaseActionHandler<WebhookActionFormData>+{+ actionType = "WEBHOOK" as const;++ // Parse existing headers if available+ private parseHeaders(automation?: AutomationDomain): HeaderPair[] {+ if (+ automation?.action?.type === "WEBHOOK" &&+ automation?.action?.config &&+ "headers" in automation.action.config &&+ automation.action.config.headers+ ) {+ try {+ const headersObject = automation.action.config.headers;+ return Object.entries(headersObject).map(([name, value]) => ({+ name,+ value: value as string,+ }));+ } catch (e) {+ console.error("Failed to parse headers:", e);+ return [];+ }+ }+ return [];+ }++ getDefaultValues(automation?: AutomationDomain): WebhookActionFormData {+ // Extract apiVersion from existing config+ let apiVersion = { prompt: "v1" } as const;+ if (+ automation?.action?.type === "WEBHOOK" &&+ automation?.action?.config &&+ "apiVersion" in automation.action.config &&+ automation.action.config.apiVersion+ ) {+ apiVersion = automation.action.config.apiVersion;+ }++ return {+ webhook: {+ url:+ (automation?.action?.type === "WEBHOOK" &&+ automation?.action?.config &&+ "url" in automation.action.config &&+ automation.action.config.url) ||+ "",+ headers: this.parseHeaders(automation),+ apiVersion,+ },+ };+ }++ validateFormData(formData: WebhookActionFormData): {+ isValid: boolean;+ errors?: string[];+ } {+ const errors: string[] = [];++ if (!formData.webhook?.url) {+ errors.push("Webhook URL is required");+ }++ // Validate headers+ if (formData.webhook?.headers) {+ const defaultHeaderKeys = Object.keys(WebhookDefaultHeaders);++ formData.webhook.headers.forEach((header: HeaderPair, index: number) => {+ // Only validate non-empty headers+ if (header.name.trim() || header.value.trim()) {+ if (!header.name.trim()) {+ errors.push(`Header ${index + 1}: Name cannot be empty`);+ }+ if (!header.value.trim()) {+ errors.push(`Header ${index + 1}: Value cannot be empty`);+ }++ // Check if header name conflicts with default headers+ if (+ header.name.trim() &&+ defaultHeaderKeys.includes(header.name.trim().toLowerCase())+ ) {+ errors.push(+ `Header ${index + 1}: "${header.name}" is automatically added by Langfuse and cannot be customized`,+ );+ }+ }+ });+ }++ return {+ isValid: errors.length === 0,+ errors: errors.length > 0 ? errors : undefined,+ };+ }++ buildActionConfig(+ formData: WebhookActionFormData,+ ): Omit<SafeWebhookActionConfig, "displaySecretKey"> {+ // Convert headers array to object+ let headersObject: Record<string, string> = {};++ if (formData.webhook?.headers) {+ headersObject = formatWebhookHeaders(formData.webhook.headers);+ }++ return {+ type: "WEBHOOK",+ url: formData.webhook?.url || "",+ headers: headersObject,+ apiVersion: formData.webhook?.apiVersion || { prompt: "v1" },+ };+ }++ renderForm(props: {+ form: UseFormReturn<WebhookActionFormData>;+ disabled: boolean;+ projectId: string;+ action?: ActionDomain;+ }) {+ return (+ <WebhookActionForm+ form={props.form}+ disabled={props.disabled}+ projectId={props.projectId}+ action={props.action}+ />+ );+ }+}diff --git a/web/src/features/automations/components/actions/index.ts b/web/src/features/automations/components/actions/index.tsnew file mode 100644index 0000000000..3d7199df3a--- /dev/null+++ b/web/src/features/automations/components/actions/index.ts@@ -0,0 +1,3 @@+export { type BaseActionHandler } from "./BaseActionHandler";+export { WebhookActionHandler } from "./WebhookActionHandler";+export { ActionHandlerRegistry } from "./ActionHandlerRegistry";diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsxnew file mode 100644index 0000000000..0f34d9a0d2--- /dev/null+++ b/web/src/features/automations/components/automationForm.tsx@@ -0,0 +1,513 @@+import React, { useState, useEffect } from "react";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { Input } from "@/src/components/ui/input";+import { Button } from "@/src/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Separator } from "@/src/components/ui/separator";+import { Switch } from "@/src/components/ui/switch";+import { useRouter } from "next/router";+import { z } from "zod/v4";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { api } from "@/src/utils/api";+import {+ type AutomationDomain,+ type ActionTypes,+ type JobConfigState,+ webhookActionFilterOptions,+} from "@langfuse/shared";+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";+import { DeleteAutomationButton } from "./DeleteAutomationButton";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { ActionHandlerRegistry } from "./actions";+import { webhookSchema } from "./actions/WebhookActionForm";+import { MultiSelect } from "@/src/features/filters/components/multi-select";++// Define the TriggerEventSource enum directly in this file to match the backend+enum TriggerEventSource {+ Prompt = "prompt",+}++// Define schemas for form validation+const baseFormSchema = z.object({+ name: z.string().min(1, "Name is required").max(100),+ eventSource: z.string().min(1, "Event source is required"),+ eventAction: z.array(z.string()),+ status: z.enum(["ACTIVE", "INACTIVE"]),+ filter: z.array(z.any()).optional(),+});++const formSchema = z.discriminatedUnion("actionType", [+ baseFormSchema.extend({+ actionType: z.literal("WEBHOOK"),+ webhook: webhookSchema,+ }),+ // add more action types here+]);++type FormValues = z.infer<typeof formSchema>;++interface AutomationFormProps {+ projectId: string;+ onSuccess?: (automationId?: string, webhookSecret?: string) => void;+ onCancel?: () => void;+ automation?: AutomationDomain;+ isEditing?: boolean;+}++export const AutomationForm = ({+ projectId,+ onSuccess,+ onCancel,+ automation,+ isEditing = false,+}: AutomationFormProps) => {+ const router = useRouter();+ const [activeTab, setActiveTab] = useState<string>("webhook");+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "automations:CUD",+ });++ const utils = api.useUtils();++ // Set up mutations+ const createAutomationMutation = api.automations.createAutomation.useMutation(+ {+ onSuccess: async () => {+ // Invalidate automations queries+ await utils.automations.invalidate();+ },+ },+ );+ const updateAutomationMutation = api.automations.updateAutomation.useMutation(+ {+ onSuccess: async () => {+ // Invalidate automations queries+ await utils.automations.invalidate();+ },+ },+ );++ // Get the action type for the form when editing+ const getActionType = () => {+ if (isEditing && automation?.action?.type) {+ return automation.action.type as ActionTypes;+ }+ return "WEBHOOK";+ };++ // Get default values based on action type+ const getDefaultValues = (): FormValues => {+ const actionType = getActionType();+ const today = new Date().toLocaleString("sv").split("T")[0]; // YYYY-MM-DD++ const baseValues = {+ name: isEditing && automation ? automation.name : `Webhook ${today}`,+ eventSource: automation+ ? automation.trigger.eventSource+ : TriggerEventSource.Prompt,+ eventAction: automation+ ? automation.trigger.eventActions+ : ["created", "updated", "deleted"],+ status: (isEditing && automation+ ? automation.trigger.status+ : "ACTIVE") as "ACTIVE" | "INACTIVE",+ filter: automation ? automation.trigger.filter || [] : [],+ };++ if (actionType === "WEBHOOK") {+ // Use action handler to get default values with proper typing+ const handler = ActionHandlerRegistry.getHandler("WEBHOOK");+ const webhookDefaults = handler.getDefaultValues(automation);+ return {+ ...baseValues,+ actionType: "WEBHOOK" as const,+ eventSource: TriggerEventSource.Prompt,+ webhook: {+ url: webhookDefaults.webhook.url || "",+ headers: webhookDefaults.webhook.headers || [],+ apiVersion: webhookDefaults.webhook.apiVersion || {+ prompt: "v1" as const,+ },+ },+ };+ } else {+ throw new Error("Invalid action type");+ }+ };++ // Initialize form with default values or values from existing automation+ const form = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: getDefaultValues(),+ });++ // Set the active tab based on the action type+ useEffect(() => {+ if (isEditing && automation?.action?.type) {+ setActiveTab(automation.action.type.toLowerCase());+ }+ }, [isEditing, automation]);++ // Handle form submission+ const onSubmit = async (data: FormValues) => {+ if (!hasAccess) {+ showSuccessToast({+ title: "Permission Denied",+ description: "You don't have permission to modify automations.",+ });+ return;+ }++ // Use action handler to validate and build config+ const handler = ActionHandlerRegistry.getHandler(data.actionType);+ const validation = handler.validateFormData(data);++ if (!validation.isValid) {+ showSuccessToast({+ title: "Validation Error",+ description:+ validation.errors?.join(", ") || "Please fill in all required fields",+ });+ return;+ }++ const actionConfig = handler.buildActionConfig(data);++ if (isEditing && automation) {+ // Update existing automation+ await updateAutomationMutation.mutateAsync({+ projectId,+ automationId: automation.id,+ name: data.name,+ eventSource: data.eventSource,+ eventAction: data.eventAction,+ filter: data.filter && data.filter.length > 0 ? data.filter : null,+ status: data.status as JobConfigState,+ actionType: data.actionType,+ actionConfig: actionConfig,+ });++ onSuccess?.(automation.id);+ } else {+ // Create new automation+ const result = await createAutomationMutation.mutateAsync({+ projectId,+ name: data.name,+ eventSource: data.eventSource,+ eventAction: data.eventAction,+ filter: data.filter && data.filter.length > 0 ? data.filter : null,+ status: data.status as JobConfigState,+ actionType: data.actionType,+ actionConfig: actionConfig,+ });+ onSuccess?.(result.automation.id, result.webhookSecret);+ }+ };++ // Update button text based on if we're editing an existing automation+ const submitButtonText =+ isEditing && automation ? "Update Webhook" : "Save Webhook";++ // Update required fields based on action type+ const handleActionTypeChange = (value: ActionTypes) => {+ setActiveTab(value.toLowerCase());+ form.setValue("actionType", value);+ const handler = ActionHandlerRegistry.getHandler("WEBHOOK");+ const defaultValues = handler.getDefaultValues();+ form.setValue("webhook", defaultValues.webhook);+ };++ // Handle cancel button click+ const handleCancel = () => {+ if (onCancel) {+ onCancel();+ } else {+ router.push(`/project/${projectId}/settings/automations`);+ }+ };++ // Get current action handler for rendering+ const getCurrentActionHandler = () => {+ try {+ const actionType = form.watch("actionType");+ return ActionHandlerRegistry.getHandler(actionType);+ } catch (error) {+ console.error("Failed to get action handler:", error);+ return null;+ }+ };++ const currentActionHandler = getCurrentActionHandler();++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">+ {isEditing && (+ <div className="mb-6 flex items-center gap-4">+ <div className="flex-1">+ <FormField+ control={form.control}+ name="name"+ rules={{ required: "Name is required" }}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ placeholder="Automation name"+ {...field}+ disabled={!hasAccess || !isEditing}+ className="rounded-none border-0 border-b border-border bg-transparent px-0 text-2xl font-semibold focus-visible:ring-0 focus-visible:ring-offset-0"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <FormField+ control={form.control}+ name="status"+ render={({ field }) => (+ <FormItem className="flex flex-row items-center gap-2">+ <FormLabel className="text-sm font-medium">Active</FormLabel>+ <FormControl>+ <Switch+ checked={field.value === "ACTIVE"}+ onCheckedChange={(checked) =>+ field.onChange(checked ? "ACTIVE" : "INACTIVE")+ }+ disabled={!hasAccess || !isEditing}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ )}++ <Card>+ <CardHeader>+ <CardTitle>Trigger</CardTitle>+ <CardDescription>+ Configure when this automation should run.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <FormField+ control={form.control}+ name="eventSource"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Event Source</FormLabel>+ <Select+ onValueChange={field.onChange}+ value={field.value}+ disabled={!hasAccess || !isEditing}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select an event source" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value={TriggerEventSource.Prompt}>+ Prompt+ </SelectItem>+ <SelectItem disabled={true} value="planned">+ More coming soon...+ </SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ The event that triggers this automation.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="eventAction"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Event Action</FormLabel>+ <FormControl>+ <MultiSelect+ title="Event Actions"+ label="Actions"+ values={field.value}+ onValueChange={field.onChange}+ options={[+ {+ value: "created",+ description:+ "Whenever a new prompt version is created",+ },+ {+ value: "updated",+ description:+ "Whenever tags or labels on a prompt version are updated",+ },+ {+ value: "deleted",+ description: "Whenever a prompt version is deleted",+ },+ ]}+ className="my-0 w-auto overflow-hidden"+ disabled={!hasAccess || !isEditing}+ labelTruncateCutOff={4}+ />+ </FormControl>+ <FormDescription>+ The actions on the event source that trigger this+ automation.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="filter"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Filter</FormLabel>+ <FormControl>+ <InlineFilterBuilder+ columns={webhookActionFilterOptions()}+ filterState={field.value || []}+ onChange={field.onChange}+ disabled={+ activeTab === "annotation_queue" ||+ !hasAccess ||+ !isEditing+ }+ />+ </FormControl>+ <FormDescription>+ Add conditions to narrow down when this trigger fires.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Action</CardTitle>+ <CardDescription>+ Configure what happens when the trigger fires.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <FormField+ control={form.control}+ name="actionType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Action Type</FormLabel>+ <Select+ onValueChange={handleActionTypeChange}+ value={field.value}+ disabled={!hasAccess || !isEditing}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select an action type" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {ActionHandlerRegistry.getAllActionTypes().map(+ (actionType) => (+ <SelectItem key={actionType} value={actionType}>+ {actionType === "WEBHOOK"+ ? "Webhook"+ : "Annotation Queue"}+ </SelectItem>+ ),+ )}+ <SelectItem disabled={true} value="planned">+ More coming soon...+ </SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ The type of action to perform when the trigger fires.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <Separator className="my-4" />++ {currentActionHandler &&+ currentActionHandler.renderForm({+ form,+ disabled: !hasAccess || !isEditing,+ projectId,+ action: automation?.action,+ })}+ </CardContent>+ </Card>++ {isEditing && (+ <div className="flex justify-between gap-3">+ {isEditing && automation?.trigger.id && automation?.action.id && (+ <div>+ <DeleteAutomationButton+ projectId={projectId}+ automationId={automation.id}+ variant="button"+ onSuccess={() => {+ utils.automations.invalidate();+ router.push(`/project/${projectId}/settings/automations`);+ }}+ />+ </div>+ )}+ <div className="flex-grow"></div>+ <div className="flex gap-3">+ <Button type="button" variant="outline" onClick={handleCancel}>+ Cancel+ </Button>+ <Button+ type="submit"+ disabled={!hasAccess || form.formState.isSubmitting}+ >+ {submitButtonText}+ </Button>+ </div>+ </div>+ )}+ </form>+ </Form>+ );+};diff --git a/web/src/features/automations/components/automations.tsx b/web/src/features/automations/components/automations.tsxnew file mode 100644index 0000000000..500f665700--- /dev/null+++ b/web/src/features/automations/components/automations.tsx@@ -0,0 +1,291 @@+import { useRouter } from "next/router";+import { AutomationSidebar } from "@/src/features/automations/components/AutomationSidebar";+import { AutomationDetails } from "@/src/features/automations/components/AutomationDetails";+import { AutomationForm } from "@/src/features/automations/components/automationForm";+import { WebhookSecretRender } from "@/src/features/automations/components/WebhookSecretRender";+import { Button } from "@/src/components/ui/button";+import { Plus } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import Page from "@/src/components/layouts/page";+import { api } from "@/src/utils/api";+import { useQueryParams, StringParam, withDefault } from "use-query-params";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { type AutomationDomain } from "@langfuse/shared";++export default function AutomationsPage() {+ const router = useRouter();+ const utils = api.useUtils();+ const projectId = router.query.projectId as string;+ const [webhookSecret, setWebhookSecret] = useState<string | null>(null);+ const [showSecretDialog, setShowSecretDialog] = useState(false);++ const [urlParams, setUrlParams] = useQueryParams({+ view: withDefault(StringParam, "list"),+ automationId: StringParam,+ tab: withDefault(StringParam, "executions"),+ });++ const { view, automationId } = urlParams;++ const selectedAutomation = useMemo(+ () => (automationId ? { automationId } : undefined),+ [automationId],+ );++ // Fetch automations to check if any exist+ const { data: automations } = api.automations.getAutomations.useQuery({+ projectId,+ });++ // Fetch editing automation when in edit mode+ const { data: editingAutomation } = api.automations.getAutomation.useQuery(+ {+ projectId,+ automationId: automationId!,+ },+ {+ enabled: view === "edit" && !!automationId,+ },+ );++ // Clear selected automation if no automations exist+ useEffect(() => {+ if (+ automations !== undefined &&+ automations.length === 0 &&+ selectedAutomation+ ) {+ setUrlParams({+ view: "list",+ automationId: undefined,+ tab: urlParams.tab,+ });+ }+ }, [automations, selectedAutomation, projectId, setUrlParams, urlParams.tab]);++ const handleCreateAutomation = () => {+ setUrlParams({+ view: "create",+ automationId: undefined,+ tab: urlParams.tab,+ });+ };++ const handleEditAutomation = (automation: AutomationDomain) => {+ setUrlParams({+ view: "edit",+ automationId: automation.id,+ tab: urlParams.tab,+ });+ };++ const handleReturnToList = () => {+ setUrlParams({+ ...urlParams,+ view: "list",+ });+ };++ const handleCreateSuccess = (+ automationId?: string,+ webhookSecret?: string,+ ) => {+ // Show webhook secret if provided+ if (webhookSecret) {+ setWebhookSecret(webhookSecret);+ setShowSecretDialog(true);+ }++ // Navigate to the newly created automation detail page+ if (automationId) {+ setUrlParams({+ view: "list",+ automationId,+ tab: urlParams.tab,+ });+ } else {+ setUrlParams({+ ...urlParams,+ view: "list",+ });+ }+ };++ const handleEditSuccess = () => {+ // Return to detail view of the edited automation+ utils.automations.invalidate();+ setUrlParams({+ ...urlParams,+ view: "list",+ });+ };++ const handleAutomationSelect = (automation: AutomationDomain) => {+ setUrlParams({+ view: "list",+ automationId: automation.id,+ tab: urlParams.tab, // Preserve the current tab selection+ });+ };++ const handleDeleteAutomation = () => {+ // Find the current automation index+ if (!automations || !selectedAutomation) return;++ const currentIndex = automations.findIndex(+ (automation) => automation.id === selectedAutomation.automationId,+ );++ if (currentIndex === -1) return;++ // Select the next automation, or the previous one if this was the last+ let nextIndex: number;+ if (currentIndex < automations.length - 1) {+ // Select the next automation+ nextIndex = currentIndex + 1;+ } else if (currentIndex > 0) {+ // Select the previous automation (this was the last one)+ nextIndex = currentIndex - 1;+ } else {+ // This was the only automation, clear selection+ setUrlParams({+ view: "list",+ automationId: undefined,+ tab: urlParams.tab,+ });+ return;+ }++ const nextAutomation = automations[nextIndex];+ if (nextAutomation) {+ setUrlParams({+ view: "list",+ automationId: nextAutomation.id,+ tab: urlParams.tab,+ });+ }+ };++ const renderMainContent = () => {+ if (view === "create") {+ return (+ <div className="p-6">+ <AutomationForm+ projectId={projectId}+ onSuccess={handleCreateSuccess}+ onCancel={handleReturnToList}+ isEditing={true}+ />+ </div>+ );+ }++ if (view === "edit" && editingAutomation) {+ return (+ <div className="p-6">+ <AutomationForm+ projectId={projectId}+ onSuccess={handleEditSuccess}+ onCancel={handleReturnToList}+ automation={editingAutomation}+ isEditing={true}+ />+ </div>+ );+ }++ if (selectedAutomation) {+ return (+ <div className="p-6">+ <AutomationDetails+ key={selectedAutomation.automationId}+ projectId={projectId}+ automationId={selectedAutomation.automationId}+ onEditSuccess={handleEditSuccess}+ onEdit={handleEditAutomation}+ onDelete={handleDeleteAutomation}+ />+ </div>+ );+ }++ return (+ <div className="p-6">+ <div className="flex h-full items-center justify-center text-muted-foreground">+ <div className="text-center">+ <h3 className="text-lg font-medium">Select a webhook</h3>+ <p className="mt-2 text-sm">+ Choose a webhook from the sidebar to view its details and+ execution history.+ </p>+ </div>+ </div>+ </div>+ );+ };++ return (+ <Page+ headerProps={{+ title: "Webhooks",+ breadcrumb: [+ {+ name: "Webhooks",+ href: `/project/${projectId}/automations`,+ },+ ],+ actionButtonsRight: (+ <Button onClick={handleCreateAutomation}>+ <Plus className="mr-2 h-4 w-4" />+ Create Webhook+ </Button>+ ),+ }}+ >+ <div className="flex h-full">+ <AutomationSidebar+ projectId={projectId}+ selectedAutomation={selectedAutomation}+ onAutomationSelect={handleAutomationSelect}+ />+ <div className="flex-1 overflow-auto">{renderMainContent()}</div>+ </div>++ {/* Webhook Secret Dialog */}+ <Dialog open={showSecretDialog} onOpenChange={setShowSecretDialog}>+ <DialogContent className="max-w-4xl">+ <DialogHeader>+ <DialogTitle>Webhook Secret Created</DialogTitle>+ <DialogDescription>+ Your automation has been created successfully. Please copy the+ webhook secret below - it will only be shown once.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ {webhookSecret && (+ <WebhookSecretRender webhookSecret={webhookSecret} />+ )}+ </DialogBody>+ <DialogFooter>+ <Button+ onClick={() => {+ setShowSecretDialog(false);+ setWebhookSecret(null);+ }}+ >+ {"I've saved the secret"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </Page>+ );+}diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.tsnew file mode 100644index 0000000000..a56ebf1921--- /dev/null+++ b/web/src/features/automations/server/router.ts@@ -0,0 +1,479 @@+import { createTRPCRouter } from "@/src/server/api/trpc";+import { protectedProjectProcedure } from "@/src/server/api/trpc";+import { z } from "zod/v4";+import {+ ActionCreateSchema,+ ActionType,+ JobConfigState,+} from "@langfuse/shared";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { v4 } from "uuid";+import {+ getActionById,+ getAutomations,+ getAutomationById,+ getConsecutiveAutomationFailures,+ logger,+} from "@langfuse/shared/src/server";+import { generateWebhookSecret } from "@langfuse/shared/encryption";+import { processWebhookActionConfig } from "./webhookHelpers";+import { TRPCError } from "@trpc/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";++export const CreateAutomationInputSchema = z.object({+ projectId: z.string(),+ name: z.string().min(1, "Name is required"),+ eventSource: z.string(),+ eventAction: z.array(z.string()),+ filter: z.array(z.any()).nullable(),+ status: z.enum(JobConfigState).default(JobConfigState.ACTIVE),+ // Action fields+ actionType: z.enum(ActionType),+ actionConfig: ActionCreateSchema,+});++export const UpdateAutomationInputSchema = CreateAutomationInputSchema.extend({+ automationId: z.string(),+});++export const automationsRouter = createTRPCRouter({+ // Get automations that were recently auto-disabled due to failures+ getCountOfConsecutiveFailures: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ automationId: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ // Check if user has at least read access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:read",+ });++ const recentlyDisabled = await getConsecutiveAutomationFailures({+ automationId: input.automationId,+ projectId: input.projectId,+ });++ return { count: recentlyDisabled };+ }),++ // Regenerate webhook secret for an automation+ regenerateWebhookSecret: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ actionId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ // Check if user has create/update/delete access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:CUD",+ });++ const existingAction = await getActionById({+ projectId: input.projectId,+ actionId: input.actionId,+ });++ if (!existingAction || existingAction.type !== "WEBHOOK") {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Action with id ${input.actionId} not found.`,+ });+ }++ // Generate new webhook secret+ const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =+ generateWebhookSecret();++ await auditLog({+ session: ctx.session,+ resourceType: "action",+ resourceId: input.actionId,+ action: "update",+ before: {+ displaySecretKey: existingAction.config.displaySecretKey,+ },+ after: {+ displaySecretKey: newDisplaySecretKey,+ },+ });++ // Update action config with new secret+ const updatedConfig = {+ ...(existingAction.config as any),+ secretKey: newSecretKey,+ displaySecretKey: newDisplaySecretKey,+ };++ await ctx.prisma.action.update({+ where: { id: input.actionId, projectId: ctx.session.projectId },+ data: { config: updatedConfig },+ });++ return {+ displaySecretKey: newDisplaySecretKey,+ webhookSecret: newSecretKey, // Return full secret for one-time display+ };+ }),++ getAutomations: protectedProjectProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => {+ // Check if user has at least read access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:read",+ });++ return await getAutomations({+ projectId: input.projectId,+ });+ }),++ // Get a single automation by automation ID+ getAutomation: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ automationId: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ // Check if user has at least read access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:read",+ });++ const automation = await getAutomationById({+ projectId: input.projectId,+ automationId: input.automationId,+ });++ if (!automation) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Automation with id ${input.automationId} not found.`,+ });+ }++ return automation;+ }),++ // Get execution history for an automation+ getAutomationExecutions: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ automationId: z.string(),+ page: z.number().min(0).default(0),+ limit: z.number().min(1).max(1000).default(50),+ }),+ )+ .query(async ({ ctx, input }) => {+ // Check if user has at least read access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:read",+ });++ // First get the automation to extract triggerId and actionId+ const automation = await getAutomationById({+ projectId: input.projectId,+ automationId: input.automationId,+ });++ if (!automation) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Automation with id ${input.automationId} not found.`,+ });+ }++ const executions = await ctx.prisma.automationExecution.findMany({+ where: {+ projectId: ctx.session.projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ },+ orderBy: {+ createdAt: "desc",+ },+ skip: input.page * input.limit,+ take: input.limit,+ });++ const totalCount = await ctx.prisma.automationExecution.count({+ where: {+ projectId: ctx.session.projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ },+ });++ return {+ executions,+ totalCount,+ };+ }),++ // Combined route that creates both an action and a trigger+ createAutomation: protectedProjectProcedure+ .input(CreateAutomationInputSchema)+ .mutation(async ({ ctx, input }) => {+ // Check if user has create/update/delete access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:CUD",+ });++ const triggerId = v4();+ const actionId = v4();++ // Process webhook action configuration using helper+ const { finalActionConfig, newUnencryptedWebhookSecret } =+ await processWebhookActionConfig({+ actionConfig: input.actionConfig,+ projectId: input.projectId,+ });++ const [trigger, action, automation] = await ctx.prisma.$transaction(+ async (tx) => {+ const trigger = await tx.trigger.create({+ data: {+ id: triggerId,+ projectId: ctx.session.projectId,+ eventSource: input.eventSource,+ eventActions: input.eventAction,+ filter: input.filter || [],+ status: input.status,+ },+ });++ // First create the action+ const action = await tx.action.create({+ data: {+ id: actionId,+ projectId: ctx.session.projectId,+ type: input.actionType,+ config: finalActionConfig,+ },+ });++ // Create the automation+ const automation = await tx.automation.create({+ data: {+ projectId: ctx.session.projectId,+ triggerId: triggerId,+ actionId: actionId,+ name: input.name,+ },+ });++ return [trigger, action, automation];+ },+ );++ await auditLog({+ session: ctx.session,+ resourceType: "automation",+ resourceId: trigger.id,+ action: "create",+ before: undefined,+ after: {+ automation,+ action: action,+ trigger: trigger,+ },+ });++ logger.info(`Created automation ${trigger.id} for action ${action.id}`);++ return {+ action,+ trigger,+ automation,+ webhookSecret: newUnencryptedWebhookSecret, // Return webhook secret at top level for one-time display+ };+ }),++ // Update an existing automation+ updateAutomation: protectedProjectProcedure+ .input(UpdateAutomationInputSchema)+ .mutation(async ({ ctx, input }) => {+ // Check if user has create/update/delete access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:CUD",+ });++ const existingAutomation = await getAutomationById({+ projectId: input.projectId,+ automationId: input.automationId,+ });++ if (!existingAutomation) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Automation with id ${input.automationId} not found.`,+ });+ }++ // Process webhook action configuration using helper+ const { finalActionConfig } = await processWebhookActionConfig({+ actionConfig: input.actionConfig,+ actionId: existingAutomation.action.id,+ projectId: input.projectId,+ });++ const [action, trigger, automation] = await ctx.prisma.$transaction(+ async (tx) => {+ // Update the action+ const action = await tx.action.update({+ where: {+ id: existingAutomation.action.id,+ projectId: ctx.session.projectId,+ },+ data: {+ type: input.actionType,+ config: finalActionConfig,+ },+ });++ // Update the trigger+ const trigger = await tx.trigger.update({+ where: {+ id: existingAutomation.trigger.id,+ projectId: ctx.session.projectId,+ },+ data: {+ eventSource: input.eventSource,+ eventActions: input.eventAction,+ filter: input.filter || [],+ status: input.status,+ },+ });++ // Update the automation name in Automation+ await tx.automation.update({+ where: {+ id: input.automationId,+ projectId: ctx.session.projectId,+ },+ data: {+ name: input.name,+ },+ });++ // Get the updated automation+ const automation = await tx.automation.findFirst({+ where: {+ id: input.automationId,+ projectId: ctx.session.projectId,+ },+ });++ return [action, trigger, automation];+ },+ );++ await auditLog({+ session: ctx.session,+ resourceType: "automation",+ resourceId: trigger.id,+ action: "update",+ before: {+ automation: existingAutomation,+ action: existingAutomation.action,+ trigger: existingAutomation.trigger,+ },+ after: {+ automation: automation,+ action: action,+ trigger: trigger,+ },+ });++ return { action, trigger, automation };+ }),++ // Delete an automation (both trigger and action)+ deleteAutomation: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ automationId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ // Check if user has create/update/delete access to automations+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:CUD",+ });++ const existingAutomation = await getAutomationById({+ projectId: input.projectId,+ automationId: input.automationId,+ });++ if (!existingAutomation) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Automation with id ${input.automationId} not found.`,+ });+ }++ await ctx.prisma.$transaction(async (tx) => {+ await tx.automation.delete({+ where: {+ id: input.automationId,+ projectId: ctx.session.projectId,+ },+ });++ await tx.automationExecution.deleteMany({+ where: {+ triggerId: existingAutomation.trigger.id,+ actionId: existingAutomation.action.id,+ },+ });++ await tx.action.delete({+ where: {+ id: existingAutomation.action.id,+ projectId: ctx.session.projectId,+ },+ });++ await tx.trigger.delete({+ where: {+ id: existingAutomation.trigger.id,+ projectId: ctx.session.projectId,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "automation",+ resourceId: input.automationId,+ action: "delete",+ before: existingAutomation,+ });+ });+ }),+});diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.tsnew file mode 100644index 0000000000..5ef8b9db65--- /dev/null+++ b/web/src/features/automations/server/webhookHelpers.ts@@ -0,0 +1,77 @@+import {+ decrypt,+ encrypt,+ generateWebhookSecret,+} from "@langfuse/shared/encryption";+import { type ActionCreate, type ActionConfig } from "@langfuse/shared";+import { getActionByIdWithSecrets } from "@langfuse/shared/src/server";++interface WebhookConfigOptions {+ actionConfig: ActionCreate;+ actionId?: string;+ projectId: string;+}++/**+ * Processes webhook action configuration by:+ * 1. Adding default headers+ * 2. Generating or preserving webhook secrets+ * 3. Encrypting secrets for storage+ */+export async function processWebhookActionConfig({+ actionConfig,+ actionId,+ projectId,+}: WebhookConfigOptions): Promise<{+ finalActionConfig: ActionConfig;+ newUnencryptedWebhookSecret?: string; // For one-time display+}> {+ if (actionConfig.type !== "WEBHOOK") {+ throw new Error("Action type is not WEBHOOK");+ }++ const existingAction = actionId+ ? ((await getActionByIdWithSecrets({+ projectId: projectId!,+ actionId,+ })) ?? undefined)+ : undefined;++ const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =+ generateWebhookSecret();++ const finalActionConfig = {+ ...actionConfig,+ headers: {+ ...actionConfig.headers,+ },+ secretKey: existingAction?.config.secretKey ?? encrypt(newSecretKey),+ displaySecretKey:+ existingAction?.config.displaySecretKey ?? newDisplaySecretKey,+ };++ return {+ finalActionConfig,+ newUnencryptedWebhookSecret: existingAction?.config.secretKey+ ? undefined+ : newSecretKey,+ };+}++/**+ * Extracts webhook secret for one-time display after creation+ */+export function extractWebhookSecret(+ actionConfig: ActionConfig,+): string | undefined {+ if (actionConfig.type !== "WEBHOOK" || !actionConfig.secretKey) {+ return undefined;+ }++ try {+ return decrypt(actionConfig.secretKey);+ } catch (error) {+ console.error("Failed to decrypt webhook secret for display:", error);+ return undefined;+ }+}diff --git a/web/src/features/filters/components/multi-select.tsx b/web/src/features/filters/components/multi-select.tsxindex 09ffce42b6..701cb1774e 100644--- a/web/src/features/filters/components/multi-select.tsx+++ b/web/src/features/filters/components/multi-select.tsx@@ -22,6 +22,7 @@ import { Separator } from "@/src/components/ui/separator";import { type FilterOption } from "@langfuse/shared";import { Input } from "@/src/components/ui/input";import { useRef, useState } from "react";+import { PropertyHoverCard } from "@/src/features/widgets/components/WidgetPropertySelectItem";const getFreeTextInput = (isCustomSelectEnabled: boolean,@@ -41,6 +42,7 @@ export function MultiSelect({className,disabled,isCustomSelectEnabled = false,+ labelTruncateCutOff = 2,}: {title?: string;label?: string;@@ -50,6 +52,7 @@ export function MultiSelect({className?: string;disabled?: boolean;isCustomSelectEnabled?: boolean;+ labelTruncateCutOff?: number;}) {const selectedValues = new Set(values);const optionValues = new Set(options.map((option) => option.value));@@ -115,7 +118,7 @@ export function MultiSelect({{selectedValues.size}</Badge><div className="hidden space-x-1 lg:flex">- {selectedValues.size > 2 ? (+ {selectedValues.size > labelTruncateCutOff ? (<Badgevariant="secondary"className="rounded-sm px-1 font-normal"@@ -150,7 +153,7 @@ export function MultiSelect({{options.map((option) => {if (option.value.length === 0) return;const isSelected = selectedValues.has(option.value);- return (+ const commandItem = (<InputCommandItemkey={option.value}onSelect={() => {@@ -186,6 +189,18 @@ export function MultiSelect({) : null}</InputCommandItem>);++ return option.description ? (+ <PropertyHoverCard+ key={option.value}+ label={option.displayValue ?? option.value}+ description={option.description}+ >+ {commandItem}+ </PropertyHoverCard>+ ) : (+ commandItem+ );})}</InputCommandGroup>{isCustomSelectEnabled && (diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.tsindex 5f4c7c7818..74d5c15ed7 100644--- a/web/src/features/filters/hooks/useFilterState.ts+++ b/web/src/features/filters/hooks/useFilterState.ts@@ -5,6 +5,7 @@ import {tracesTableCols,singleFilter,sessionsViewCols,+ promptsTableCols,} from "@langfuse/shared";import { scoresTableCols } from "@/src/server/api/definitions/scoresTable";import {@@ -13,7 +14,6 @@ import {decodeDelimitedArray,withDefault,} from "use-query-params";-import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";import { usersTableCols } from "@/src/server/api/definitions/usersTable";import useSessionStorage from "@/src/components/useSessionStorage";import { evalConfigFilterColumns } from "@/src/server/api/definitions/evalConfigsTable";diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsxindex 455feace62..910dd954d5 100644--- a/web/src/features/prompts/components/prompt-detail.tsx+++ b/web/src/features/prompts/components/prompt-detail.tsx@@ -56,6 +56,7 @@ import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButtonimport { Command, CommandInput } from "@/src/components/ui/command";import { renderContentWithPromptButtons } from "@/src/features/prompts/components/renderContentWithPromptButtons";import { PromptVariableListPreview } from "@/src/features/prompts/components/PromptVariableListPreview";+import { WebhookButton } from "@/src/features/automations/components/WebhookButton";const getPythonCode = (name: string,@@ -305,6 +306,7 @@ export const PromptDetail = ({),actionButtonsRight: (<>+ {projectId && <WebhookButton projectId={projectId} />}{projectId && (<DuplicatePromptButtonpromptId={prompt.id}diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex 19a6f13f52..d8c24a3e26 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -11,7 +11,6 @@ import { TagPromptPopover } from "@/src/features/tag/components/TagPromptPopoverimport { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";-import { promptsTableColsWithOptions } from "@/src/server/api/definitions/promptsTable";import {NumberParam,StringParam,@@ -33,6 +32,7 @@ import {BreadcrumbSeparator,} from "@/src/components/ui/breadcrumb";import { Slash, Folder, Home } from "lucide-react";+import { promptsTableColsWithOptions } from "@langfuse/shared";type PromptTableRow = {id: string;diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.tsindex d7c03e28cd..493173c195 100644--- a/web/src/features/prompts/server/actions/createPrompt.ts+++ b/web/src/features/prompts/server/actions/createPrompt.ts@@ -19,6 +19,7 @@ import {redis,extractPlaceholderNames,} from "@langfuse/shared/src/server";+import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";export type CreatePromptParams = CreatePromptTRPCType & {createdBy: string;@@ -100,6 +101,8 @@ export const createPrompt = async ({const promptService = new PromptService(prisma, redis);const promptDependencies = parsePromptDependencyTags(prompt);+ const touchedPromptIds: string[] = [];+try {await promptService.buildAndResolvePromptGraph({projectId,@@ -150,30 +153,36 @@ export const createPrompt = async ({),];- if (finalLabels.length > 0)+ if (finalLabels.length > 0) {// If we're creating a new labeled prompt, we must remove those labels on previous prompts since labels are unique- create.push(- ...(await removeLabelsFromPreviousPromptVersions({- prisma,- projectId,- promptName: name,- labelsToRemove: finalLabels,- })),- );+ const {+ touchedPromptIds: touchedPromptIdsPrevPrompts,+ updates: updatesPrevPrompts,+ } = await removeLabelsFromPreviousPromptVersions({+ prisma,+ projectId,+ promptName: name,+ labelsToRemove: finalLabels,+ });+ touchedPromptIds.push(...touchedPromptIdsPrevPrompts);+ create.push(...updatesPrevPrompts);+ }const haveTagsChanged =JSON.stringify([...new Set(finalTags)].sort()) !==JSON.stringify([...new Set(latestPrompt?.tags)].sort());- if (haveTagsChanged)+ if (haveTagsChanged) {// If we're creating a new prompt with tags, we must update those tags on previous prompts since tags are consistent across versions- create.push(- ...(await updatePromptTagsOnAllVersions({+ const { touchedPromptIds: touchedPromptIdsTags, updates: updatesTags } =+ await updatePromptTagsOnAllVersions({prisma,projectId,promptName: name,tags: finalTags,- })),- );+ });+ touchedPromptIds.push(...touchedPromptIdsTags);+ create.push(...updatesTags);+ }// Lock and invalidate cache for _all_ versions and labels of the prompt nameawait promptService.lockCache({ projectId, promptName: name });@@ -188,6 +197,26 @@ export const createPrompt = async ({// Unlock cacheawait promptService.unlockCache({ projectId, promptName: name });+ const updatedPrompts = await prisma.prompt.findMany({+ where: {+ id: { in: touchedPromptIds },+ projectId,+ },+ });++ await Promise.all([+ ...updatedPrompts.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "updated",+ ),+ ),+ promptChangeEventSourcing(+ await promptService.resolvePrompt(createdPrompt),+ "created",+ ),+ ]);+return createdPrompt;};@@ -265,6 +294,9 @@ export const duplicatePrompt = async ({projectId,createdBy,commitMessage: prompt.commitMessage,+ createdAt: new Date(),+ updatedAt: new Date(),+ isActive: true,};});@@ -298,5 +330,16 @@ export const duplicatePrompt = async ({},});+ const promptService = new PromptService(prisma, redis);++ await Promise.all(+ promptsToCreate.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "created",+ ),+ ),+ );+return createdPrompt;};diff --git a/web/src/features/prompts/server/actions/getPromptsMeta.ts b/web/src/features/prompts/server/actions/getPromptsMeta.tsindex f6ffb5f0e4..ce7b80cac6 100644--- a/web/src/features/prompts/server/actions/getPromptsMeta.ts+++ b/web/src/features/prompts/server/actions/getPromptsMeta.ts@@ -1,5 +1,8 @@-import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";-import { type GetPromptsMetaType, type FilterState } from "@langfuse/shared";+import {+ type GetPromptsMetaType,+ type FilterState,+ promptsTableCols,+} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { tableColumnsToSqlFilterAndPrefix } from "@langfuse/shared/src/server";diff --git a/web/src/features/prompts/server/actions/updatePrompts.ts b/web/src/features/prompts/server/actions/updatePrompts.tsindex 588b9a534c..58a1493520 100644--- a/web/src/features/prompts/server/actions/updatePrompts.ts+++ b/web/src/features/prompts/server/actions/updatePrompts.ts@@ -3,6 +3,7 @@ import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/simport { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";import { prisma, Prisma } from "@langfuse/shared/src/db";import { redis } from "@langfuse/shared/src/server";+import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";export type UpdatePromptParams = {promptName: string;@@ -19,9 +20,11 @@ export const updatePrompt = async (params: UpdatePromptParams) => {);const promptService = new PromptService(prisma, redis);try {+ const touchedPromptIds: string[] = [];+await promptService.lockCache({ projectId, promptName: promptName });- const result = prisma.$transaction(async (tx) => {+ const result = await prisma.$transaction(async (tx) => {const prompt = (await tx.$queryRaw<Array<{@@ -47,6 +50,8 @@ export const updatePrompt = async (params: UpdatePromptParams) => {throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);}+ touchedPromptIds.push(prompt.id);+const newLabelsSet = new Set([...newLabels, ...prompt.labels]);const removedLabels = [];@@ -102,14 +107,21 @@ export const updatePrompt = async (params: UpdatePromptParams) => {)}`,);+ const {+ touchedPromptIds: labelsTouchedPromptIds,+ updates: labelUpdates,+ } = await removeLabelsFromPreviousPromptVersions({+ prisma: tx,+ projectId,+ promptName,+ labelsToRemove: [...new Set(newLabels)],+ });++ touchedPromptIds.push(...labelsTouchedPromptIds);+const result = await Promise.all([// Remove labels from other prompts- ...(await removeLabelsFromPreviousPromptVersions({- prisma: tx,- projectId,- promptName,- labelsToRemove: [...new Set(newLabels)],- })),+ ...labelUpdates,// Update prompttx.prompt.update({where: {@@ -130,6 +142,30 @@ export const updatePrompt = async (params: UpdatePromptParams) => {await promptService.invalidateCache({ projectId, promptName: promptName });await promptService.unlockCache({ projectId, promptName: promptName });+ // For updates, we need the before state, but we don't have it easily accessible here+ // This updatePrompt function only handles label updates, so the main content doesn't change+ // We'll pass undefined for now since label changes don't need before state for webhooks++ const updatedPrompts = await prisma.prompt.findMany({+ where: {+ id: { in: touchedPromptIds },+ projectId,+ },+ });++ logger.info(+ `Triggering webhook for ${updatedPrompts.length} prompts for project ${projectId}, touchedPromptIds: ${JSON.stringify(touchedPromptIds)}`,+ );++ await Promise.all(+ updatedPrompts.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "updated",+ ),+ ),+ );+return result;} catch (e) {await promptService.unlockCache({ projectId, promptName: promptName });diff --git a/web/src/features/prompts/server/promptChangeEventSourcing.ts b/web/src/features/prompts/server/promptChangeEventSourcing.tsnew file mode 100644index 0000000000..c76aa81af9--- /dev/null+++ b/web/src/features/prompts/server/promptChangeEventSourcing.ts@@ -0,0 +1,54 @@+import { jsonSchemaNullable, type TriggerEventAction } from "@langfuse/shared";+import {+ logger,+ type PromptResult,+ EntityChangeQueue,+ QueueJobs,+ QueueName,+} from "@langfuse/shared/src/server";+import { v4 } from "uuid";++/**+ * Queue prompt change events for async processing using the generic EntityChangeQueue+ */+export const promptChangeEventSourcing = async (+ promptData: PromptResult | null,+ action: TriggerEventAction,+) => {+ if (!promptData) {+ return;+ }++ const event = {+ timestamp: new Date(),+ id: v4(),+ name: QueueJobs.EntityChangeJob as QueueJobs.EntityChangeJob,+ payload: {+ entityType: "prompt-version" as const,+ projectId: promptData.projectId,+ promptId: promptData.id,+ action: action,+ prompt: {+ ...promptData,+ prompt: jsonSchemaNullable.parse(promptData.prompt),+ config: jsonSchemaNullable.parse(promptData.config),+ },+ },+ };+ try {+ // Queue the entity change event for async processing+ await EntityChangeQueue.getInstance()?.add(+ QueueName.EntityChangeQueue,+ event,+ );++ logger.info(+ `Queued entity change event for prompt ${promptData.id} in project ${promptData.projectId} with action ${action}`,+ );+ } catch (error) {+ logger.error(+ `Failed to queue entity change event for prompt ${promptData.id} for project ${promptData.projectId}: ${error}`,+ );+ throw error;+ }+};diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex 8d8fa1ff73..150b1ff371 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -10,7 +10,6 @@ import {import { type Prompt, Prisma } from "@langfuse/shared/src/db";import { createPrompt, duplicatePrompt } from "../actions/createPrompt";import { checkHasProtectedLabels } from "../utils/checkHasProtectedLabels";-import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";import {CreatePromptTRPCSchema,InvalidRequestError,@@ -18,6 +17,7 @@ import {optionalPaginationZod,paginationZod,PromptLabelSchema,+ promptsTableCols,PromptType,} from "@langfuse/shared";import { orderBy, singleFilter } from "@langfuse/shared";@@ -33,6 +33,7 @@ import {} from "@langfuse/shared/src/server";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import { TRPCError } from "@trpc/server";+import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";const PromptFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -455,6 +456,16 @@ export const promptRouter = createTRPCRouter({// Unlock cacheawait promptService.unlockCache({ projectId, promptName });++ // Trigger webhooks for prompt deletion+ await Promise.all(+ prompts.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "deleted",+ ),+ ),+ );} catch (e) {logger.error(e);throw e;@@ -603,6 +614,12 @@ export const promptRouter = createTRPCRouter({// Unlock cacheawait promptService.unlockCache({ projectId, promptName });++ // Trigger webhooks for prompt version deletion+ await promptChangeEventSourcing(+ await promptService.resolvePrompt(promptVersion),+ "deleted",+ );} catch (e) {logger.error(e);throw e;@@ -714,6 +731,8 @@ export const promptRouter = createTRPCRouter({}}+ const touchedPromptIds = [toBeLabeledPrompt.id];+await auditLog({session: ctx.session,@@ -738,6 +757,8 @@ export const promptRouter = createTRPCRouter({orderBy: [{ version: "desc" }],});+ touchedPromptIds.push(...previousLabeledPrompts.map((p) => p.id));+const toBeExecuted = [ctx.prisma.prompt.update({where: {@@ -775,6 +796,24 @@ export const promptRouter = createTRPCRouter({// Unlock cacheawait promptService.unlockCache({ projectId, promptName });++ // Trigger webhooks for prompt label update+ const updatedPrompts = await ctx.prisma.prompt.findMany({+ where: {+ id: { in: touchedPromptIds },+ projectId,+ },+ });++ // Send webhooks for ALL affected prompts+ await Promise.all(+ updatedPrompts.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "updated",+ ),+ ),+ );} catch (e) {logger.error(`Failed to set prompt labels: ${e}`, e);throw e;@@ -908,8 +947,24 @@ export const promptRouter = createTRPCRouter({// Unlock cacheawait promptService.unlockCache({ projectId, promptName });- } catch (error) {- logger.error(error);++ // Trigger webhooks for prompt tag update++ const prompts = await ctx.prisma.prompt.findMany({+ where: { projectId, name: promptName },+ });++ await Promise.all(+ prompts.map(async (prompt) =>+ promptChangeEventSourcing(+ await promptService.resolvePrompt(prompt),+ "updated",+ ),+ ),+ );+ } catch (e) {+ logger.error(`Failed to update prompt tags: ${e}`, e);+ throw e;}}),allPromptMeta: protectedProjectProcedurediff --git a/web/src/features/prompts/server/utils/updatePromptLabels.ts b/web/src/features/prompts/server/utils/updatePromptLabels.tsindex 0925f52034..539607d1d5 100644--- a/web/src/features/prompts/server/utils/updatePromptLabels.ts+++ b/web/src/features/prompts/server/utils/updatePromptLabels.ts@@ -23,14 +23,21 @@ export const removeLabelsFromPreviousPromptVersions = async ({orderBy: [{ version: "desc" }],});- return previouslyLabeledPrompts.map((prevPrompt) =>- prisma.prompt.update({- where: { id: prevPrompt.id },- data: {- labels: prevPrompt.labels.filter(- (prevLabel) => !labelsToRemove.includes(prevLabel),- ),- },- }),+ const touchedPromptIds = previouslyLabeledPrompts.map(+ (prevPrompt) => prevPrompt.id,);++ return {+ touchedPromptIds,+ updates: previouslyLabeledPrompts.map((prevPrompt) =>+ prisma.prompt.update({+ where: { id: prevPrompt.id },+ data: {+ labels: prevPrompt.labels.filter(+ (prevLabel) => !labelsToRemove.includes(prevLabel),+ ),+ },+ }),+ ),+ };};diff --git a/web/src/features/prompts/server/utils/updatePromptTags.ts b/web/src/features/prompts/server/utils/updatePromptTags.tsindex 62ebb164ff..3a1706224f 100644--- a/web/src/features/prompts/server/utils/updatePromptTags.ts+++ b/web/src/features/prompts/server/utils/updatePromptTags.ts@@ -15,14 +15,22 @@ export const updatePromptTagsOnAllVersions = async ({where: { projectId, name: promptName },});- if (previousVersions.length === 0) return [];+ if (previousVersions.length === 0)+ return { touchedPromptIds: [], updates: [] };- return previousVersions.map((prevVersion) =>- prisma.prompt.update({- where: { id: prevVersion.id },- data: {- tags: [...new Set(tags)], // Ensure tags are unique- },- }),+ const touchedPromptIds = previousVersions.map(+ (prevVersion) => prevVersion.id,);++ return {+ touchedPromptIds,+ updates: previousVersions.map((prevVersion) =>+ prisma.prompt.update({+ where: { id: prevVersion.id },+ data: {+ tags: [...new Set(tags)], // Ensure tags are unique+ },+ }),+ ),+ };};diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 585505dc27..88aa98eb47 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -70,6 +70,9 @@ const projectScopes = ["TableViewPresets:CUD","TableViewPresets:read",++ "automations:CUD",+ "automations:read",] as const;// type string of all Resource:Action, e.g. "members:read"@@ -125,6 +128,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"dashboards:CUD","TableViewPresets:CUD","TableViewPresets:read",+ "automations:CUD",+ "automations:read",],ADMIN: ["project:read",@@ -174,6 +179,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"dashboards:CUD","TableViewPresets:CUD","TableViewPresets:read",+ "automations:CUD",+ "automations:read",],MEMBER: ["project:read",@@ -210,6 +217,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"dashboards:CUD","TableViewPresets:CUD","TableViewPresets:read",+ "automations:read",+ "automations:CUD",],VIEWER: ["project:read",@@ -227,6 +236,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"promptExperiments:read","dashboards:read","TableViewPresets:read",+ "automations:read",],NONE: [],};diff --git a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx b/web/src/features/widgets/components/WidgetPropertySelectItem.tsxindex 88e1e7f025..7d4f0efd64 100644--- a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx+++ b/web/src/features/widgets/components/WidgetPropertySelectItem.tsx@@ -7,32 +7,24 @@ import { HoverCardPortal } from "@radix-ui/react-hover-card";import { SelectItem } from "@/src/components/ui/select";import * as React from "react";-/**- * Generic SelectItem with a hover-card that shows documentation for a widget property- * (view, metric, dimension).- */-export const WidgetPropertySelectItem = ({- value,- label,- description,- unit,- type,- className,-}: {- value: string;+interface PropertyHoverCardProps {label: string;description?: string;unit?: string;type?: string;- className?: string;-}) => {+ children: React.ReactNode;+}++export const PropertyHoverCard = ({+ label,+ description,+ unit,+ type,+ children,+}: PropertyHoverCardProps) => {return (<HoverCard openDelay={0} closeDelay={0}>- <HoverCardTrigger asChild>- <SelectItem value={value} className={className ?? "max-w-56"}>- {label}- </SelectItem>- </HoverCardTrigger>+ <HoverCardTrigger asChild>{children}</HoverCardTrigger><HoverCardPortal><HoverCardContent hideWhenDetached align="start" side="right"><div className="mb-1 text-sm font-bold">{label}</div>@@ -56,3 +48,36 @@ export const WidgetPropertySelectItem = ({</HoverCard>);};++/**+ * Generic SelectItem with a hover-card that shows documentation for a widget property+ * (view, metric, dimension).+ */+export const WidgetPropertySelectItem = ({+ value,+ label,+ description,+ unit,+ type,+ className,+}: {+ value: string;+ label: string;+ description?: string;+ unit?: string;+ type?: string;+ className?: string;+}) => {+ return (+ <PropertyHoverCard+ label={label}+ description={description}+ unit={unit}+ type={type}+ >+ <SelectItem value={value} className={className ?? "max-w-56"}>+ {label}+ </SelectItem>+ </PropertyHoverCard>+ );+};diff --git a/web/src/pages/project/[projectId]/automations.tsx b/web/src/pages/project/[projectId]/automations.tsxnew file mode 100644index 0000000000..a1cad04652--- /dev/null+++ b/web/src/pages/project/[projectId]/automations.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/automations/components/automations";diff --git a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsxindex 987a85d692..9b5e4fd2c8 100644--- a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx@@ -12,6 +12,7 @@ import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";import PromptMetrics from "./metrics";import { useQueryParams, StringParam } from "use-query-params";import React from "react";+import { WebhookButton } from "@/src/features/automations/components/WebhookButton";export default function PromptsWithFolder() {const router = useRouter();@@ -88,19 +89,24 @@ export default function PromptsWithFolder() {href: "https://langfuse.com/docs/prompts",},actionButtonsRight: (- <ActionButton- icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}- hasAccess={hasCUDAccess}- href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ""}`}- variant="default"- limit={promptLimit}- limitValue={Number(count?.totalCount ?? 0)}- onClick={() => {- capture("prompts:new_form_open");- }}- >- New prompt- </ActionButton>+ <>+ {projectId && (+ <WebhookButton projectId={projectId} variant="secondary" />+ )}+ <ActionButton+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasCUDAccess}+ href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ""}`}+ variant="default"+ limit={promptLimit}+ limitValue={Number(count?.totalCount ?? 0)}+ onClick={() => {+ capture("prompts:new_form_open");+ }}+ >+ New prompt+ </ActionButton>+ </>),}}scrollable={showOnboarding}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex bbb072fcba..d88921839c 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -38,6 +38,7 @@ import { tableRouter } from "@/src/features/table/server/tableRouter";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";+import { automationsRouter } from "@/src/features/automations/server/router";import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";import { plainRouter } from "@/src/features/support-chat/trpc/plain";@@ -87,6 +88,7 @@ export const appRouter = createTRPCRouter({cloudStatus: cloudStatusRouter,dashboardWidgets: dashboardWidgetRouter,TableViewPresets: TableViewPresetsRouter,+ automations: automationsRouter,plain: plainRouter,});diff --git a/worker/src/__tests__/promptVersionProcessor.test.ts b/worker/src/__tests__/promptVersionProcessor.test.tsnew file mode 100644index 0000000000..a34a70ecce--- /dev/null+++ b/worker/src/__tests__/promptVersionProcessor.test.ts@@ -0,0 +1,397 @@+import { describe, it, expect, beforeEach, beforeAll, afterAll } from "vitest";+import { v4 } from "uuid";+import {+ ActionExecutionStatus,+ JobConfigState,+ TriggerEventSource,+ TriggerEventAction,+ PromptType,+} from "@langfuse/shared";+import {+ createOrgProjectAndApiKey,+ redis,+ EntityChangeEventType,+} from "@langfuse/shared/src/server";+import { ActionType, prisma } from "@langfuse/shared/src/db";+import { promptVersionProcessor } from "../features/entityChange/promptVersionProcessor";++describe("promptVersionChangeWorker", () => {+ let orgId: string;+ let projectId: string;+ let auth: string;++ beforeEach(async () => {+ // Create test organization and project+ const result = await createOrgProjectAndApiKey();+ orgId = result.orgId;+ projectId = result.projectId;+ auth = result.auth;+ });++ describe("successful trigger execution", () => {+ it("should execute webhook for matching prompt created event", async () => {+ // Create a prompt+ const promptId = v4();++ // Create a webhook action+ const actionId = v4();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId,+ type: ActionType.WEBHOOK,+ config: {+ url: "https://webhook.example.com/test",+ headers: {},+ method: "POST",+ },+ },+ });++ // Create a trigger that matches prompt created events+ const triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId,+ eventSource: TriggerEventSource.Prompt,+ status: JobConfigState.ACTIVE,+ filter: [+ {+ column: "action",+ operator: "=",+ value: "created",+ type: "string",+ },+ ],+ },+ });++ // Create automation linking trigger and action+ const automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ name: "prompt-created-automation",+ projectId,+ triggerId,+ actionId,+ },+ });++ // Create the event to process+ const event: EntityChangeEventType = {+ entityType: "prompt-version",+ projectId,+ promptId,+ action: "created",+ prompt: {+ id: promptId,+ projectId,+ name: "test-prompt",+ version: 1,+ prompt: { messages: [{ role: "user", content: "Hello" }] },+ config: null,+ tags: [],+ labels: [],+ type: PromptType.Chat,+ isActive: true,+ createdBy: "test-user",+ createdAt: new Date(),+ updatedAt: new Date(),+ commitMessage: null,+ },+ };++ // Execute the worker+ await promptVersionProcessor(event);++ // Verify automation execution was created+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId,+ automationId,+ triggerId,+ actionId,+ },+ });++ expect(executions).toHaveLength(1);+ expect(executions[0].status).toBe(ActionExecutionStatus.PENDING);+ expect(executions[0].sourceId).toBe(promptId);+ });++ it("should execute webhook for matching prompt updated event", async () => {+ // Create a prompt+ const promptId = v4();++ // Create a webhook action+ const actionId = v4();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId,+ type: ActionType.WEBHOOK,+ config: {+ url: "https://webhook.example.com/test",+ headers: {},+ method: "POST",+ },+ },+ });++ // Create a trigger that matches prompt updated events+ const triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId,+ eventSource: TriggerEventSource.Prompt,+ status: JobConfigState.ACTIVE,+ filter: [+ {+ column: "action",+ operator: "=",+ value: "updated",+ type: "string",+ },+ ],+ },+ });++ // Create automation linking trigger and action+ const automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ name: "prompt-updated-automation",+ projectId,+ triggerId,+ actionId,+ },+ });++ // Create the event to process+ const event: EntityChangeEventType = {+ entityType: "prompt-version",+ projectId,+ promptId,+ action: "updated",+ prompt: {+ id: promptId,+ projectId,+ name: "test-prompt",+ version: 2,+ prompt: { messages: [{ role: "user", content: "Hello updated" }] },+ config: null,+ tags: [],+ labels: [],+ type: PromptType.Chat,+ isActive: true,+ createdBy: "test-user",+ createdAt: new Date(),+ updatedAt: new Date(),+ commitMessage: null,+ },+ };++ // Execute the worker+ await promptVersionProcessor(event);++ // Verify automation execution was created+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId,+ automationId,+ triggerId,+ actionId,+ },+ });++ expect(executions).toHaveLength(1);+ expect(executions[0].status).toBe(ActionExecutionStatus.PENDING);+ });+ });++ it("should not execute when action filter doesn't match", async () => {+ // Create a prompt+ const promptId = v4();++ // Create a webhook action+ const actionId = v4();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId,+ type: ActionType.WEBHOOK,+ config: {+ url: "https://webhook.example.com/test",+ headers: {},+ method: "POST",+ },+ },+ });++ // Create a trigger that only matches DELETED events+ const triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId,+ eventSource: TriggerEventSource.Prompt,+ status: JobConfigState.ACTIVE,+ filter: [+ {+ column: "action",+ operator: "=",+ value: "deleted",+ type: "string",+ },+ ],+ },+ });++ // Create automation linking trigger and action+ const automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ name: "prompt-deleted-automation",+ projectId,+ triggerId,+ actionId,+ },+ });++ // Create a CREATED event (which shouldn't match the DELETED filter)+ const event: EntityChangeEventType = {+ entityType: "prompt-version",+ projectId,+ promptId,+ action: "created",+ prompt: {+ id: promptId,+ projectId,+ name: "test-prompt",+ version: 1,+ prompt: { messages: [{ role: "user", content: "Hello" }] },+ config: null,+ tags: [],+ labels: [],+ type: PromptType.Chat,+ isActive: true,+ createdBy: "test-user",+ createdAt: new Date(),+ updatedAt: new Date(),+ commitMessage: null,+ },+ };++ // Execute the worker+ await promptVersionProcessor(event);++ // Verify no automation execution was created+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId,+ automationId,+ },+ });++ expect(executions).toHaveLength(0);+ });++ it("should not execute when prompt name filter doesn't match", async () => {+ // Create a prompt+ const promptId = v4();++ // Create a webhook action+ const actionId = v4();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId,+ type: ActionType.WEBHOOK,+ config: {+ url: "https://webhook.example.com/test",+ headers: {},+ method: "POST",+ },+ },+ });++ // Create a trigger that matches CREATED events but only for specific prompt name+ const triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId,+ eventSource: TriggerEventSource.Prompt,+ status: JobConfigState.ACTIVE,+ filter: [+ {+ column: "action",+ operator: "=",+ value: "created",+ type: "string",+ },+ {+ column: "name",+ operator: "=",+ value: "target-prompt",+ type: "string",+ },+ ],+ },+ });++ // Create automation linking trigger and action+ const automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ name: "specific-prompt-automation",+ projectId,+ triggerId,+ actionId,+ },+ });++ // Create event with different prompt name+ const event: EntityChangeEventType = {+ entityType: "prompt-version",+ projectId,+ promptId,+ action: "created",+ prompt: {+ id: promptId,+ projectId,+ name: "different-prompt",+ version: 1,+ prompt: { messages: [{ role: "user", content: "Hello" }] },+ config: null,+ tags: [],+ labels: [],+ type: PromptType.Chat,+ isActive: true,+ createdBy: "test-user",+ createdAt: new Date(),+ updatedAt: new Date(),+ commitMessage: null,+ },+ };++ // Execute the worker+ await promptVersionProcessor(event);++ // Verify no automation execution was created+ const executions = await prisma.automationExecution.findMany({+ where: {+ projectId,+ automationId,+ },+ });++ expect(executions).toHaveLength(0);+ });+});diff --git a/worker/src/__tests__/signature.test.ts b/worker/src/__tests__/signature.test.tsnew file mode 100644index 0000000000..de99175379--- /dev/null+++ b/worker/src/__tests__/signature.test.ts@@ -0,0 +1,149 @@+import { describe, it, expect } from "vitest";+import {+ generateWebhookSecret,+ getDisplaySecretKey,+ generateWebhookSignature,+ createSignatureHeader,+} from "@langfuse/shared/encryption";++describe("signature.ts", () => {+ describe("generateWebhookSecret", () => {+ it("should generate a webhook secret with correct format", () => {+ const result = generateWebhookSecret();++ expect(result).toHaveProperty("secretKey");+ expect(result).toHaveProperty("displaySecretKey");++ // Secret key should be lf-whsec_ prefix + 64 hex characters (32 bytes)+ expect(result.secretKey).toMatch(/^lf-whsec_[a-f0-9]{64}$/);+ expect(result.secretKey).toHaveLength(73); // lf-whsec_ (9) + 64 hex chars++ // Display secret should be properly formatted+ expect(result.displaySecretKey).toMatch(/^lf-whsec_\.\.\.[a-f0-9]{4}$/);+ });++ it("should generate different secrets on each call", () => {+ const secret1 = generateWebhookSecret();+ const secret2 = generateWebhookSecret();++ expect(secret1.secretKey).not.toBe(secret2.secretKey);+ expect(secret1.displaySecretKey).not.toBe(secret2.displaySecretKey);+ });+ });++ describe("getDisplaySecretKey", () => {+ it("should create display version for valid secret", () => {+ const secretKey =+ "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";+ const display = getDisplaySecretKey(secretKey);++ expect(display).toBe("lf-whsec_...7890");+ });++ it("should handle short secrets with default masking", () => {+ const shortSecret = "abc123";+ const display = getDisplaySecretKey(shortSecret);++ expect(display).toBe("****");+ });+ });++ describe("generateWebhookSignature", () => {+ it("should generate consistent signatures for same inputs", () => {+ const payload = '{"test": "data"}';+ const timestamp = 1640995200; // Fixed timestamp+ const secret = "test_secret_key";++ const signature1 = generateWebhookSignature(payload, timestamp, secret);+ const signature2 = generateWebhookSignature(payload, timestamp, secret);++ expect(signature1).toBe(signature2);+ expect(signature1).toMatch(/^[a-f0-9]{64}$/); // SHA256 hex output+ });++ it("should generate different signatures for different payloads", () => {+ const timestamp = 1640995200;+ const secret = "test_secret_key";++ const sig1 = generateWebhookSignature(+ '{"test": "data1"}',+ timestamp,+ secret,+ );+ const sig2 = generateWebhookSignature(+ '{"test": "data2"}',+ timestamp,+ secret,+ );++ expect(sig1).not.toBe(sig2);+ });+ });++ describe("createSignatureHeader", () => {+ it("should create properly formatted signature header", () => {+ const payload = '{"test": "webhook"}';+ const secret = "test_webhook_secret";++ const header = createSignatureHeader(payload, secret);++ // Should match format: t=timestamp,v1=signature+ expect(header).toMatch(/^t=\d+,v1=[a-f0-9]{64}$/);+ });+ });++ describe("User webhook verification", () => {+ it("should allow users to verify our webhook signatures", () => {+ const { secretKey } = generateWebhookSecret();+ const payload = '{"event": "trace.created", "data": {"id": "123"}}';+ const signatureHeader = createSignatureHeader(payload, secretKey);++ // User verification process+ const isValid = verifyWebhookSignature(payload, signatureHeader, secretKey);+ expect(isValid).toBe(true);+ });++ it("should reject invalid signatures when users verify", () => {+ const { secretKey } = generateWebhookSecret();+ const wrongSecret = "wrong_secret";+ const payload = '{"event": "trace.created"}';+ const signatureHeader = createSignatureHeader(payload, secretKey);++ const isValid = verifyWebhookSignature(payload, signatureHeader, wrongSecret);+ expect(isValid).toBe(false);+ });+ });+});++// Example verification function that users would implement+function verifyWebhookSignature(+ payload: string,+ signatureHeader: string,+ secret: string,+): boolean {+ try {+ const [timestampPart, signaturePart] = signatureHeader.split(",");++ if (!timestampPart || !signaturePart) {+ return false;+ }++ const timestamp = parseInt(timestampPart.split("=")[1]);+ const receivedSignature = signaturePart.split("=")[1];++ if (!timestamp || !receivedSignature) {+ return false;+ }++ // Generate expected signature using our provided function+ const expectedSignature = generateWebhookSignature(payload, timestamp, secret);++ // Use timing-safe comparison+ return require("crypto").timingSafeEqual(+ Buffer.from(receivedSignature),+ Buffer.from(expectedSignature)+ );+ } catch (error) {+ return false;+ }+}diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.tsnew file mode 100644index 0000000000..f9b535e666--- /dev/null+++ b/worker/src/__tests__/webhooks.test.ts@@ -0,0 +1,495 @@+import {+ describe,+ it,+ expect,+ beforeEach,+ beforeAll,+ afterAll,+ afterEach,+} from "vitest";+import { v4 } from "uuid";+import {+ ActionExecutionStatus,+ JobConfigState,+ PromptDomainSchema,+ WebhookActionConfigWithSecrets,+} from "@langfuse/shared";+import {+ WebhookInput,+ createOrgProjectAndApiKey,+ executeWebhook,+ logger,+ redis,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import {+ createSignatureHeader,+ decrypt,+ encrypt,+} from "@langfuse/shared/encryption";+import { generateWebhookSecret } from "@langfuse/shared/encryption";+import { setupServer } from "msw/node";+import { http, HttpResponse } from "msw";++// Mock webhook server for testing HTTP requests+class WebhookTestServer {+ private server;+ private receivedRequests: Array<{+ url: string;+ method: string;+ headers: Record<string, string>;+ body: string;+ }> = [];++ constructor() {+ this.server = setupServer(+ // Default success response+ http.post("https://webhook.example.com/*", async ({ request }) => {+ this.receivedRequests.push({+ url: request.url,+ method: request.method,+ headers: Object.fromEntries(request.headers.entries()),+ body: JSON.stringify(await request.json()),+ });+ return HttpResponse.json({ success: true }, { status: 200 });+ }),++ // Error response endpoint+ http.post("https://webhook-error.example.com/*", async ({ request }) => {+ this.receivedRequests.push({+ url: request.url,+ method: request.method,+ headers: Object.fromEntries(request.headers.entries()),+ body: JSON.stringify(await request.json()),+ });+ return HttpResponse.json(+ { error: "Internal Server Error" },+ { status: 500 },+ );+ }),++ // Timeout endpoint+ http.post("https://webhook-timeout.example.com/*", () => {+ return HttpResponse.error();+ }),+ );+ }++ setup() {+ this.server.listen();+ }++ reset() {+ this.receivedRequests = [];+ this.server.resetHandlers();+ }++ teardown() {+ this.server.close();+ }++ getReceivedRequests() {+ return this.receivedRequests;+ }++ getLastRequest() {+ return this.receivedRequests[this.receivedRequests.length - 1];+ }+}++const webhookServer = new WebhookTestServer();++describe("Webhook Integration Tests", () => {+ let projectId: string;+ let triggerId: string;+ let actionId: string;+ let automationId: string;+ let promptId: string;+ let executionId: string;++ beforeAll(() => {+ webhookServer.setup();+ });++ beforeEach(async () => {+ webhookServer.reset();++ // Create test project+ ({ projectId } = await createOrgProjectAndApiKey());++ // Create test prompt+ promptId = v4();+ await prisma.prompt.create({+ data: {+ id: promptId,+ projectId,+ name: "test-prompt",+ version: 1,+ type: "text",+ prompt: { text: "Hello {{name}}" },+ createdBy: "test-user",+ },+ });++ // Create test trigger+ triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId,+ eventSource: "prompt-version",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ // Create test action+ actionId = v4();+ const { secretKey, displaySecretKey } = generateWebhookSecret();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://webhook.example.com/test",+ headers: {+ "Content-Type": "application/json",+ "X-Custom-Header": "test-value",+ },+ apiVersion: { prompt: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ // Link trigger to action+ automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ projectId,+ triggerId,+ actionId,+ name: "Test Automation",+ },+ });+ executionId = v4();+ });++ afterEach(() => {+ webhookServer.reset();+ });++ afterAll(() => {+ webhookServer.teardown();+ });++ describe("executeWebhook function", () => {+ it("should execute webhook successfully with signature", async () => {+ // Get the full prompt for the payload+ const fullPrompt = await prisma.prompt.findUnique({+ where: { id: promptId },+ });++ const webhookInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ prompt: PromptDomainSchema.parse(fullPrompt),+ action: "created",+ type: "prompt-version",+ },+ };++ await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ triggerId,+ automationId,+ actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: webhookInput.executionId,+ input: webhookInput,+ },+ });++ await executeWebhook(webhookInput);++ // Verify webhook request was made+ const requests = webhookServer.getReceivedRequests();+ expect(requests).toHaveLength(1);++ const request = requests[0];+ expect(request.url).toBe("https://webhook.example.com/test");+ expect(request.method).toBe("POST");+ expect(request.headers["content-type"]).toBe("application/json");+ expect(request.headers["x-custom-header"]).toBe("test-value");++ expect(request.headers["x-langfuse-signature"]).toMatch(+ /^t=\d+,v1=[a-f0-9]+$/,+ );++ // check signature+ const signature = request.headers["x-langfuse-signature"];+ const payload = JSON.parse(request.body);++ const action = await prisma.action.findUnique({+ where: { id: actionId },+ });++ const secretKey = (action?.config as WebhookActionConfigWithSecrets)+ ?.secretKey;++ if (!secretKey) {+ throw new Error("Action has no secret key");+ }++ const decryptedSecret = decrypt(secretKey);+ const expectedSignature = createSignatureHeader(+ JSON.stringify(payload),+ decryptedSecret,+ );++ expect(signature).toBe(expectedSignature);++ expect(payload.id).toBe(webhookInput.executionId);+ expect(payload.type).toBe("prompt-version");+ expect(payload.action).toBe("created");+ expect(payload.prompt.name).toBe("test-prompt");+ expect(payload.prompt.version).toBe(1);+ expect(payload.timestamp).toBeDefined();+ expect(payload.prompt.createdAt).toBeDefined();+ expect(payload.prompt.updatedAt).toBeDefined();++ // Verify prompt is the last field in the payload+ const payloadKeys = Object.keys(payload);+ expect(payloadKeys[payloadKeys.length - 1]).toBe("prompt");++ // Verify database execution record was updated+ const execution = await prisma.automationExecution.findUnique({+ where: { id: executionId },+ });+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);+ expect(execution?.output).toMatchObject({+ httpStatus: 200,+ responseBody: '{"success":true}',+ });+ expect(execution?.startedAt).toBeDefined();+ expect(execution?.finishedAt).toBeDefined();+ });++ it("should fail webhook execution if secret key does not exist and retry the bull job", async () => {+ const fullPrompt = await prisma.prompt.findUnique({+ where: { id: promptId },+ });++ const executionId = v4();++ await prisma.action.update({+ where: { id: actionId },+ data: {+ config: {+ type: "WEBHOOK",+ url: "https://webhook-error.example.com/test",+ headers: { "Content-Type": "application/json" },+ apiVersion: { prompt: "v1" },+ secretKey: null, // Explicitly set secret to null+ },+ },+ });++ await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ triggerId,+ automationId,+ actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: v4(),+ input: {+ promptName: "test-prompt",+ promptVersion: 1,+ action: "created",+ type: "prompt-version",+ },+ },+ });++ const webhookInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ prompt: PromptDomainSchema.parse(fullPrompt),+ action: "created",+ type: "prompt-version",+ },+ };++ await expect(executeWebhook(webhookInput)).rejects.toThrow(+ "Webhook config has no secret key, failing webhook execution",+ );++ const execution = await prisma.automationExecution.findUnique({+ where: { id: executionId },+ });++ expect(execution?.status).toBe(ActionExecutionStatus.PENDING);+ });++ it("should handle webhook endpoint returning error", async () => {+ const fullPrompt = await prisma.prompt.findUnique({+ where: { id: promptId },+ });++ const action = await prisma.action.findUnique({+ where: { id: actionId },+ });++ if (!action) {+ throw new Error("Action not found");+ }++ await prisma.action.update({+ where: { id: actionId },+ data: {+ projectId,+ type: "WEBHOOK",+ config: {+ ...(action.config as WebhookActionConfigWithSecrets),+ url: "https://webhook-error.example.com/test",+ },+ },+ });++ await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ triggerId,+ automationId,+ actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: v4(),+ input: {+ promptName: "test-prompt",+ promptVersion: 1,+ action: "created",+ type: "prompt-version",+ },+ },+ });+ // Create action pointing to error endpoint+ const webhookInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ prompt: PromptDomainSchema.parse(fullPrompt),+ action: "created",+ type: "prompt-version",+ },+ };++ await executeWebhook(webhookInput);++ // Verify execution was marked as error+ const execution = await prisma.automationExecution.findUnique({+ where: { id: executionId },+ });+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);+ expect(execution?.error).toContain(+ `Webhook does not return 200: failed with status 500 for url https://webhook-error.example.com/test and project ${projectId}`,+ );+ expect(execution?.output).toMatchObject({+ httpStatus: 500,+ responseBody: '{"error":"Internal Server Error"}',+ });+ });++ it("should disable trigger after 5 consecutive failures", async () => {+ const fullPrompt = await prisma.prompt.findUnique({+ where: { id: promptId },+ });++ const action = await prisma.action.findUnique({+ where: { id: actionId },+ });++ if (!action) {+ throw new Error("Action not found");+ }++ await prisma.action.update({+ where: { id: actionId },+ data: {+ projectId,+ type: "WEBHOOK",+ config: {+ ...(action.config as WebhookActionConfigWithSecrets),+ url: "https://webhook-error.example.com/test",+ },+ },+ });++ // Execute webhook 5 times to trigger consecutive failures+ for (let i = 0; i < 5; i++) {+ const executionId = v4();++ await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ triggerId,+ automationId,+ actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: v4(),+ input: {+ promptName: "test-prompt",+ promptVersion: 1,+ action: "created",+ type: "prompt-version",+ },+ },+ });++ const webhookInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ prompt: PromptDomainSchema.parse(fullPrompt),+ action: "created",+ type: "prompt-version",+ },+ };++ await executeWebhook(webhookInput);++ // Verify execution was marked as error+ const execution = await prisma.automationExecution.findUnique({+ where: { id: executionId },+ });++ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);+ expect(execution?.error).toContain(+ `Webhook does not return 200: failed with status 500 for url https://webhook-error.example.com/test and project ${projectId}`,+ );+ }++ // Verify trigger was disabled after 5 consecutive failures+ const trigger = await prisma.trigger.findUnique({+ where: { id: triggerId },+ });+ expect(trigger?.status).toBe(JobConfigState.INACTIVE);+ });+ });+});diff --git a/worker/src/app.ts b/worker/src/app.tsindex 4aec1b8bcd..ca778e25ed 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -30,6 +30,7 @@ import {BlobStorageIntegrationQueue,DeadLetterRetryQueue,IngestionQueue,+ webhookProcessor,} from "@langfuse/shared/src/server";import { env } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";@@ -54,6 +55,7 @@ import {import { batchActionQueueProcessor } from "./queues/batchActionQueue";import { scoreDeleteProcessor } from "./queues/scoreDelete";import { DlqRetryService } from "./services/dlq/dlqRetryService";+import { entityChangeQueueProcessor } from "./queues/entityChangeQueue";const app = express();@@ -338,6 +340,22 @@ if (env.QUEUE_CONSUMER_DEAD_LETTER_RETRY_QUEUE_IS_ENABLED === "true") {);}+if (env.QUEUE_CONSUMER_WEBHOOK_QUEUE_IS_ENABLED === "true") {+ WorkerManager.register(QueueName.WebhookQueue, webhookProcessor, {+ concurrency: env.LANGFUSE_WEBHOOK_QUEUE_PROCESSING_CONCURRENCY,+ });+}++if (env.QUEUE_CONSUMER_ENTITY_CHANGE_QUEUE_IS_ENABLED === "true") {+ WorkerManager.register(+ QueueName.EntityChangeQueue,+ entityChangeQueueProcessor,+ {+ concurrency: env.LANGFUSE_ENTITY_CHANGE_QUEUE_PROCESSING_CONCURRENCY,+ },+ );+}+process.on("SIGINT", () => onShutdown("SIGINT"));process.on("SIGTERM", () => onShutdown("SIGTERM"));diff --git a/worker/src/env.ts b/worker/src/env.tsindex 1e7c331ccc..96bdcef001 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -14,6 +14,8 @@ const EnvSchema = z.object({.max(65536, `options.port should be >= 0 and < 65536`).default(3030),+ LANGFUSE_CACHE_AUTOMATIONS_ENABLED: z.enum(["true", "false"]).default("true"),+ LANGFUSE_CACHE_AUTOMATIONS_TTL_SECONDS: z.coerce.number().default(60),LANGFUSE_S3_BATCH_EXPORT_ENABLED: z.enum(["true", "false"]).default("false"),LANGFUSE_S3_BATCH_EXPORT_BUCKET: z.string().optional(),LANGFUSE_S3_BATCH_EXPORT_PREFIX: z.string().default(""),@@ -181,6 +183,12 @@ const EnvSchema = z.object({QUEUE_CONSUMER_DEAD_LETTER_RETRY_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("false"),+ QUEUE_CONSUMER_WEBHOOK_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),+ QUEUE_CONSUMER_ENTITY_CHANGE_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),// Core data S3 upload - Langfuse CloudLANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: z@@ -229,6 +237,15 @@ const EnvSchema = z.object({LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES: z.enum(["true", "false"]).default("false"),++ LANGFUSE_WEBHOOK_QUEUE_PROCESSING_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(5),+ LANGFUSE_ENTITY_CHANGE_QUEUE_PROCESSING_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(2),});export const env: z.infer<typeof EnvSchema> =diff --git a/worker/src/features/entityChange/entityChangeWorker.ts b/worker/src/features/entityChange/entityChangeWorker.tsnew file mode 100644index 0000000000..816a0f9cd5--- /dev/null+++ b/worker/src/features/entityChange/entityChangeWorker.ts@@ -0,0 +1,43 @@+import {+ getCurrentSpan,+ logger,+ type EntityChangeEventType,+} from "@langfuse/shared/src/server";+import { promptVersionProcessor } from "./promptVersionProcessor";++/**+ * Generic entity change worker that delegates to specific entity handlers+ */+export const entityChangeWorker = async (+ event: EntityChangeEventType,+): Promise<void> => {+ try {+ logger.info(+ `Processing entity change event for entity ${event.entityType}`,+ { event: JSON.stringify(event, null, 2) },+ );++ const span = getCurrentSpan();++ if (span) {+ span.setAttribute("entityType", event.entityType);+ span.setAttribute("projectId", event.projectId);+ span.setAttribute("promptId", event.promptId);+ span.setAttribute("action", event.action);+ }++ switch (event.entityType) {+ case "prompt-version":+ return await promptVersionProcessor(event);+ default:+ throw new Error(+ `Unsupported entity type: ${(event as any).entityType}`,+ );+ }+ } catch (error) {+ logger.error(+ `Failed to process entity change event for entity ${event.entityType}: ${error}`,+ );+ throw error;+ }+};diff --git a/worker/src/features/entityChange/promptVersionProcessor.ts b/worker/src/features/entityChange/promptVersionProcessor.tsnew file mode 100644index 0000000000..4aadef51eb--- /dev/null+++ b/worker/src/features/entityChange/promptVersionProcessor.ts@@ -0,0 +1,212 @@+import {+ type TriggerEventAction,+ jsonSchemaNullable,+ InternalServerError,+} from "@langfuse/shared";+import {+ getTriggerConfigurations,+ getActionById,+ logger,+ WebhookQueue,+ QueueName,+ QueueJobs,+ InMemoryFilterService,+ type PromptResult,+ getAutomations,+ EntityChangeEventType,+} from "@langfuse/shared/src/server";+import { TriggerEventSource } from "@langfuse/shared";+import { ActionExecutionStatus, JobConfigState } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { v4 } from "uuid";++/**+ * Process prompt change events with in-memory filtering+ */+export const promptVersionProcessor = async (+ event: EntityChangeEventType,+): Promise<void> => {+ try {+ logger.info(+ `Processing prompt version change event for prompt ${event.promptId} for project ${event.projectId}`,+ { event: JSON.stringify(event, null, 2) },+ );++ // Get active prompt triggers+ const triggers = await getTriggerConfigurations({+ projectId: event.projectId,+ eventSource: TriggerEventSource.Prompt,+ status: JobConfigState.ACTIVE,+ });++ logger.debug(`Found ${triggers.length} active prompt triggers`, {+ promptId: event.promptId,+ projectId: event.projectId,+ action: event.action,+ });++ // Process each trigger+ for (const trigger of triggers) {+ try {+ // Create a unified data object that includes both prompt data and the action+ const eventData = {+ ...event.prompt,+ action: event.action,+ };++ // Create a field mapper for all data including action+ const fieldMapper = (data: typeof eventData, column: string) => {+ switch (column) {+ case "action":+ return data.action;+ case "Name":+ return data.name;+ default:+ return undefined;+ }+ };++ // Use InMemoryFilterService for all filtering including actions+ const eventMatches = InMemoryFilterService.evaluateFilter(+ eventData,+ trigger.filter,+ fieldMapper,+ );++ if (!eventMatches) {+ logger.debug(`Event doesn't match trigger ${trigger.id} filters`, {+ promptId: event.promptId,+ projectId: event.projectId,+ action: event.action,+ });+ continue;+ }++ logger.debug(`Trigger ${trigger.id} matches, executing actions`, {+ promptId: event.promptId,+ projectId: event.projectId,+ action: event.action,+ });++ if (trigger.actionIds.length !== 1) {+ logger.debug(+ `Trigger ${trigger.id} for project ${trigger.projectId} has multiple or no actions. This is not expected`,+ );+ throw new InternalServerError(+ `Trigger ${trigger.id} for project ${trigger.projectId} has multiple or no actions. This is not expected`,+ );+ }++ await Promise.all(+ trigger.actionIds.map(async (actionId) =>+ executeWebhookAction({+ promptData: {+ ...event.prompt,+ resolutionGraph: null,+ },+ action: event.action,+ triggerId: trigger.id,+ actionId,+ projectId: event.projectId,+ }),+ ),+ );+ } catch (error) {+ logger.error(+ `Error processing trigger ${trigger.id} for prompt ${event.promptId} for project ${event.projectId}: ${error}`,+ );+ // Continue processing other triggers instead of failing the entire operation+ }+ }+ } catch (error) {+ logger.error(+ `Failed to process prompt version change event for prompt ${event.promptId} for project ${event.projectId}: ${error}`,+ );+ throw error; // Re-throw to trigger retry mechanism+ }+};++/**+ * Execute a webhook action for a prompt version change+ */+async function executeWebhookAction({+ promptData,+ action,+ triggerId,+ actionId,+ projectId,+}: {+ promptData: PromptResult;+ action: string;+ triggerId: string;+ actionId: string;+ projectId: string;+}): Promise<void> {+ // Get action configuration+ const actionConfig = await getActionById({+ projectId,+ actionId,+ });++ if (!actionConfig) {+ throw new Error(`Action ${actionId} not found`);+ }++ const automations = await getAutomations({+ projectId,+ actionId,+ });++ if (automations.length !== 1) {+ throw new InternalServerError(+ `Expected 1 automation for action ${actionId}, got ${automations.length}`,+ );+ }++ const executionId = v4();++ // Create execution record+ const execution = await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ automationId: automations[0].id,+ triggerId: triggerId,+ actionId: actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: promptData.id,+ input: {+ promptName: promptData.name,+ promptVersion: promptData.version,+ promptId: promptData.id,+ automationId: automations[0].id,+ type: "prompt-version",+ },+ },+ });++ logger.debug(+ `Created action execution ${execution.id} for project ${projectId} and trigger ${triggerId} and action ${actionId}`,+ );++ // Queue webhook+ await WebhookQueue.getInstance()?.add(QueueName.WebhookQueue, {+ timestamp: new Date(),+ id: v4(),+ payload: {+ projectId,+ automationId: automations[0].id,+ executionId: executionId,+ payload: {+ action: action as TriggerEventAction,+ type: "prompt-version",+ prompt: {+ ...promptData,+ prompt: jsonSchemaNullable.parse(promptData.prompt),+ config: jsonSchemaNullable.parse(promptData.config),+ },+ },+ },+ name: QueueJobs.WebhookJob,+ });+}diff --git a/worker/src/queues/entityChangeQueue.ts b/worker/src/queues/entityChangeQueue.tsnew file mode 100644index 0000000000..89d8597a5d--- /dev/null+++ b/worker/src/queues/entityChangeQueue.ts@@ -0,0 +1,16 @@+import { Job } from "bullmq";+import { logger, QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";+import { entityChangeWorker } from "../features/entityChange/entityChangeWorker";++export const entityChangeQueueProcessor = async (+ job: Job<TQueueJobTypes[QueueName.EntityChangeQueue]>,+) => {+ logger.debug(+ `Processing entity change event for entity ${job.data.payload.entityType}, event: ${JSON.stringify(+ job.data,+ null,+ 2,+ )}`,+ );+ return await entityChangeWorker(job.data.payload);+};\ No newline at end of file