Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(notifications): add project notification channels (#14942)

Tobias Wochinger26b44d614f9b
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index f32b8b2342..ac1305cd59 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -5,6 +5,10 @@ import { z } from "zod";
export enum TriggerEventSource {
Prompt = "prompt",
Monitor = "monitor",
+ // ProjectNotification groups platform "something went wrong" events (e.g.
+ // failed exports, blocked evaluators). The specific event lives in the
+ // trigger's eventActions.
+ ProjectNotification = "project-notification",
}
export const EventActionSchema = z.enum(["created", "updated", "deleted"]);
@@ -14,8 +18,23 @@ export type TriggerEventAction = z.infer<typeof EventActionSchema>;
export const TriggerEventSourceSchema = z.enum([
TriggerEventSource.Prompt,
TriggerEventSource.Monitor,
+ TriggerEventSource.ProjectNotification,
]);
+/**
+ * ProjectNotificationEventTypeSchema enumerates the platform "something went
+ * wrong" events routable to project notification channels. Stored as a
+ * `project-notification`-source trigger's eventActions. Client-safe so
+ * settings UI can list them. Add new event types here.
+ */
+export const ProjectNotificationEventTypeSchema = z.enum([
+ "blob-export-failed",
+ "evaluator-blocked",
+]);
+export type ProjectNotificationEventType = z.infer<
+ typeof ProjectNotificationEventTypeSchema
+>;
+
export type TriggerDomain = Omit<
Trigger,
"filter" | "eventSource" | "eventActions"
@@ -43,7 +62,7 @@ export type ActionDomainWithSecrets = Omit<Action, "config"> & {
export const ActionTypeSchema = z.enum(["WEBHOOK", "SLACK", "GITHUB_DISPATCH"]);
export const AvailableWebhookApiSchema = z.partialRecord(
- z.enum(["prompt", "monitor"]),
+ z.enum(["prompt", "monitor", "project-notification"]),
z.enum(["v1"]),
);
diff --git a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts
index 5e1f8c9565..2410f79a17 100644
--- a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts
+++ b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts
@@ -1,9 +1,5 @@
-import { slackifyMarkdown } from "slackify-markdown";
-
-import {
- escapeSlackMrkdwn,
- type SlackMessage,
-} from "../../../server/services/SlackService";
+import { buildColoredAttachmentSlackMessage } from "../../../server/services/buildColoredAttachmentSlackMessage";
+import { type SlackMessage } from "../../../server/services/SlackService";
import { type MonitorAlert, type MonitorSeverity } from "../types";
/** severityVisual maps MonitorSeverity to its Slack attachment color. */
@@ -20,51 +16,11 @@ const severityVisual: Record<MonitorSeverity, { color: string }> = {
export function buildMonitorAlertSlackMessage(
alert: MonitorAlert,
): SlackMessage {
- const { color } = severityVisual[alert.severity];
- const title = escapeSlackMrkdwn(alert.message.title);
- const titleText = alert.permalink
- ? `*<${alert.permalink}|${title}>*`
- : `*${title}*`;
- const blocks: any[] = [
- {
- type: "section",
- text: { type: "mrkdwn", text: titleText },
- },
- {
- type: "section",
- text: { type: "mrkdwn", text: slackifyMarkdown(alert.message.body) },
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: `⏱ ${alert.timestamp.toISOString()}`,
- },
- ],
- },
- ...(alert.permalink
- ? [
- {
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View in Langfuse",
- emoji: true,
- },
- url: alert.permalink,
- },
- ],
- },
- ]
- : []),
- ];
- // Color bar renders only on attachment-nested blocks; top-level text/blocks would duplicate above it.
- return {
- blocks: [],
- attachments: [{ color, fallback: alert.message.title, blocks }],
- };
+ return buildColoredAttachmentSlackMessage({
+ color: severityVisual[alert.severity].color,
+ title: alert.message.title,
+ body: alert.message.body,
+ timestamp: alert.timestamp,
+ url: alert.permalink,
+ });
}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index f5c8aa922d..462f1c9ef2 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -117,6 +117,7 @@ export * from "./redis/s3SlowdownTracking";
export * from "./redis/ingestionFailureTracking";
export * from "./auth/types";
export * from "./queues";
+export * from "./notifications";
export * from "./orderByToPrisma";
export * from "./filterToPrisma";
export * from "./instrumentation";
@@ -148,6 +149,7 @@ export * from "./services/blockEvaluatorConfigs";
export * from "./services/getProjectAdminEmails";
export * from "./clickhouse/measureAndReturn";
export * from "./services/SlackService";
+export * from "./services/buildColoredAttachmentSlackMessage";
export * from "./tableMappings";
export * from "./otel";
export * from "./datasets/executeWithDatasetServiceStrategy";
diff --git a/packages/shared/src/server/notifications/buildProjectNotificationSlackMessage.ts b/packages/shared/src/server/notifications/buildProjectNotificationSlackMessage.ts
new file mode 100644
index 0000000000..352e5f1915
--- /dev/null
+++ b/packages/shared/src/server/notifications/buildProjectNotificationSlackMessage.ts
@@ -0,0 +1,38 @@
+import { buildColoredAttachmentSlackMessage } from "../services/buildColoredAttachmentSlackMessage";
+import { type SlackMessage } from "../services/SlackService";
+import {
+ type ProjectNotificationEvent,
+ type ProjectNotificationEventType,
+ type ProjectNotificationSeverity,
+} from "./types";
+
+/** projectNotificationTitle maps an event type to a human-readable Slack title. */
+const projectNotificationTitle: Record<ProjectNotificationEventType, string> = {
+ "blob-export-failed": "Blob storage export failed",
+ "evaluator-blocked": "Evaluator blocked",
+};
+
+/** severityColor maps a project-notification severity to its Slack attachment color. */
+const severityColor: Record<ProjectNotificationSeverity, string> = {
+ ALERT: "#dc3545",
+ WARNING: "#ffc107",
+ INFO: "#6c757d",
+};
+
+/**
+ * buildProjectNotificationSlackMessage renders a project notification event
+ * into a Slack Block Kit message, reusing the monitor-alert layout.
+ */
+export function buildProjectNotificationSlackMessage(
+ event: ProjectNotificationEvent,
+): SlackMessage {
+ const title = `${projectNotificationTitle[event.eventType]}: ${event.resourceName}`;
+ return buildColoredAttachmentSlackMessage({
+ color: severityColor[event.severity],
+ title,
+ body: event.message,
+ timestamp: new Date(),
+ url: event.url,
+ contextText: `Project: ${event.projectName}`,
+ });
+}
diff --git a/packages/shared/src/server/notifications/dispatchProjectNotification.test.ts b/packages/shared/src/server/notifications/dispatchProjectNotification.test.ts
new file mode 100644
index 0000000000..063209f3af
--- /dev/null
+++ b/packages/shared/src/server/notifications/dispatchProjectNotification.test.ts
@@ -0,0 +1,187 @@
+import { vi, describe, it, expect, beforeEach } from "vitest";
+
+const { add, getInstance, createExecution } = vi.hoisted(() => ({
+ add: vi.fn(),
+ getInstance: vi.fn(),
+ createExecution: vi.fn(),
+}));
+
+vi.mock("../redis/webhookQueue", () => ({
+ WebhookQueue: { getInstance: () => getInstance() },
+}));
+
+vi.mock("../repositories/automation-repository", () => ({
+ getAutomations: vi.fn(),
+}));
+
+vi.mock("../services/getProjectAdminEmails", () => ({
+ getProjectAdminEmails: vi.fn(),
+}));
+
+vi.mock(
+ "../services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail",
+ () => ({ sendBlobStorageExportFailedEmail: vi.fn() }),
+);
+
+vi.mock("../services/email/evaluatorBlocked/sendEvaluatorBlockedEmail", () => ({
+ sendEvaluatorBlockedEmail: vi.fn(),
+}));
+
+// No importOriginal: db.ts imports the server barrel, which circularly imports
+// this module under test; re-export the needed enums from @prisma/client instead.
+vi.mock("../../db", async () => {
+ const prismaClient = await import("@prisma/client");
+ return {
+ ActionExecutionStatus: prismaClient.ActionExecutionStatus,
+ JobConfigState: prismaClient.JobConfigState,
+ prisma: { automationExecution: { create: createExecution } },
+ };
+});
+
+vi.mock("../../env", () => ({
+ env: {
+ EMAIL_FROM_ADDRESS: undefined as string | undefined,
+ SMTP_CONNECTION_URL: undefined as string | undefined,
+ NEXTAUTH_URL: undefined as string | undefined,
+ CLOUD_CRM_EMAIL: undefined as string | undefined,
+ },
+}));
+
+import { JobConfigState } from "@prisma/client";
+import { type AutomationDomain } from "../../domain/automations";
+import { env } from "../../env";
+import { getAutomations } from "../repositories/automation-repository";
+import { sendBlobStorageExportFailedEmail } from "../services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail";
+import { sendEvaluatorBlockedEmail } from "../services/email/evaluatorBlocked/sendEvaluatorBlockedEmail";
+import { getProjectAdminEmails } from "../services/getProjectAdminEmails";
+import { dispatchProjectNotification } from "./dispatchProjectNotification";
+import { type ProjectNotificationEvent } from "./types";
+
+const blobEvent: ProjectNotificationEvent = {
+ eventType: "blob-export-failed",
+ severity: "ALERT",
+ projectId: "proj_1",
+ projectName: "My Project",
+ resourceId: "res_1",
+ resourceName: "my-export-bucket",
+ message: "Blob storage export failed.",
+ url: "https://cloud.langfuse.com/x",
+};
+
+const evaluatorEvent: ProjectNotificationEvent = {
+ eventType: "evaluator-blocked",
+ severity: "ALERT",
+ projectId: "proj_1",
+ projectName: "My Project",
+ resourceId: "cfg_1",
+ resourceName: "Toxicity",
+ message: "Evaluator was blocked.",
+ url: "https://cloud.langfuse.com/x",
+ blockReason: "LLM_CONNECTION_MISSING",
+ evalTemplateId: "tpl_1",
+};
+
+const automation = (
+ id: string,
+ status: JobConfigState,
+ eventActions: string[],
+): AutomationDomain =>
+ ({
+ id,
+ name: id,
+ trigger: { id: `trigger-${id}`, status, eventActions },
+ action: { id: `action-${id}`, type: "WEBHOOK" },
+ }) as unknown as AutomationDomain;
+
+const emailEnvValues = {
+ EMAIL_FROM_ADDRESS: "[email protected]",
+ SMTP_CONNECTION_URL: "smtp://localhost",
+ NEXTAUTH_URL: "https://cloud.langfuse.com",
+ CLOUD_CRM_EMAIL: "[email protected]",
+};
+
+const setEmailEnv = (values: Partial<typeof env>) => {
+ env.EMAIL_FROM_ADDRESS = values.EMAIL_FROM_ADDRESS;
+ env.SMTP_CONNECTION_URL = values.SMTP_CONNECTION_URL;
+ env.NEXTAUTH_URL = values.NEXTAUTH_URL;
+ env.CLOUD_CRM_EMAIL = values.CLOUD_CRM_EMAIL;
+};
+
+describe("dispatchProjectNotification", () => {
+ beforeEach(() => {
+ add.mockReset();
+ getInstance.mockReset();
+ getInstance.mockReturnValue({ add });
+ createExecution.mockReset();
+ vi.mocked(getAutomations).mockReset();
+ vi.mocked(getAutomations).mockResolvedValue([]);
+ vi.mocked(getProjectAdminEmails).mockReset();
+ vi.mocked(getProjectAdminEmails).mockResolvedValue([]);
+ vi.mocked(sendBlobStorageExportFailedEmail).mockReset();
+ vi.mocked(sendEvaluatorBlockedEmail).mockReset();
+ setEmailEnv({});
+ });
+
+ it("enqueues a webhook job only for active channels with the event enabled", async () => {
+ vi.mocked(getAutomations).mockResolvedValue([
+ automation("a1", JobConfigState.ACTIVE, ["blob-export-failed"]),
+ automation("a2", JobConfigState.ACTIVE, ["evaluator-blocked"]),
+ automation("a3", JobConfigState.INACTIVE, ["blob-export-failed"]),
+ automation("a4", JobConfigState.ACTIVE, [
+ "blob-export-failed",
+ "evaluator-blocked",
+ ]),
+ ]);
+
+ await dispatchProjectNotification({
+ projectId: "proj_1",
+ event: blobEvent,
+ });
+
+ // a1 and a4 have the event enabled; a2 has it toggled off, a3 is inactive.
+ const enqueuedAutomationIds = add.mock.calls.map(
+ (call) => call[1].payload.automationId,
+ );
+ expect(enqueuedAutomationIds.sort()).toEqual(["a1", "a4"]);
+ });
+
+ it("sends the evaluator-blocked email per recipient with the resolution url", async () => {
+ setEmailEnv(emailEnvValues);
+ vi.mocked(getProjectAdminEmails).mockResolvedValue([
+ ]);
+
+ await dispatchProjectNotification({
+ projectId: "proj_1",
+ event: evaluatorEvent,
+ });
+
+ expect(sendEvaluatorBlockedEmail).toHaveBeenCalledTimes(2);
+ expect(sendEvaluatorBlockedEmail).toHaveBeenCalledWith({
+ env: emailEnvValues,
+ projectName: "My Project",
+ evaluatorName: "Toxicity",
+ blockReason: "LLM_CONNECTION_MISSING",
+ blockMessage: "Evaluator was blocked.",
+ // LLM_CONNECTION_MISSING resolves to the llm-connections settings page
+ resolutionUrl:
+ "https://cloud.langfuse.com/project/proj_1/settings/llm-connections",
+ receiverEmail: "[email protected]",
+ });
+ });
+
+ it("still sends admin emails when the channel dispatch throws", async () => {
+ setEmailEnv(emailEnvValues);
+ // A Postgres/Redis/queue error in the channel path must not suppress email.
+ vi.mocked(getAutomations).mockRejectedValue(new Error("db down"));
+ vi.mocked(getProjectAdminEmails).mockResolvedValue(["[email protected]"]);
+
+ await expect(
+ dispatchProjectNotification({ projectId: "proj_1", event: blobEvent }),
+ ).resolves.toBeUndefined();
+
+ expect(add).not.toHaveBeenCalled();
+ expect(sendBlobStorageExportFailedEmail).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/shared/src/server/notifications/dispatchProjectNotification.ts b/packages/shared/src/server/notifications/dispatchProjectNotification.ts
new file mode 100644
index 0000000000..24b7e4f0c8
--- /dev/null
+++ b/packages/shared/src/server/notifications/dispatchProjectNotification.ts
@@ -0,0 +1,203 @@
+import { randomUUID } from "crypto";
+
+import { ActionExecutionStatus, JobConfigState, prisma } from "../../db";
+import { TriggerEventSource } from "../../domain/automations";
+import { env } from "../../env";
+import { getEvaluatorBlockResolutionPath } from "../../features/evals/evalConfigBlocking";
+import { logger } from "../logger";
+import { QueueJobs, QueueName } from "../queues";
+import { WebhookQueue } from "../redis/webhookQueue";
+import { getAutomations } from "../repositories/automation-repository";
+import { sendBlobStorageExportFailedEmail } from "../services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail";
+import { sendEvaluatorBlockedEmail } from "../services/email/evaluatorBlocked/sendEvaluatorBlockedEmail";
+import { getProjectAdminEmails } from "../services/getProjectAdminEmails";
+import { type ProjectNotificationEvent } from "./types";
+
+/** ProjectNotificationEmailEnv is the SMTP/env slice the email templates receive. */
+type ProjectNotificationEmailEnv = {
+ EMAIL_FROM_ADDRESS: string;
+ SMTP_CONNECTION_URL: string;
+ NEXTAUTH_URL: string;
+ CLOUD_CRM_EMAIL: string | undefined;
+};
+
+/**
+ * dispatchProjectNotification is the single entry point for routing a platform
+ * "something went wrong" event to a project's notification channels AND its
+ * admin emails — producers make this one call and nothing else. It (1) creates
+ * a PENDING AutomationExecution and enqueues one webhook job per active
+ * `project-notification` automation that has the event type enabled in its
+ * trigger.eventActions, and (2) resolves project admin recipients and sends
+ * the event's email template (guarding the SMTP env centrally). Producers own
+ * their own dedup (e.g. the blob-storage cooldown claim); this service is
+ * stateless and does not add a second dedup layer.
+ */
+export async function dispatchProjectNotification({
+ projectId,
+ event,
+}: {
+ projectId: string;
+ event: ProjectNotificationEvent;
+}): Promise<void> {
+ // Channel dispatch must never suppress the admin email — the email is the
+ // always-on floor (worst case for blob-export, whose 24h cooldown claim is
+ // already committed by the time we get here). Isolate channel failures.
+ try {
+ await dispatchToChannels({ projectId, event });
+ } catch (error) {
+ logger.error(
+ `dispatchProjectNotification: channel dispatch failed for ${event.eventType} in project ${projectId}; continuing to admin emails`,
+ error,
+ );
+ }
+ await dispatchAdminEmails({ projectId, event });
+}
+
+async function dispatchToChannels({
+ projectId,
+ event,
+}: {
+ projectId: string;
+ event: ProjectNotificationEvent;
+}): Promise<void> {
+ const queue = WebhookQueue.getInstance();
+ if (!queue) {
+ logger.warn(
+ `dispatchProjectNotification: WebhookQueue unavailable; skipping channel dispatch of ${event.eventType} for project ${projectId}`,
+ );
+ return;
+ }
+
+ const automations = await getAutomations({
+ projectId,
+ eventSource: TriggerEventSource.ProjectNotification,
+ });
+
+ // trigger.eventActions holds the event types the channel has enabled (the
+ // per-event toggles in the settings section); channels are created with all
+ // events enabled.
+ const matching = automations.filter(
+ (automation) =>
+ automation.trigger.status === JobConfigState.ACTIVE &&
+ (automation.trigger.eventActions as string[]).includes(event.eventType),
+ );
+
+ for (const automation of matching) {
+ const executionId = randomUUID();
+
+ // Mirror the prompt-version path: a PENDING execution row per job, which
+ // the worker resolves to COMPLETED/ERROR (and uses for auto-disable).
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ automationId: automation.id,
+ triggerId: automation.trigger.id,
+ actionId: automation.action.id,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: event.resourceId,
+ input: event,
+ },
+ });
+
+ await queue.add(QueueName.WebhookQueue, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ name: QueueJobs.WebhookJob,
+ payload: {
+ projectId,
+ automationId: automation.id,
+ executionId,
+ payload: {
+ id: executionId,
+ timestamp: new Date(),
+ type: "project-notification",
+ apiVersion: "v1",
+ event,
+ },
+ },
+ });
+ }
+}
+
+async function dispatchAdminEmails({
+ projectId,
+ event,
+}: {
+ projectId: string;
+ event: ProjectNotificationEvent;
+}): Promise<void> {
+ if (
+ !env.EMAIL_FROM_ADDRESS ||
+ !env.SMTP_CONNECTION_URL ||
+ !env.NEXTAUTH_URL
+ ) {
+ logger.warn(
+ `dispatchProjectNotification: missing email env vars; skipping admin emails for ${event.eventType} in project ${projectId}`,
+ );
+ return;
+ }
+ const emailEnv: ProjectNotificationEmailEnv = {
+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
+ NEXTAUTH_URL: env.NEXTAUTH_URL,
+ CLOUD_CRM_EMAIL: env.CLOUD_CRM_EMAIL,
+ };
+
+ const receiverEmails = await getProjectAdminEmails(projectId);
+ if (receiverEmails.length === 0) {
+ logger.warn(
+ `dispatchProjectNotification: no project admins found for project ${projectId}; skipping admin emails for ${event.eventType}`,
+ );
+ return;
+ }
+
+ await sendEventAdminEmails({ event, receiverEmails, emailEnv });
+}
+
+/** sendEventAdminEmails renders and sends the event's email template to all recipients. */
+async function sendEventAdminEmails({
+ event,
+ receiverEmails,
+ emailEnv,
+}: {
+ event: ProjectNotificationEvent;
+ receiverEmails: string[];
+ emailEnv: ProjectNotificationEmailEnv;
+}): Promise<void> {
+ switch (event.eventType) {
+ case "blob-export-failed": {
+ await sendBlobStorageExportFailedEmail({
+ env: emailEnv,
+ projectName: event.projectName,
+ settingsUrl: `${emailEnv.NEXTAUTH_URL}/project/${event.projectId}/settings/integrations/blobstorage`,
+ receiverEmails,
+ disabled: event.disabled ?? false,
+ });
+ return;
+ }
+ case "evaluator-blocked": {
+ const resolutionUrl = `${emailEnv.NEXTAUTH_URL}${getEvaluatorBlockResolutionPath(
+ {
+ projectId: event.projectId,
+ blockReason: event.blockReason,
+ templateId: event.evalTemplateId,
+ },
+ )}`;
+ await Promise.allSettled(
+ receiverEmails.map((receiverEmail) =>
+ sendEvaluatorBlockedEmail({
+ env: emailEnv,
+ projectName: event.projectName,
+ evaluatorName: event.resourceName,
+ blockReason: event.blockReason,
+ blockMessage: event.message,
+ resolutionUrl,
+ receiverEmail,
+ }),
+ ),
+ );
+ return;
+ }
+ }
+}
diff --git a/packages/shared/src/server/notifications/index.ts b/packages/shared/src/server/notifications/index.ts
new file mode 100644
index 0000000000..c885938505
--- /dev/null
+++ b/packages/shared/src/server/notifications/index.ts
@@ -0,0 +1,3 @@
+export * from "./types";
+export * from "./buildProjectNotificationSlackMessage";
+export * from "./dispatchProjectNotification";
diff --git a/packages/shared/src/server/notifications/types.ts b/packages/shared/src/server/notifications/types.ts
new file mode 100644
index 0000000000..2710c38444
--- /dev/null
+++ b/packages/shared/src/server/notifications/types.ts
@@ -0,0 +1,81 @@
+import { EvaluatorBlockReason } from "@prisma/client";
+import { z } from "zod";
+
+import {
+ ProjectNotificationEventTypeSchema,
+ type ProjectNotificationEventType,
+} from "../../domain/automations";
+
+export {
+ ProjectNotificationEventTypeSchema,
+ type ProjectNotificationEventType,
+};
+
+/** ProjectNotificationSeveritySchema is the severity vocabulary of project notification events. */
+export const ProjectNotificationSeveritySchema = z.enum([
+ "ALERT",
+ "WARNING",
+ "INFO",
+]);
+export type ProjectNotificationSeverity = z.infer<
+ typeof ProjectNotificationSeveritySchema
+>;
+
+/** projectNotificationEventBaseSchema holds the fields shared by every project notification event. */
+const projectNotificationEventBaseSchema = z.object({
+ severity: ProjectNotificationSeveritySchema,
+ projectId: z.string(),
+ projectName: z.string(),
+ resourceId: z.string(),
+ resourceName: z.string(),
+ message: z.string(),
+ url: z.string().optional(),
+});
+
+/**
+ * ProjectNotificationEventSchema is the `event` body of the
+ * project-notification webhook envelope, discriminated on eventType. It is
+ * both the producer input and the outbound wire body. `blockReason` values are
+ * the Prisma EvaluatorBlockReason enum and are public API — additive changes
+ * are fine, renames are breaking.
+ */
+export const ProjectNotificationEventSchema = z.discriminatedUnion(
+ "eventType",
+ [
+ projectNotificationEventBaseSchema.extend({
+ eventType: z.literal(
+ ProjectNotificationEventTypeSchema.enum["blob-export-failed"],
+ ),
+ // true when the integration was auto-disabled after repeated failures
+ // (terminal event; selects the "disabled" email variant).
+ disabled: z.boolean().optional(),
+ }),
+ projectNotificationEventBaseSchema.extend({
+ eventType: z.literal(
+ ProjectNotificationEventTypeSchema.enum["evaluator-blocked"],
+ ),
+ blockReason: z.enum(EvaluatorBlockReason),
+ evalTemplateId: z.string().optional(),
+ }),
+ ],
+);
+export type ProjectNotificationEvent = z.infer<
+ typeof ProjectNotificationEventSchema
+>;
+
+/**
+ * ProjectNotificationWebhookQueueEventSchema is the `project-notification`
+ * variant of the webhook envelope: the queue payload equals the outbound HTTP
+ * body, mirroring monitor-alert. `id` is the executionId, `timestamp` is the
+ * dispatch time.
+ */
+export const ProjectNotificationWebhookQueueEventSchema = z.object({
+ id: z.string(),
+ timestamp: z.coerce.date(),
+ type: z.literal("project-notification"),
+ apiVersion: z.literal("v1"),
+ event: ProjectNotificationEventSchema,
+});
+export type ProjectNotificationWebhookQueueEvent = z.infer<
+ typeof ProjectNotificationWebhookQueueEventSchema
+>;
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index ea3cf2064e..917e869c2f 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -16,6 +16,7 @@ import {
type MonitorQueueEventInput,
MonitorWebhookQueueEventSchema,
} from "../features/monitors/scheduler/types";
+import { ProjectNotificationWebhookQueueEventSchema } from "./notifications/types";
export type { MonitorQueueEvent, MonitorQueueEventInput };
@@ -283,10 +284,11 @@ export const promptVersionWebhookEnvelopeSchema = z.object({
.optional(),
});
-/** WebhookOutboundEnvelopeSchema is the WebhookInput.payload contract: a discriminated union over `type`. The monitor-alert variant is the unified envelope (queue payload = HTTP outbound body); the prompt-version variant keeps its original dispatch-time wrap. */
+/** WebhookOutboundEnvelopeSchema is the WebhookInput.payload contract: a discriminated union over `type`. The monitor-alert and system variants are unified envelopes (queue payload = HTTP outbound body); the prompt-version variant keeps its original dispatch-time wrap. */
export const WebhookOutboundEnvelopeSchema = z.discriminatedUnion("type", [
promptVersionWebhookEnvelopeSchema,
MonitorWebhookQueueEventSchema,
+ ProjectNotificationWebhookQueueEventSchema,
]);
export const WebhookInputSchema = z.object({
diff --git a/packages/shared/src/server/services/blockEvaluatorConfigs.ts b/packages/shared/src/server/services/blockEvaluatorConfigs.ts
index 2383a3553c..6836dd152d 100644
--- a/packages/shared/src/server/services/blockEvaluatorConfigs.ts
+++ b/packages/shared/src/server/services/blockEvaluatorConfigs.ts
@@ -8,8 +8,7 @@ import {
import { invalidateProjectEvalConfigCaches } from "../evalJobConfigCache";
import { recordIncrement } from "../instrumentation";
import { logger } from "../logger";
-import { sendEvaluatorBlockedEmail } from "./email/evaluatorBlocked/sendEvaluatorBlockedEmail";
-import { getProjectAdminEmails } from "./getProjectAdminEmails";
+import { dispatchProjectNotification } from "../notifications/dispatchProjectNotification";
export const EvaluatorBlockSource = {
DEFAULT_EVAL_MODEL_DELETION: "default_eval_model_deletion",
@@ -201,32 +200,6 @@ export async function notifyBlockedEvaluatorConfigs({
const blockMessage = getEvaluatorBlockMetadata(blockReason).message;
- const emailEnv = {
- EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
- SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
- NEXTAUTH_URL: env.NEXTAUTH_URL,
- CLOUD_CRM_EMAIL: env.CLOUD_CRM_EMAIL,
- };
-
- if (
- !emailEnv.EMAIL_FROM_ADDRESS ||
- !emailEnv.SMTP_CONNECTION_URL ||
- !emailEnv.NEXTAUTH_URL
- ) {
- logger.warn(
- `[EVALUATOR BLOCK] Missing email env vars. Skipping notifications for project ${projectId}.`,
- );
- return;
- }
-
- const adminEmails = await getProjectAdminEmails(projectId);
- if (adminEmails.length === 0) {
- logger.warn(
- `[EVALUATOR BLOCK] No project admins found for project ${projectId}.`,
- );
- return;
- }
-
const project = await prisma.project.findUnique({
where: {
id: projectId,
@@ -266,25 +239,34 @@ export async function notifyBlockedEvaluatorConfigs({
return;
}
- const emailJobs = blockedConfigs.flatMap((config) =>
- adminEmails.map((receiverEmail) =>
- sendEvaluatorBlockedEmail({
- env: emailEnv,
- projectName: project.name,
- evaluatorName: config.evalTemplate?.name ?? config.scoreName,
+ // Route to configured notification channels and admin emails, one
+ // notification per blocked config. The `blockedAt: null` claim upstream
+ // already deduped, so no extra throttle is needed.
+ await Promise.allSettled(
+ blockedConfigs.map((config) => {
+ const evaluatorName = config.evalTemplate?.name ?? config.scoreName;
+ const resolutionPath = getEvaluatorBlockResolutionPath({
+ projectId,
blockReason,
- blockMessage,
- resolutionUrl: `${emailEnv.NEXTAUTH_URL}${getEvaluatorBlockResolutionPath(
- {
- projectId,
- blockReason,
- templateId: config.evalTemplate?.id,
- },
- )}`,
- receiverEmail,
- }),
- ),
+ templateId: config.evalTemplate?.id,
+ });
+ return dispatchProjectNotification({
+ projectId,
+ event: {
+ eventType: "evaluator-blocked",
+ severity: "ALERT",
+ projectId,
+ resourceId: config.id,
+ resourceName: evaluatorName,
+ message: blockMessage,
+ url: env.NEXTAUTH_URL
+ ? `${env.NEXTAUTH_URL}${resolutionPath}`
+ : undefined,
+ projectName: project.name,
+ blockReason,
+ evalTemplateId: config.evalTemplate?.id,
+ },
+ });
+ }),
);
-
- await Promise.allSettled(emailJobs);
}
diff --git a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts
new file mode 100644
index 0000000000..f6dd9e9df5
--- /dev/null
+++ b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from "vitest";
+
+import { buildColoredAttachmentSlackMessage } from "./buildColoredAttachmentSlackMessage";
+
+describe("buildColoredAttachmentSlackMessage", () => {
+ const base = {
+ color: "#dc3545",
+ title: "Something failed",
+ body: "A **thing** went wrong.",
+ timestamp: new Date("2026-07-08T00:00:00.000Z"),
+ url: "https://cloud.langfuse.com/x",
+ };
+
+ it("nests title, body and timestamp inside a single color-barred attachment", () => {
+ const message = buildColoredAttachmentSlackMessage(base);
+ expect(message.blocks).toEqual([]);
+ expect(message.attachments).toHaveLength(1);
+ const attachment = message.attachments![0];
+ expect(attachment.color).toBe("#dc3545");
+ expect(attachment.fallback).toBe("Something failed");
+ const serialized = JSON.stringify(attachment.blocks);
+ expect(serialized).toContain("Something failed");
+ expect(serialized).toContain(base.timestamp.toISOString());
+ });
+
+ it("renders the title as a link and adds a deep-link button when a url is set", () => {
+ const serialized = JSON.stringify(
+ buildColoredAttachmentSlackMessage(base).attachments![0].blocks,
+ );
+ expect(serialized).toContain(`<${base.url}|Something failed>`);
+ expect(serialized).toContain("View in Langfuse");
+ });
+
+ it("omits the link and button when no url is provided", () => {
+ const { url: _url, ...noUrl } = base;
+ const serialized = JSON.stringify(
+ buildColoredAttachmentSlackMessage(noUrl).attachments![0].blocks,
+ );
+ expect(serialized).not.toContain("View in Langfuse");
+ expect(serialized).toContain("*Something failed*");
+ });
+});
diff --git a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts
new file mode 100644
index 0000000000..6370b07f84
--- /dev/null
+++ b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts
@@ -0,0 +1,73 @@
+import { slackifyMarkdown } from "slackify-markdown";
+
+import { escapeSlackMrkdwn, type SlackMessage } from "./SlackService";
+
+/**
+ * buildColoredAttachmentSlackMessage renders a color-barred Slack Block Kit
+ * message (title, markdown body, timestamp, optional deep-link button). Shared
+ * layout for monitor alerts and project notifications so both look identical;
+ * callers own their severity→color mapping.
+ */
+export function buildColoredAttachmentSlackMessage(args: {
+ color: string;
+ title: string;
+ body: string;
+ timestamp: Date;
+ url?: string;
+ /** contextText is an optional extra context element rendered next to the timestamp. */
+ contextText?: string;
+}): SlackMessage {
+ const { color } = args;
+ const title = escapeSlackMrkdwn(args.title);
+ const titleText = args.url ? `*<${args.url}|${title}>*` : `*${title}*`;
+ const blocks: any[] = [
+ {
+ type: "section",
+ text: { type: "mrkdwn", text: titleText },
+ },
+ {
+ type: "section",
+ text: { type: "mrkdwn", text: slackifyMarkdown(args.body) },
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `⏱ ${args.timestamp.toISOString()}`,
+ },
+ ...(args.contextText
+ ? [
+ {
+ type: "mrkdwn",
+ text: escapeSlackMrkdwn(args.contextText),
+ },
+ ]
+ : []),
+ ],
+ },
+ ...(args.url
+ ? [
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View in Langfuse",
+ emoji: true,
+ },
+ url: args.url,
+ },
+ ],
+ },
+ ]
+ : []),
+ ];
+ // Color bar renders only on attachment-nested blocks; top-level text/blocks would duplicate above it.
+ return {
+ blocks: [],
+ attachments: [{ color, fallback: args.title, blocks }],
+ };
+}
diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.ts
index a3289ad658..57ab5b99cf 100644
--- a/web/src/__tests__/server/automations-trpc.servertest.ts
+++ b/web/src/__tests__/server/automations-trpc.servertest.ts
@@ -364,6 +364,201 @@ describe("automations trpc", () => {
expect(prompt.map((a) => a.name)).toEqual(["prompt-automation"]);
});
});
+
+ describe("project-notification eventSource", () => {
+ it("lists project-notification automations for any reader", async () => {
+ const { project, caller } = await prepare();
+
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "project-notification",
+ eventActions: ["blob-export-failed"],
+ 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",
+ apiVersion: { "project-notification": "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+ await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "notification-channel",
+ },
+ });
+
+ const response = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "project-notification",
+ });
+ expect(response.map((a) => a.name)).toEqual(["notification-channel"]);
+ });
+
+ it("excludes project-notification automations from the general list and count", async () => {
+ const { project, caller } = await prepare();
+
+ // A prompt automation (general UI) plus a project-notification channel.
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const sharedConfig = {
+ type: "WEBHOOK" as const,
+ url: "https://example.com/webhook",
+ apiVersion: { prompt: "v1" as const },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ };
+ for (const [eventSource, name, apiVersion] of [
+ ["prompt", "prompt-automation", { prompt: "v1" as const }],
+ [
+ "project-notification",
+ "notification-channel",
+ { "project-notification": "v1" as const },
+ ],
+ ] as const) {
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource,
+ eventActions:
+ eventSource === "prompt" ? ["created"] : ["blob-export-failed"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ type: "WEBHOOK",
+ config: { ...sharedConfig, apiVersion },
+ },
+ });
+ await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name,
+ },
+ });
+ }
+
+ // No eventSource → general list excludes project-notification.
+ const generalList = await caller.automations.getAutomations({
+ projectId: project.id,
+ });
+ expect(generalList.map((a) => a.name)).toEqual(["prompt-automation"]);
+
+ // Explicit eventSource still returns the channel.
+ const notificationList = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "project-notification",
+ });
+ expect(notificationList.map((a) => a.name)).toEqual([
+ "notification-channel",
+ ]);
+
+ // Header count excludes the project-notification channel.
+ const count = await caller.automations.count({
+ projectId: project.id,
+ });
+ expect(count).toBe(1);
+ });
+
+ it("toggles trigger eventActions via updateTriggerEventActions, only for project-notification sources", async () => {
+ const { project, caller } = await prepare();
+
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "project-notification",
+ eventActions: ["blob-export-failed", "evaluator-blocked"],
+ 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",
+ apiVersion: { "project-notification": "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "notification-channel",
+ },
+ });
+
+ await caller.automations.updateTriggerEventActions({
+ projectId: project.id,
+ automationId: automation.id,
+ eventActions: ["blob-export-failed"],
+ });
+
+ const updatedTrigger = await prisma.trigger.findUniqueOrThrow({
+ where: { id: trigger.id },
+ });
+ expect(updatedTrigger.eventActions).toEqual(["blob-export-failed"]);
+
+ // Prompt-source automations must be rejected.
+ const promptTrigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+ const promptAutomation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: promptTrigger.id,
+ actionId: action.id,
+ name: "prompt-automation",
+ },
+ });
+ await expect(
+ caller.automations.updateTriggerEventActions({
+ projectId: project.id,
+ automationId: promptAutomation.id,
+ eventActions: [],
+ }),
+ ).rejects.toThrow(
+ "This operation is only supported on project-notification automations.",
+ );
+ });
+ });
});
describe("automations.getAutomation", () => {
diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
index de291a6146..cd91f9fcb8 100644
--- a/web/src/features/automations/components/actions/WebhookActionHandler.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
@@ -81,7 +81,9 @@ export class WebhookActionHandler implements BaseActionHandler<WebhookActionForm
let apiVersion: z.infer<typeof AvailableWebhookApiSchema> =
eventSource === TriggerEventSource.Monitor
? { monitor: "v1" }
- : { prompt: "v1" };
+ : eventSource === TriggerEventSource.ProjectNotification
+ ? { "project-notification": "v1" }
+ : { prompt: "v1" };
if (
automation?.action?.type === "WEBHOOK" &&
automation?.action?.config &&
diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsx
index 4436461321..2cae740ca7 100644
--- a/web/src/features/automations/components/automationForm.tsx
+++ b/web/src/features/automations/components/automationForm.tsx
@@ -37,6 +37,7 @@ import {
ActionTypeSchema,
type FilterState,
type JobConfigState,
+ ProjectNotificationEventTypeSchema,
TriggerEventSource,
TriggerEventSourceSchema,
webhookActionFilterOptions,
@@ -72,6 +73,19 @@ const githubDispatchSchema = z.object({
/** promptEventActionDefaults is the default eventAction set for a fresh prompt-source automation. */
const promptEventActionDefaults: string[] = ["created", "updated", "deleted"];
+/** projectNotificationName derives the auto-generated channel name from the destination — the name field is hidden for this source. */
+const projectNotificationName = (data: FormValues): string => {
+ if (data.actionType === "SLACK") return `Slack #${data.slack.channelName}`;
+ if (data.actionType === "WEBHOOK") {
+ try {
+ return `Webhook ${new URL(data.webhook.url).hostname}`;
+ } catch {
+ return "Webhook";
+ }
+ }
+ return "Project notification";
+};
+
/** CreateAutomationPrefill pre-fills the create-automation form from a deep link. */
export type CreateAutomationPrefill = {
eventSource?: TriggerEventSource;
@@ -181,7 +195,9 @@ const formSchema = z
}),
])
.superRefine((data, ctx) => {
- // Prompt-source triggers require at least one event action; monitor-source triggers don't use this field.
+ // Prompt-source triggers require at least one event action; monitor and
+ // project-notification sources don't use this field (project-notification
+ // triggers are match-all).
if (
data.eventSource === TriggerEventSource.Prompt &&
data.eventAction.length === 0
@@ -352,6 +368,10 @@ interface AutomationFormProps {
isEditing?: boolean;
/** prefill is the pre-parsed deep-link payload (decoded by the caller). Ignored when automation is set. */
prefill?: CreateAutomationPrefill | null;
+ /** lockedEventSource fixes the trigger source and hides the source picker (e.g. the project-notifications settings section). */
+ lockedEventSource?: TriggerEventSource;
+ /** allowedActionTypes restricts the action-type picker; defaults to all registered action types. */
+ allowedActionTypes?: ActionTypes[];
}
export const AutomationForm = ({
@@ -361,6 +381,8 @@ export const AutomationForm = ({
automation,
isEditing = false,
prefill,
+ lockedEventSource,
+ allowedActionTypes,
}: AutomationFormProps) => {
const router = useRouter();
const hasAccess = useHasProjectAccess({
@@ -405,20 +427,32 @@ export const AutomationForm = ({
const resolvedEventSource: TriggerEventSource =
automation?.trigger.eventSource ??
+ lockedEventSource ??
parsedPrefill.eventSource ??
TriggerEventSource.Prompt;
const resolvedEventAction: string[] =
automation?.trigger.eventActions ??
- (resolvedEventSource === TriggerEventSource.Monitor
- ? []
- : promptEventActionDefaults);
+ (resolvedEventSource === TriggerEventSource.Prompt
+ ? promptEventActionDefaults
+ : resolvedEventSource === TriggerEventSource.ProjectNotification
+ ? // New channels start with every event enabled; the per-event
+ // toggles in the settings section manage them afterwards.
+ [...ProjectNotificationEventTypeSchema.options]
+ : []);
const resolvedFilter: FilterState =
automation?.trigger.filter ?? parsedPrefill.filter ?? [];
const baseValues = {
- name: isEditing && automation ? automation.name : "",
+ // Project-notification names are auto-generated at submit; seed a
+ // non-empty placeholder so the hidden field passes validation.
+ name:
+ isEditing && automation
+ ? automation.name
+ : resolvedEventSource === TriggerEventSource.ProjectNotification
+ ? "Project notification"
+ : "",
eventSource: resolvedEventSource,
eventAction: resolvedEventAction,
status: (isEditing && automation
@@ -507,12 +541,20 @@ export const AutomationForm = ({
const actionConfig = handler.buildActionConfig(data);
+ // Project-notification names are auto-generated from the destination (the
+ // name field is hidden for this source; regenerated on every save so the
+ // name follows destination edits).
+ const resolvedName =
+ data.eventSource === TriggerEventSource.ProjectNotification
+ ? projectNotificationName(data)
+ : data.name;
+
if (isEditing && automation) {
// Update existing automation
await updateAutomationMutation.mutateAsync({
projectId,
automationId: automation.id,
- name: data.name,
+ name: resolvedName,
eventSource: data.eventSource,
eventAction: data.eventAction,
filter: data.filter && data.filter.length > 0 ? data.filter : null,
@@ -523,7 +565,7 @@ export const AutomationForm = ({
showSuccessToast({
title: "Automation Updated",
- description: `Successfully updated automation "${data.name}".`,
+ description: `Successfully updated automation "${resolvedName}".`,
});
onSuccess?.(automation.id);
@@ -531,7 +573,7 @@ export const AutomationForm = ({
// Create new automation
const result = await createAutomationMutation.mutateAsync({
projectId,
- name: data.name,
+ name: resolvedName,
eventSource: data.eventSource,
eventAction: data.eventAction,
filter: data.filter && data.filter.length > 0 ? data.filter : null,
@@ -542,7 +584,7 @@ export const AutomationForm = ({
showSuccessToast({
title: "Automation Created",
- description: `Successfully created automation "${data.name}".`,
+ description: `Successfully created automation "${resolvedName}".`,
});
onSuccess?.(
@@ -604,6 +646,11 @@ export const AutomationForm = ({
/** watchedEventSource drives the conditional trigger UI (prompt → filter builder, monitor → tag picker). */
const watchedEventSource = form.watch("eventSource") as TriggerEventSource;
+ // Project-notification channels are deliberately minimal: match-all trigger
+ // (no trigger card), auto-generated name, no status toggle.
+ const isProjectNotification =
+ watchedEventSource === TriggerEventSource.ProjectNotification;
+
/** handleEventSourceChange resets eventAction + filter to defaults appropriate for the picked source. */
const handleEventSourceChange = (value: TriggerEventSource) => {
form.setValue("eventSource", value);
@@ -618,7 +665,7 @@ export const AutomationForm = ({
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 pb-6">
- {isEditing && (
+ {isEditing && !isProjectNotification && (
<div className="mb-6 flex items-center gap-4">
<div className="flex-1">
<FormField
@@ -663,29 +710,34 @@ export const AutomationForm = ({
</div>
)}
- <Card>
- <CardHeader>
- <CardTitle>Trigger</CardTitle>
- <CardDescription>
- Configure when this automation should run.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <EventSourceField
- control={form.control}
- onSourceChange={handleEventSourceChange}
- disabled={!hasAccess || !isEditing}
- />
- {watchedEventSource === TriggerEventSource.Monitor ? (
- <MonitorTriggerFields projectId={projectId} />
- ) : (
- <PromptTriggerFields
- control={form.control}
- disabled={!hasAccess || !isEditing}
- />
- )}
- </CardContent>
- </Card>
+ {/* Project-notification triggers are match-all, so there is nothing to configure. */}
+ {!isProjectNotification && (
+ <Card>
+ <CardHeader>
+ <CardTitle>Trigger</CardTitle>
+ <CardDescription>
+ Configure when this automation should run.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {!lockedEventSource && (
+ <EventSourceField
+ control={form.control}
+ onSourceChange={handleEventSourceChange}
+ disabled={!hasAccess || !isEditing}
+ />
+ )}
+ {watchedEventSource === TriggerEventSource.Monitor ? (
+ <MonitorTriggerFields projectId={projectId} />
+ ) : (
+ <PromptTriggerFields
+ control={form.control}
+ disabled={!hasAccess || !isEditing}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )}
<Card>
<CardHeader>
@@ -712,19 +764,20 @@ export const AutomationForm = ({
</SelectTrigger>
</FormControl>
<SelectContent>
- {ActionHandlerRegistry.getAllActionTypes().map(
- (actionType) => (
- <SelectItem key={actionType} value={actionType}>
- {actionType === "WEBHOOK"
- ? "Webhook"
- : actionType === "SLACK"
- ? "Slack"
- : actionType === "GITHUB_DISPATCH"
- ? "GitHub Dispatch"
- : "Annotation Queue"}
- </SelectItem>
- ),
- )}
+ {(
+ allowedActionTypes ??
+ ActionHandlerRegistry.getAllActionTypes()
+ ).map((actionType) => (
+ <SelectItem key={actionType} value={actionType}>
+ {actionType === "WEBHOOK"
+ ? "Webhook"
+ : actionType === "SLACK"
+ ? "Slack"
+ : actionType === "GITHUB_DISPATCH"
+ ? "GitHub Dispatch"
+ : "Annotation Queue"}
+ </SelectItem>
+ ))}
<SelectItem disabled={true} value="planned">
More coming soon...
</SelectItem>
@@ -752,19 +805,23 @@ export const AutomationForm = ({
{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>
- )}
+ {/* Project-notification channels are deleted from the channel list; the in-form delete redirects to the automations page. */}
+ {isEditing &&
+ !isProjectNotification &&
+ 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="grow"></div>
<div className="flex gap-3">
<Button type="button" variant="outline" onClick={handleCancel}>
diff --git a/web/src/features/automations/server/automationService.ts b/web/src/features/automations/server/automationService.ts
new file mode 100644
index 0000000000..63c6e98fac
--- /dev/null
+++ b/web/src/features/automations/server/automationService.ts
@@ -0,0 +1,72 @@
+import { TriggerEventSource, type TriggerDomain } from "@langfuse/shared";
+import { type PrismaClient, type Trigger } from "@langfuse/shared/src/db";
+import { getAutomationById } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+
+/** assertProjectNotificationAutomation loads an automation and guards it to the project-notification source. */
+async function assertProjectNotificationAutomation({
+ projectId,
+ automationId,
+}: {
+ projectId: string;
+ automationId: string;
+}) {
+ const existingAutomation = await getAutomationById({
+ projectId,
+ automationId,
+ });
+
+ if (!existingAutomation) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: `Automation with id ${automationId} not found.`,
+ });
+ }
+
+ if (
+ existingAutomation.trigger.eventSource !==
+ TriggerEventSource.ProjectNotification
+ ) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "This operation is only supported on project-notification automations.",
+ });
+ }
+
+ return existingAutomation;
+}
+
+/**
+ * updateTriggerEventActions toggles which event types a project-notification
+ * automation's trigger subscribes to. Restricted to the project-notification
+ * event source — other sources manage eventActions through the full automation
+ * update flow. Returns the previous trigger (for audit logging) and the
+ * updated row.
+ */
+export async function updateTriggerEventActions({
+ prisma,
+ projectId,
+ automationId,
+ eventActions,
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ automationId: string;
+ eventActions: string[];
+}): Promise<{ previousTrigger: TriggerDomain; trigger: Trigger }> {
+ const existingAutomation = await assertProjectNotificationAutomation({
+ projectId,
+ automationId,
+ });
+
+ const trigger = await prisma.trigger.update({
+ where: {
+ id: existingAutomation.trigger.id,
+ projectId,
+ },
+ data: { eventActions },
+ });
+
+ return { previousTrigger: existingAutomation.trigger, trigger };
+}
diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.ts
index af7cb2c045..afad70b5e9 100644
--- a/web/src/features/automations/server/router.ts
+++ b/web/src/features/automations/server/router.ts
@@ -11,7 +11,9 @@ import {
convertToSafeWebhookConfig,
isGitHubDispatchAction,
convertToSafeGitHubDispatchConfig,
+ TriggerEventSource,
TriggerEventSourceSchema,
+ ProjectNotificationEventTypeSchema,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { v4 } from "uuid";
@@ -25,6 +27,7 @@ import {
import { generateWebhookSecret, encrypt } from "@langfuse/shared/encryption";
import { processWebhookActionConfig } from "./webhookHelpers";
import { processGitHubDispatchActionConfig } from "./githubDispatchHelpers";
+import { updateTriggerEventActions } from "./automationService";
import { TRPCError } from "@trpc/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
@@ -154,10 +157,22 @@ export const automationsRouter = createTRPCRouter({
scope: "automations:read",
});
- return await getAutomations({
+ const automations = await getAutomations({
projectId: input.projectId,
eventSource: input.eventSource,
});
+
+ // Project-notification channels are managed from project settings, not
+ // the general Automations UI. When no eventSource is requested (the
+ // general list), exclude them so they don't leak into that view.
+ if (input.eventSource) {
+ return automations;
+ }
+ return automations.filter(
+ (automation) =>
+ automation.trigger.eventSource !==
+ TriggerEventSource.ProjectNotification,
+ );
}),
// Get a single automation by automation ID
@@ -497,6 +512,43 @@ export const automationsRouter = createTRPCRouter({
};
}),
+ // Toggle which project-notification events a channel receives. Narrow
+ // update on trigger.eventActions only, so the action config (and webhook
+ // secrets) is never round-tripped through the client.
+ updateTriggerEventActions: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ automationId: z.string(),
+ eventActions: z.array(ProjectNotificationEventTypeSchema),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "automations:CUD",
+ });
+
+ const { previousTrigger, trigger } = await updateTriggerEventActions({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ automationId: input.automationId,
+ eventActions: input.eventActions,
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "automation",
+ resourceId: trigger.id,
+ action: "update",
+ before: { trigger: previousTrigger },
+ after: { trigger },
+ });
+
+ return { trigger };
+ }),
+
// Delete an automation (both trigger and action)
deleteAutomation: protectedProjectProcedure
.input(
@@ -573,9 +625,18 @@ export const automationsRouter = createTRPCRouter({
scope: "automations:read",
});
+ // Exclude project-notification channels from the general Automations
+ // header count (they live in project settings, not this UI).
const count = await ctx.prisma.action.count({
where: {
projectId: input.projectId,
+ automations: {
+ none: {
+ trigger: {
+ eventSource: TriggerEventSource.ProjectNotification,
+ },
+ },
+ },
},
});
diff --git a/web/src/features/notifications/components/NotificationSettings.tsx b/web/src/features/notifications/components/PersonalNotificationSettings.tsx
similarity index 55%
rename from web/src/features/notifications/components/NotificationSettings.tsx
rename to web/src/features/notifications/components/PersonalNotificationSettings.tsx
index 545a24f142..c502431bbf 100644
--- a/web/src/features/notifications/components/NotificationSettings.tsx
+++ b/web/src/features/notifications/components/PersonalNotificationSettings.tsx
@@ -2,12 +2,11 @@ import { useState } from "react";
import { useRouter } from "next/router";
import { api } from "@/src/utils/api";
import Header from "@/src/components/layouts/header";
-import { Card, CardContent } from "@/src/components/ui/card";
import { Label } from "@/src/components/ui/label";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-export function NotificationSettings() {
+export function PersonalNotificationSettings() {
const router = useRouter();
const projectId = router.query.projectId as string;
const [isSaving, setIsSaving] = useState(false);
@@ -46,14 +45,10 @@ export function NotificationSettings() {
if (isLoading || !preferences) {
return (
<div>
- <Header title="Notification Settings" />
- <Card className="mt-4">
- <CardContent className="p-6">
- <p className="text-muted-foreground text-sm">
- Loading preferences...
- </p>
- </CardContent>
- </Card>
+ <Header title="Personal Notifications" />
+ <p className="text-muted-foreground mt-4 text-sm">
+ Loading preferences...
+ </p>
</div>
);
}
@@ -64,36 +59,33 @@ export function NotificationSettings() {
return (
<div>
- <Header title="Notification Settings" />
- <Card className="mt-4">
- <CardContent className="space-y-6 p-6">
- <div>
- <h3 className="text-lg font-medium">Email Notifications</h3>
+ <Header title="Personal Notifications" />
+ <div className="flex flex-col gap-4">
+ <div>
+ <h3 className="text-lg font-medium">Email Notifications</h3>
+ <p className="text-muted-foreground text-sm">
+ Manage your personal email notification preferences for this
+ project.
+ </p>
+ </div>
+
+ <div className="flex items-center justify-between rounded-lg border p-4">
+ <div className="flex flex-col gap-0.5">
+ <Label htmlFor="comment-mention" className="text-base">
+ Comment Mentions
+ </Label>
<p className="text-muted-foreground text-sm">
- Manage your email notification preferences for this project.
+ Receive an email when someone mentions you in a comment
</p>
</div>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between rounded-lg border p-4">
- <div className="space-y-0.5">
- <Label htmlFor="comment-mention" className="text-base">
- Comment Mentions
- </Label>
- <p className="text-muted-foreground text-sm">
- Receive an email when someone mentions you in a comment
- </p>
- </div>
- <Switch
- id="comment-mention"
- checked={emailCommentMention?.enabled ?? true}
- onCheckedChange={handleToggle}
- disabled={isSaving || !hasAccess}
- />
- </div>
- </div>
- </CardContent>
- </Card>
+ <Switch
+ id="comment-mention"
+ checked={emailCommentMention?.enabled ?? true}
+ onCheckedChange={handleToggle}
+ disabled={isSaving || !hasAccess}
+ />
+ </div>
+ </div>
{updatePreference.isError && (
<div className="border-destructive bg-destructive/10 mt-4 rounded-lg border p-4">
diff --git a/web/src/features/notifications/components/ProjectNotificationChannels.tsx b/web/src/features/notifications/components/ProjectNotificationChannels.tsx
new file mode 100644
index 0000000000..1e09058efb
--- /dev/null
+++ b/web/src/features/notifications/components/ProjectNotificationChannels.tsx
@@ -0,0 +1,171 @@
+import Header from "@/src/components/layouts/header";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { Switch } from "@/src/components/design-system/Switch/Switch";
+import { AutomationForm } from "@/src/features/automations/components/automationForm";
+import { WebhookSecretRender } from "@/src/features/automations/components/WebhookSecretRender";
+import { ProjectNotificationChannelsList } from "@/src/features/notifications/components/ProjectNotificationChannelsList";
+import { useProjectNotificationChannels } from "@/src/features/notifications/hooks/useProjectNotificationChannels";
+import { cn } from "@/src/utils/tailwind";
+import {
+ TriggerEventSource,
+ type ActionTypes,
+ type ProjectNotificationEventType,
+} from "@langfuse/shared";
+
+/** Project notifications route to webhooks or Slack; GitHub dispatch is not wired for this event source. */
+const PROJECT_NOTIFICATION_ACTION_TYPES: ActionTypes[] = ["WEBHOOK", "SLACK"];
+
+/** NOTIFIED_EVENTS lists the toggleable project-notification events, keyed by their eventType. */
+const NOTIFIED_EVENTS: {
+ value: ProjectNotificationEventType;
+ title: string;
+ description: string;
+}[] = [
+ {
+ value: "blob-export-failed",
+ title: "Blob storage export failed",
+ description: "Sent when a scheduled blob storage export fails.",
+ },
+ {
+ value: "evaluator-blocked",
+ title: "Evaluator deactivated",
+ description:
+ "Sent when an evaluator is deactivated due to an unrecoverable error, such as a deleted model or LLM connection.",
+ },
+];
+
+/**
+ * ProjectNotificationChannels is the admin-only "Project Notifications"
+ * settings section. It lists configured channels and delegates create/edit to
+ * the shared <AutomationForm> scoped to the project-notification event source.
+ */
+export function ProjectNotificationChannels({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const {
+ hasAccess,
+ channels,
+ isLoading,
+ mode,
+ editingChannel,
+ webhookSecret,
+ isDeleting,
+ isTogglingEvent,
+ isEventEnabled,
+ actions,
+ } = useProjectNotificationChannels(projectId);
+
+ const hasChannels = Boolean(channels?.length);
+
+ if (!hasAccess) return null;
+
+ return (
+ <div>
+ <Header title="Project Notifications" />
+ <p className="text-muted-foreground mb-4 text-sm">
+ Manage project notifications. Channel notifications are sent in addition
+ to the admin emails.
+ </p>
+
+ {mode === "list" ? (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-col gap-4">
+ <ProjectNotificationChannelsList
+ channels={channels}
+ isLoading={isLoading}
+ isDeleting={isDeleting}
+ onAdd={actions.openCreate}
+ onEdit={actions.openEdit}
+ onDelete={actions.deleteChannel}
+ />
+ </div>
+
+ <div className="flex flex-col gap-4">
+ <div>
+ <h3 className="text-lg font-medium">Events</h3>
+ <p className="text-muted-foreground text-sm">
+ {hasChannels
+ ? "Choose which events are delivered to your channels."
+ : "Configure a channel above to enable project notifications."}
+ </p>
+ </div>
+ {NOTIFIED_EVENTS.map((event) => (
+ <div
+ key={event.value}
+ className="flex items-center justify-between gap-4 rounded-lg border p-4"
+ >
+ <div
+ className={cn(
+ "flex flex-col gap-0.5",
+ !hasChannels && "opacity-50",
+ )}
+ >
+ <p className="text-base font-medium">{event.title}</p>
+ <p className="text-muted-foreground text-sm">
+ {event.description}
+ </p>
+ </div>
+ <Switch
+ checked={isEventEnabled(event.value)}
+ onCheckedChange={(checked) =>
+ actions.setEventEnabled(event.value, checked)
+ }
+ disabled={!hasChannels || isTogglingEvent}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <AutomationForm
+ key={editingChannel?.id ?? "create"}
+ projectId={projectId}
+ isEditing
+ lockedEventSource={TriggerEventSource.ProjectNotification}
+ allowedActionTypes={PROJECT_NOTIFICATION_ACTION_TYPES}
+ automation={editingChannel ?? undefined}
+ onSuccess={actions.onFormSuccess}
+ onCancel={actions.closeForm}
+ />
+ )}
+
+ {/* One-time webhook secret reveal after creating a webhook channel. */}
+ <Dialog
+ open={Boolean(webhookSecret)}
+ onOpenChange={(open) => {
+ if (!open) actions.dismissWebhookSecret();
+ }}
+ >
+ <DialogContent className="max-w-4xl">
+ <DialogHeader>
+ <DialogTitle>Webhook Secret Created</DialogTitle>
+ <DialogDescription>
+ Copy the webhook secret below — it will only be shown once.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ {webhookSecret && (
+ <WebhookSecretRender webhookSecret={webhookSecret} />
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button onClick={actions.dismissWebhookSecret}>
+ {"I've saved the secret"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx b/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx
new file mode 100644
index 0000000000..a277cc12ba
--- /dev/null
+++ b/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx
@@ -0,0 +1,100 @@
+import { SiSlack } from "react-icons/si";
+import { Webhook, Plus, Pencil, Trash2 } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { type AutomationDomain } from "@langfuse/shared";
+
+const destinationLabel = (automation: AutomationDomain): string => {
+ if (automation.action.type === "SLACK") {
+ const config = automation.action.config;
+ return config.type === "SLACK" ? `Slack #${config.channelName}` : "Slack";
+ }
+ if (automation.action.type === "WEBHOOK") {
+ const config = automation.action.config;
+ return config.type === "WEBHOOK" ? `Webhook ${config.url}` : "Webhook";
+ }
+ return automation.action.type;
+};
+
+export type ProjectNotificationChannelsListProps = {
+ channels: AutomationDomain[] | undefined;
+ isLoading: boolean;
+ isDeleting: boolean;
+ onAdd: () => void;
+ onEdit: (channel: AutomationDomain) => void;
+ onDelete: (automationId: string) => void;
+};
+
+/**
+ * ProjectNotificationChannelsList is the presentational list of configured
+ * channels: props in, callbacks out. The create/edit form is the reused
+ * <AutomationForm>, rendered by the container instead of this component.
+ */
+export function ProjectNotificationChannelsList({
+ channels,
+ isLoading,
+ isDeleting,
+ onAdd,
+ onEdit,
+ onDelete,
+}: ProjectNotificationChannelsListProps) {
+ return (
+ <div className="flex flex-col gap-4">
+ {isLoading ? (
+ <p className="text-muted-foreground text-sm">Loading channels...</p>
+ ) : !channels || channels.length === 0 ? null : (
+ <div className="flex flex-col gap-3">
+ {channels.map((channel) => (
+ <div
+ key={channel.id}
+ className="flex items-center justify-between gap-4 rounded-lg border p-4"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ {channel.action.type === "SLACK" ? (
+ <SiSlack className="h-4 w-4 shrink-0" />
+ ) : (
+ <Webhook className="h-4 w-4 shrink-0" />
+ )}
+ <span
+ className="truncate text-sm font-medium"
+ title={destinationLabel(channel)}
+ >
+ {destinationLabel(channel)}
+ </span>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => onEdit(channel)}
+ title="Edit channel"
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ disabled={isDeleting}
+ onClick={() => onDelete(channel.id)}
+ title="Delete channel"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* One channel per project: adding is only offered while none exists. */}
+ {!isLoading && !channels?.length && (
+ <div>
+ <Button variant="secondary" onClick={onAdd}>
+ <Plus className="mr-2 h-4 w-4" />
+ Add channel
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/notifications/hooks/useProjectNotificationChannels.ts b/web/src/features/notifications/hooks/useProjectNotificationChannels.ts
new file mode 100644
index 0000000000..42b9f3036e
--- /dev/null
+++ b/web/src/features/notifications/hooks/useProjectNotificationChannels.ts
@@ -0,0 +1,110 @@
+import { useState } from "react";
+
+import { api } from "@/src/utils/api";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ TriggerEventSource,
+ type AutomationDomain,
+ type ProjectNotificationEventType,
+} from "@langfuse/shared";
+
+/** ProjectNotificationChannelsMode is the section's view: the channel list or the create/edit form. */
+export type ProjectNotificationChannelsMode = "list" | "create" | "edit";
+
+/**
+ * useProjectNotificationChannels owns the data + navigation state for the
+ * project-notification channels settings section. The create/edit form itself
+ * is the reused <AutomationForm>, which owns its own mutations; this hook only
+ * lists channels, deletes them, and tracks which view is shown plus the
+ * one-time webhook secret reveal.
+ */
+export function useProjectNotificationChannels(projectId: string) {
+ const utils = api.useUtils();
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+
+ const { data: channels, isLoading } = api.automations.getAutomations.useQuery(
+ { projectId, eventSource: TriggerEventSource.ProjectNotification },
+ { enabled: Boolean(projectId) && hasAccess },
+ );
+
+ const [mode, setMode] = useState<ProjectNotificationChannelsMode>("list");
+ const [editingChannel, setEditingChannel] = useState<AutomationDomain | null>(
+ null,
+ );
+ const [webhookSecret, setWebhookSecret] = useState<string | null>(null);
+
+ const deleteChannel = api.automations.deleteAutomation.useMutation({
+ onSuccess: () => utils.automations.getAutomations.invalidate({ projectId }),
+ });
+
+ const updateEventActions =
+ api.automations.updateTriggerEventActions.useMutation({
+ onSuccess: () =>
+ utils.automations.getAutomations.invalidate({ projectId }),
+ });
+
+ /** isEventEnabled: an event is on when every channel has it enabled (toggles write to all channels, so states converge). */
+ const isEventEnabled = (eventType: ProjectNotificationEventType): boolean =>
+ Boolean(channels?.length) &&
+ (channels ?? []).every((channel) =>
+ (channel.trigger.eventActions as string[]).includes(eventType),
+ );
+
+ /** setEventEnabled applies the toggle to every channel's trigger.eventActions. */
+ const setEventEnabled = (
+ eventType: ProjectNotificationEventType,
+ enabled: boolean,
+ ) => {
+ for (const channel of channels ?? []) {
+ const current = channel.trigger
+ .eventActions as unknown as ProjectNotificationEventType[];
+ const next = enabled
+ ? Array.from(new Set([...current, eventType]))
+ : current.filter((event) => event !== eventType);
+ updateEventActions.mutate({
+ projectId,
+ automationId: channel.id,
+ eventActions: next,
+ });
+ }
+ };
+
+ return {
+ hasAccess,
+ channels,
+ isLoading,
+ mode,
+ editingChannel,
+ webhookSecret,
+ isDeleting: deleteChannel.isPending,
+ isTogglingEvent: updateEventActions.isPending,
+ isEventEnabled,
+ actions: {
+ setEventEnabled,
+ openCreate: () => {
+ setEditingChannel(null);
+ setMode("create");
+ },
+ openEdit: (channel: AutomationDomain) => {
+ setEditingChannel(channel);
+ setMode("edit");
+ },
+ closeForm: () => {
+ setEditingChannel(null);
+ setMode("list");
+ },
+ /** onFormSuccess returns to the list and, for a freshly created webhook, reveals the secret once. */
+ onFormSuccess: (_automationId?: string, secret?: string) => {
+ setEditingChannel(null);
+ setMode("list");
+ if (secret) setWebhookSecret(secret);
+ },
+ deleteChannel: (automationId: string) =>
+ deleteChannel.mutate({ projectId, automationId }),
+ dismissWebhookSecret: () => setWebhookSecret(null),
+ },
+ };
+}
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index 2adda6cd45..4ae89f5dd8 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -30,7 +30,8 @@ import ProtectedLabelsSettings from "@/src/features/prompts/components/Protected
import { SiSlack } from "react-icons/si";
import { ScoreConfigSettings } from "@/src/features/score-configs/components/ScoreConfigSettings";
import { env } from "@/src/env.mjs";
-import { NotificationSettings } from "@/src/features/notifications/components/NotificationSettings";
+import { PersonalNotificationSettings } from "@/src/features/notifications/components/PersonalNotificationSettings";
+import { ProjectNotificationChannels } from "@/src/features/notifications/components/ProjectNotificationChannels";
import { WebCalloutIntegrationCard } from "@/src/features/web-callouts/components/WebCalloutSettingsPage";
import { DeveloperToolsSettings } from "@/src/features/developer-tools/components/DeveloperToolsSettings";
@@ -240,8 +241,13 @@ export const getProjectSettingsPages = ({
{
title: "Notifications",
slug: "notifications",
- cmdKKeywords: ["inbox", "email", "mention", "alert"],
- content: <NotificationSettings />,
+ cmdKKeywords: ["inbox", "email", "mention", "alert", "slack", "webhook"],
+ content: (
+ <div className="flex flex-col gap-6">
+ <PersonalNotificationSettings />
+ <ProjectNotificationChannels projectId={project.id} />
+ </div>
+ ),
},
{
title: "Billing",
diff --git a/worker/src/__tests__/slack-processor.test.ts b/worker/src/__tests__/slack-processor.test.ts
index b6e8ee25e3..6c92aa8c5d 100644
--- a/worker/src/__tests__/slack-processor.test.ts
+++ b/worker/src/__tests__/slack-processor.test.ts
@@ -452,6 +452,66 @@ describe("Slack Processor", () => {
expect(trigger?.status).toBe(JobConfigState.INACTIVE);
});
+ it("project-notification Slack: records ERROR rows on failure but never disables the trigger", async () => {
+ mockSlackService.sendMessage.mockRejectedValue(
+ new Error("Slack API error"),
+ );
+
+ const buildInput = (): WebhookInput => {
+ const executionId = v4();
+ return {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ id: executionId,
+ timestamp: new Date(),
+ type: "project-notification",
+ apiVersion: "v1",
+ event: {
+ eventType: "blob-export-failed",
+ severity: "ALERT",
+ projectId,
+ projectName: "Test Project",
+ resourceId: projectId,
+ resourceName: "test-bucket",
+ message: "Blob storage export failed.",
+ },
+ },
+ };
+ };
+
+ // Fail many times over — well past any historical threshold.
+ for (let i = 0; i < 8; i++) {
+ const input = buildInput();
+ await prisma.automationExecution.create({
+ data: {
+ id: input.executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: projectId,
+ input: {},
+ },
+ });
+ await executeWebhook(input, { skipValidation: true });
+
+ // Each failure is recorded as an ERROR row for visibility.
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: input.executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ }
+
+ // Project-notification channels never auto-disable.
+ const trigger = await prisma.trigger.findUnique({
+ where: { id: triggerId },
+ });
+ expect(trigger?.status).toBe(JobConfigState.ACTIVE);
+ });
+
it("monitor-alert with a JSON-round-tripped (string) timestamp builds the full message, not the fallback", async () => {
// Reconfigure the action as a monitor-alert SLACK action.
await prisma.action.update({
diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.ts
index b0a80b186c..785ba64f30 100644
--- a/worker/src/__tests__/webhooks.test.ts
+++ b/worker/src/__tests__/webhooks.test.ts
@@ -707,6 +707,127 @@ describe("Webhook Integration Tests", () => {
expect(await redis!.get(failureKey)).toBeNull();
});
+ it("delivers a project notification envelope verbatim and completes the execution row", async () => {
+ const event = {
+ eventType: "blob-export-failed" as const,
+ severity: "ALERT" as const,
+ projectId,
+ projectName: "Test Project",
+ resourceId: projectId,
+ resourceName: "test-export-bucket",
+ message: "Blob storage export failed.",
+ url: `https://cloud.langfuse.com/project/${projectId}/settings`,
+ };
+ const executionId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ id: executionId,
+ timestamp: new Date(),
+ type: "project-notification",
+ apiVersion: "v1",
+ event,
+ },
+ };
+
+ // dispatchProjectNotification creates a PENDING row per enqueued job.
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ automationId,
+ triggerId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: event.resourceId,
+ input: event,
+ },
+ });
+
+ await executeWebhook(webhookInput, { skipValidation: true });
+
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1);
+ const body = JSON.parse(requests[0].body);
+ expect(body.type).toBe("project-notification");
+ expect(body.apiVersion).toBe("v1");
+ expect(body.id).toBe(executionId);
+ expect(body.event).toEqual(event);
+ // like the prompt-version path, the execution row is resolved to COMPLETED
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("project-notification webhook: records ERROR rows on failure but never disables the trigger", async () => {
+ // Point the webhook action at the always-500 endpoint.
+ 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: {
+ config: {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ url: "https://webhook-error.example.com/test",
+ },
+ },
+ });
+
+ // Fail more times than the (prompt/monitor) disable threshold of 5.
+ for (let i = 0; i < 6; i++) {
+ const executionId = v4();
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ automationId,
+ triggerId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: projectId,
+ input: {},
+ },
+ });
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ id: executionId,
+ timestamp: new Date(),
+ type: "project-notification",
+ apiVersion: "v1",
+ event: {
+ eventType: "blob-export-failed",
+ severity: "ALERT",
+ projectId,
+ projectName: "Test Project",
+ resourceId: projectId,
+ resourceName: "test-export-bucket",
+ message: "Blob storage export failed.",
+ },
+ },
+ };
+ await executeWebhook(webhookInput, { skipValidation: true });
+
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ }
+
+ // Project-notification channels never auto-disable.
+ const trigger = await prisma.trigger.findUnique({
+ where: { id: triggerId },
+ });
+ expect(trigger?.status).toBe(JobConfigState.ACTIVE);
+ });
+
it("auto-disables despite a redis.del failure on the failure-side reset", async () => {
const action = await prisma.action.findUnique({
where: { id: actionId },
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index f14b4456a8..b6461032ca 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -27,12 +27,11 @@ import {
BlobStorageIntegrationProcessingQueue,
queryClickhouse,
QueueJobs,
- sendBlobStorageExportFailedEmail,
- getProjectAdminEmails,
enrichObservationWithModelData,
createModelCache,
blobStorageEndpointConnectionValidationOptions,
validateBlobStorageEndpoint,
+ dispatchProjectNotification,
} from "@langfuse/shared/src/server";
import {
registerInFlightBlobExport,
@@ -1470,42 +1469,42 @@ function notifyBlobStorageExportFailedInBackground(
}
}
- const emailEnv = {
- EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,
- SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,
- NEXTAUTH_URL: env.NEXTAUTH_URL,
- CLOUD_CRM_EMAIL: env.CLOUD_CRM_EMAIL,
- };
-
- if (
- !emailEnv.EMAIL_FROM_ADDRESS ||
- !emailEnv.SMTP_CONNECTION_URL ||
- !emailEnv.NEXTAUTH_URL
- ) {
- return;
- }
-
- const [adminEmails, project] = await Promise.all([
- getProjectAdminEmails(projectId),
+ const [project, integration] = await Promise.all([
prisma.project.findUnique({
where: { id: projectId },
select: { name: true },
}),
+ prisma.blobStorageIntegration.findUnique({
+ where: { projectId },
+ select: { bucketName: true },
+ }),
]);
-
- if (adminEmails.length === 0) {
- return;
- }
-
const projectName = project?.name ?? projectId;
- const settingsUrl = `${emailEnv.NEXTAUTH_URL}/project/${projectId}/settings/integrations/blobstorage`;
-
- await sendBlobStorageExportFailedEmail({
- env: emailEnv,
- projectName,
- settingsUrl,
- receiverEmails: adminEmails,
- disabled,
+ const settingsPath = `/project/${projectId}/settings/integrations/blobstorage`;
+
+ // Route to configured notification channels and admin emails. The
+ // cooldown claim above already deduped, so no extra throttle is needed.
+ // `disabled` marks the terminal "export turned off" notification, which
+ // selects the disabled email/subject variant downstream.
+ await dispatchProjectNotification({
+ projectId,
+ event: {
+ eventType: "blob-export-failed",
+ severity: "ALERT",
+ projectId,
+ projectName,
+ // The integration is keyed by projectId (1:1); the bucket name is
+ // the most useful human label for the failing export destination.
+ resourceId: projectId,
+ resourceName: integration?.bucketName ?? "Blob storage integration",
+ message: disabled
+ ? `Blob storage export disabled for project "${projectName}" after repeated failures.`
+ : `Blob storage export failed for project "${projectName}".`,
+ url: env.NEXTAUTH_URL
+ ? `${env.NEXTAUTH_URL}${settingsPath}`
+ : undefined,
+ disabled,
+ },
});
} catch (error) {
logger.error(
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 7751ec1158..6132969c63 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -30,6 +30,8 @@ import {
SlackService,
logger,
redis,
+ ProjectNotificationWebhookQueueEventSchema,
+ buildProjectNotificationSlackMessage,
} from "@langfuse/shared/src/server";
import {
MonitorWebhookQueueEventSchema,
@@ -91,6 +93,17 @@ function buildWebhookOutboundPayload(input: WebhookInput) {
}
return parsed.data;
}
+ if (input.payload.type === "project-notification") {
+ const parsed = ProjectNotificationWebhookQueueEventSchema.safeParse(
+ input.payload,
+ );
+ if (!parsed.success) {
+ throw new InternalServerError(
+ `Invalid project notification payload: ${parsed.error.message}`,
+ );
+ }
+ return parsed.data;
+ }
const promptPayload = input.payload;
const parsed = PromptWebhookOutboundSchema.safeParse({
id: input.executionId,
@@ -382,6 +395,11 @@ async function executeHttpAction({
return { httpStatus: httpStatus || 0, responseBody: responseBody || "" };
}
+ // project-notification records the ERROR row for visibility but never
+ // auto-disables; prompt-version / github keep the consecutive-failure
+ // disable behavior below.
+ const disablesOnFailure = payloadType !== "project-notification";
+
// Update execution status and check if we should disable trigger
await prisma.$transaction(async (tx) => {
// Update execution status
@@ -406,6 +424,10 @@ async function executeHttpAction({
},
});
+ if (!disablesOnFailure) {
+ return;
+ }
+
// Check consecutive failures from execution history
const consecutiveFailures = await getConsecutiveAutomationFailures({
automationId: automation.id,
@@ -743,6 +765,49 @@ async function executeSlackAction({
return;
}
+ if (input.payload.type === "project-notification") {
+ // Project notifications resolve their AutomationExecution row (so the
+ // executions table stays accurate) but never auto-disable — a persistently
+ // failing channel keeps recording ERROR rows and stays ACTIVE.
+ try {
+ await sendSlackProjectNotification({
+ payload: input.payload,
+ projectId,
+ channelId: slackConfig.channelId,
+ });
+ 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(),
+ },
+ });
+ } catch (error) {
+ logger.error("Error executing Slack action", error);
+ await prisma.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",
+ },
+ });
+ }
+ return;
+ }
+
try {
// Build message blocks using predefined formats or custom template
let blocks: any[] = [];
@@ -892,6 +957,32 @@ async function sendSlackMonitorAlert({
await resetAutomationFailures({ projectId, automationId });
}
+/** sendSlackProjectNotification builds and posts a project notification to Slack. */
+async function sendSlackProjectNotification({
+ payload,
+ projectId,
+ channelId,
+}: {
+ payload: WebhookInput["payload"];
+ projectId: string;
+ channelId: string;
+}) {
+ const parsed = ProjectNotificationWebhookQueueEventSchema.safeParse(payload);
+ if (!parsed.success) {
+ throw new InternalServerError(
+ `Invalid project notification payload: ${parsed.error.message}`,
+ );
+ }
+ const message = buildProjectNotificationSlackMessage(parsed.data.event);
+ const client =
+ await SlackService.getInstance().getWebClientForProject(projectId);
+ await SlackService.getInstance().sendMessage({
+ client,
+ channelId,
+ ...message,
+ });
+}
+
/** slackMonitorAlertFailure tracks a failed monitor-alert delivery and auto-disables the trigger past the failure threshold. */
async function slackMonitorAlertFailure({
projectId,
@@ -909,7 +1000,10 @@ async function slackMonitorAlertFailure({
where: { id: automation.trigger.id, projectId },
data: { status: JobConfigState.INACTIVE },
});
- await resetAutomationFailures({ projectId, automationId: automation.id });
+ await resetAutomationFailures({
+ projectId,
+ automationId: automation.id,
+ });
logger.warn(
`Automation ${automation.trigger.id} disabled after ${count} consecutive failures in project ${projectId} (monitor-alert/slack)`,
);