Skip to content

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

fix(monitors): correct Slack alert formatting (#14132)

Mark Salpeter996e1112535c
diff --git a/packages/shared/package.json b/packages/shared/package.json
index b5c3bf8d96..85ccea6f4e 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -138,6 +138,7 @@
"oci-common": "^2.125.0",
"oci-objectstorage": "^2.125.0",
"safe-regex2": "^5.0.0",
+ "slackify-markdown": "^5.0.0",
"undici": "^7.24.6",
"uuid": "^14.0.0",
"winston": "^3.15.0",
diff --git a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts
new file mode 100644
index 0000000000..55abac5e5b
--- /dev/null
+++ b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect } from "vitest";
+
+import { type MonitorAlert } from "../types";
+import { buildMonitorAlertSlackMessage } from "./buildMonitorAlertSlackMessage";
+
+/** mockMonitorAlert is the ALERT each case overrides. */
+const mockMonitorAlert: MonitorAlert = {
+ monitorId: "mon_01",
+ projectId: "proj_01",
+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",
+ message: {
+ title: "High error rate",
+ body: "**count(observations.value)** is **above** `100`",
+ },
+ severity: "ALERT",
+ timestamp: new Date("2026-05-18T12:01:00.000Z"),
+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),
+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),
+ view: "observations",
+ filters: [],
+ window: "5m",
+};
+
+describe("buildMonitorAlertSlackMessage", () => {
+ it("ALERT: red attachment; linked title; body mrkdwn; timestamp; neutral view button", () => {
+ const { blocks, attachments } =
+ buildMonitorAlertSlackMessage(mockMonitorAlert);
+ expect(blocks).toEqual([]);
+ expect(attachments).toHaveLength(1);
+ expect(attachments![0].color).toBe("#dc3545");
+ expect(attachments![0].fallback).toBe("High error rate");
+ const inner = attachments![0].blocks!;
+ expect(inner[0]).toMatchObject({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*<https://cloud.langfuse.com/project/proj_01/monitors/mon_01|High error rate>*",
+ },
+ });
+ expect(inner[1]).toMatchObject({
+ type: "section",
+ text: { type: "mrkdwn" },
+ });
+ expect(inner[1].text.text).toContain("*count(observations.value)*");
+ expect(inner[2]).toMatchObject({ type: "context" });
+ expect(inner[2].elements[0].text).toContain("2026-05-18T12:01:00.000Z");
+ expect(inner[3]).toMatchObject({ type: "actions" });
+ expect(inner[3].elements[0]).toMatchObject({
+ type: "button",
+ url: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",
+ });
+ expect(inner[3].elements[0].style).toBeUndefined();
+ });
+
+ it.each([
+ ["WARNING", "#ffc107"],
+ ["OK", "#28a745"],
+ ["NO_DATA", "#6c757d"],
+ ["UNKNOWN", "#6c757d"],
+ ["PAUSED", "#6c757d"],
+ ] as const)("%s: linked title, attachment color %s", (severity, color) => {
+ const { attachments } = buildMonitorAlertSlackMessage({
+ ...mockMonitorAlert,
+ severity,
+ });
+ expect(attachments![0].color).toBe(color);
+ expect(attachments![0].blocks![0].text.text).toContain("High error rate");
+ });
+
+ it("title links to the permalink", () => {
+ const { attachments } = buildMonitorAlertSlackMessage(mockMonitorAlert);
+ expect(attachments![0].blocks![0].text.text).toBe(
+ "*<https://cloud.langfuse.com/project/proj_01/monitors/mon_01|High error rate>*",
+ );
+ });
+
+ it("renders a plain bold title and omits the button when permalink is absent", () => {
+ const { attachments } = buildMonitorAlertSlackMessage({
+ ...mockMonitorAlert,
+ permalink: undefined,
+ });
+ const inner = attachments![0].blocks!;
+ expect(inner[0].text.text).toBe("*High error rate*");
+ expect(inner.some((b: any) => b.type === "actions")).toBe(false);
+ expect(inner.some((b: any) => b.type === "context")).toBe(true);
+ });
+});
diff --git a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts
new file mode 100644
index 0000000000..5e1f8c9565
--- /dev/null
+++ b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts
@@ -0,0 +1,70 @@
+import { slackifyMarkdown } from "slackify-markdown";
+
+import {
+ escapeSlackMrkdwn,
+ type SlackMessage,
+} from "../../../server/services/SlackService";
+import { type MonitorAlert, type MonitorSeverity } from "../types";
+
+/** severityVisual maps MonitorSeverity to its Slack attachment color. */
+const severityVisual: Record<MonitorSeverity, { color: string }> = {
+ ALERT: { color: "#dc3545" },
+ WARNING: { color: "#ffc107" },
+ OK: { color: "#28a745" },
+ NO_DATA: { color: "#6c757d" },
+ UNKNOWN: { color: "#6c757d" },
+ PAUSED: { color: "#6c757d" },
+};
+
+/** buildMonitorAlertSlackMessage renders a MonitorAlert into a Slack Block Kit SlackMessage. */
+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 }],
+ };
+}
diff --git a/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts b/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts
index e4c4c4d86b..a6a41d35dc 100644
--- a/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts
+++ b/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts
@@ -94,7 +94,7 @@ const cases: Case[] = [
next: "ALERT",
expected: {
title: "[ALERT] Latency monitor",
- body: `${metricRef} is **above** \`100\``,
+ body: `${metricRef} is **above** \`100\` over the last **5m**`,
},
},
{
@@ -103,7 +103,7 @@ const cases: Case[] = [
next: "WARNING",
expected: {
title: "[WARNING] Latency monitor",
- body: `${metricRef} is **above** \`50\``,
+ body: `${metricRef} is **above** \`50\` over the last **5m**`,
},
},
{
@@ -112,7 +112,7 @@ const cases: Case[] = [
next: "WARNING",
expected: {
title: "[WARNING] Latency monitor",
- body: `${metricRef} is **above** \`100\``,
+ body: `${metricRef} is **above** \`100\` over the last **5m**`,
},
},
];
@@ -150,7 +150,9 @@ describe("renderAlertMessage", () => {
},
completion: completion("ALERT"),
});
- expect(result.body).toBe(`${metricRef} is **${word}** \`100\``);
+ expect(result.body).toBe(
+ `${metricRef} is **${word}** \`100\` over the last **5m**`,
+ );
},
);
});
diff --git a/packages/shared/src/features/monitors/processor/renderAlertMessage.ts b/packages/shared/src/features/monitors/processor/renderAlertMessage.ts
index adcfd7bdf6..c088f935f6 100644
--- a/packages/shared/src/features/monitors/processor/renderAlertMessage.ts
+++ b/packages/shared/src/features/monitors/processor/renderAlertMessage.ts
@@ -29,7 +29,7 @@ export function renderAlertMessage(args: {
monitor.alertThreshold,
monitor.warningThreshold ?? null,
);
- body = `${metricRef} is **${operatorWord(monitor.thresholdOperator)}** \`${threshold}\``;
+ body = `${metricRef} is **${operatorWord(monitor.thresholdOperator)}** \`${threshold}\` over the last **${monitor.window}**`;
}
return { title, body };
}
diff --git a/packages/shared/src/features/monitors/server.ts b/packages/shared/src/features/monitors/server.ts
index c8ee1b7ff4..0027328e71 100644
--- a/packages/shared/src/features/monitors/server.ts
+++ b/packages/shared/src/features/monitors/server.ts
@@ -6,3 +6,4 @@ export * from "./service";
export * from "./scheduler/types";
export * from "./scheduler/scheduler";
export * from "./processor/processor";
+export * from "./processor/buildMonitorAlertSlackMessage";
diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.ts
index 361dd4499f..0ff0af8534 100644
--- a/packages/shared/src/server/services/SlackService.ts
+++ b/packages/shared/src/server/services/SlackService.ts
@@ -49,12 +49,24 @@ export interface GetChannelsResult {
hasPrivateChannelAccess: boolean;
}
-export interface SlackMessageParams {
- client: WebClient;
- channelId: string;
+/** SlackMessage is the Block Kit payload sent to Slack. */
+export interface SlackMessage {
blocks: any[];
text?: string;
- attachments?: unknown[];
+ attachments?: { color: string; fallback?: string; blocks?: any[] }[];
+}
+
+export interface SlackMessageParams extends SlackMessage {
+ client: WebClient;
+ channelId: string;
+}
+
+/** escapeSlackMrkdwn escapes Slack mrkdwn special characters to prevent injection. */
+export function escapeSlackMrkdwn(text: string): string {
+ return text
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
}
export interface SlackMessageResponse {
@@ -465,7 +477,11 @@ export class SlackService {
channel: params.channelId,
blocks: params.blocks,
attachments: params.attachments as any,
- text: params.text || "Langfuse Notification",
+ text:
+ params.text ||
+ (params.blocks?.length || params.attachments?.length
+ ? undefined
+ : "Langfuse Notification"),
unfurl_links: false,
unfurl_media: false,
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e191454f85..fa8bf44956 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -301,6 +301,9 @@ importers:
safe-regex2:
specifier: ^5.0.0
version: 5.0.0
+ slackify-markdown:
+ specifier: ^5.0.0
+ version: 5.0.0
undici:
specifier: ^7.24.6
version: 7.25.0
diff --git a/worker/src/__tests__/monitorProcessor.test.ts b/worker/src/__tests__/monitorProcessor.test.ts
index 0dda5d7899..778eaa1bfa 100644
--- a/worker/src/__tests__/monitorProcessor.test.ts
+++ b/worker/src/__tests__/monitorProcessor.test.ts
@@ -399,7 +399,7 @@ const cases: ProcessCase[] = [
severity: "ALERT",
message: {
title: `[ALERT] Test ${monitorAId}`,
- body: "`count(observations.count)` is **above** `100`",
+ body: "`count(observations.count)` is **above** `100` over the last **5m**",
},
view: "observations",
window: "5m",
diff --git a/worker/src/__tests__/slack-message-builder.test.ts b/worker/src/__tests__/slack-message-builder.test.ts
index 7e07649b80..c6daf7315a 100644
--- a/worker/src/__tests__/slack-message-builder.test.ts
+++ b/worker/src/__tests__/slack-message-builder.test.ts
@@ -305,106 +305,4 @@ describe("SlackMessageBuilder", () => {
expect(blocks[0].text.text).toContain("Langfuse Notification");
});
});
-
- describe("buildMonitorMessage", () => {
- const mockMonitorEnvelope = {
- id: "exe_01",
- timestamp: new Date("2026-05-18T12:01:00.000Z"),
- type: "monitor-alert" as const,
- apiVersion: "v1" as const,
- payload: {
- monitorId: "mon_01",
- projectId: "proj_01",
- permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",
- message: {
- title: "High error rate",
- body: "**count(observations.value)** is **above** `100`",
- },
- severity: "ALERT" as const,
- timestamp: new Date("2026-05-18T12:01:00.000Z"),
- fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),
- toTimestamp: new Date("2026-05-18T12:00:30.000Z"),
- view: "observations" as const,
- filters: [],
- window: "5m" as const,
- },
- };
-
- it("ALERT: header is title only (no severity emoji); body converted to Slack mrkdwn; red attachment", () => {
- const { blocks, attachments } =
- SlackMessageBuilder.buildMonitorMessage(mockMonitorEnvelope);
- expect(blocks[0]).toMatchObject({
- type: "header",
- text: { type: "plain_text", text: "High error rate" },
- });
- // slackify-markdown converts **bold** → *bold* (Slack mrkdwn)
- expect(blocks[1]).toMatchObject({
- type: "section",
- text: { type: "mrkdwn" },
- });
- expect(blocks[1].text.text).toContain("*count(observations.value)*");
- expect(blocks[2]).toMatchObject({ type: "actions" });
- expect(blocks[2].elements[0]).toMatchObject({
- type: "button",
- url: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",
- });
- expect(blocks[3]).toMatchObject({ type: "context" });
- expect(attachments).toEqual([{ color: "#dc3545" }]);
- });
-
- it.each([
- ["WARNING", "#ffc107"],
- ["OK", "#28a745"],
- ["NO_DATA", "#6c757d"],
- ["UNKNOWN", "#6c757d"],
- ["PAUSED", "#6c757d"],
- ] as const)(
- "%s: header is title only, attachment color %s",
- (severity, color) => {
- const { blocks, attachments } = SlackMessageBuilder.buildMonitorMessage(
- {
- ...mockMonitorEnvelope,
- payload: { ...mockMonitorEnvelope.payload, severity },
- },
- );
- expect(blocks[0].text.text).toBe("High error rate");
- expect(attachments).toEqual([{ color }]);
- },
- );
-
- it("header has no severity emoji prefix", () => {
- const { blocks } =
- SlackMessageBuilder.buildMonitorMessage(mockMonitorEnvelope);
- expect(blocks[0].text.text).toBe("High error rate");
- });
-
- it("truncates a header longer than 150 chars to 150 with an ellipsis", () => {
- const longTitle = "[ALERT] " + "x".repeat(160);
- const { blocks } = SlackMessageBuilder.buildMonitorMessage({
- ...mockMonitorEnvelope,
- payload: {
- ...mockMonitorEnvelope.payload,
- message: { ...mockMonitorEnvelope.payload.message, title: longTitle },
- },
- });
- const headerText = blocks[0].text.text as string;
- expect(headerText.length).toBeLessThanOrEqual(150);
- expect(headerText.endsWith("…")).toBe(true);
- });
-
- it("omits the actions block when permalink is absent", () => {
- const { blocks } = SlackMessageBuilder.buildMonitorMessage({
- ...mockMonitorEnvelope,
- payload: { ...mockMonitorEnvelope.payload, permalink: undefined },
- });
- expect(blocks.every((b) => b.type !== "actions")).toBe(true);
- expect(blocks.some((b) => b.type === "context")).toBe(true);
- });
-
- it("buildMessage routes monitor-alert envelopes", () => {
- const result = SlackMessageBuilder.buildMessage(mockMonitorEnvelope);
- expect(result.attachments).toEqual([{ color: "#dc3545" }]);
- expect(result.blocks[0].text.text).toBe("High error rate");
- });
- });
});
diff --git a/worker/src/__tests__/slack-processor.test.ts b/worker/src/__tests__/slack-processor.test.ts
index 047574afa4..b6e8ee25e3 100644
--- a/worker/src/__tests__/slack-processor.test.ts
+++ b/worker/src/__tests__/slack-processor.test.ts
@@ -498,21 +498,23 @@ describe("Slack Processor", () => {
expect(mockSlackService.sendMessage).toHaveBeenCalledTimes(1);
const sent = mockSlackService.sendMessage.mock.calls[0][0];
- const blocks = sent.blocks;
- // Full monitor message: header block carries the alert title.
- expect(blocks[0].type).toBe("header");
- expect(blocks[0].text.text).toBe("High error rate");
+ // Full monitor message: content nests in the colored attachment; the
+ // linked title section carries the alert title.
+ expect(sent.blocks).toEqual([]);
+ const inner = sent.attachments![0].blocks!;
+ expect(inner[0].type).toBe("section");
+ expect(inner[0].text.text).toContain("High error rate");
- // Not the fallback: a single section block starting "*Langfuse Notification*".
+ // Not the fallback: fallback emits a single top-level section and no attachment.
const isFallback =
- blocks.length === 1 &&
- blocks[0].type === "section" &&
- blocks[0].text?.text?.startsWith("*Langfuse Notification*");
+ sent.attachments === undefined &&
+ sent.blocks.length === 1 &&
+ sent.blocks[0].text?.text?.startsWith("*Langfuse Notification*");
expect(isFallback).toBe(false);
});
- it("monitor-alert: text fallback is the alert title, not the generic notification", async () => {
+ it("monitor-alert: attachment fallback is the alert title; no generic notification text", async () => {
await prisma.action.update({
where: { id: actionId },
data: {
@@ -554,12 +556,16 @@ describe("Slack Processor", () => {
await executeWebhook(wireInput, { skipValidation: true });
- expect(mockSlackService.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ text: "[ALERT] High error rate" }),
+ const sent = mockSlackService.sendMessage.mock.calls[0][0];
+ expect(sent.text).toBeUndefined();
+ expect(sent.attachments).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ fallback: "[ALERT] High error rate" }),
+ ]),
);
});
- it("monitor-alert: text fallback escapes Slack mention tokens in the monitor name", async () => {
+ it("monitor-alert: title escapes Slack mention tokens in the monitor name", async () => {
await prisma.action.update({
where: { id: actionId },
data: {
@@ -604,11 +610,10 @@ describe("Slack Processor", () => {
await executeWebhook(wireInput, { skipValidation: true });
- expect(mockSlackService.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- text: "[ALERT] &lt;!channel&gt; investigate",
- }),
- );
+ const sent = mockSlackService.sendMessage.mock.calls[0][0];
+ const titleBlock = sent.attachments![0].blocks![0];
+ expect(titleBlock.text.text).toContain("&lt;!channel&gt;");
+ expect(titleBlock.text.text).not.toContain("<!channel>");
});
it("should handle SlackService errors gracefully", async () => {
diff --git a/worker/src/features/slack/slackMessageBuilder.ts b/worker/src/features/slack/slackMessageBuilder.ts
index f6ad53af96..b964a17db7 100644
--- a/worker/src/features/slack/slackMessageBuilder.ts
+++ b/worker/src/features/slack/slackMessageBuilder.ts
@@ -1,44 +1,17 @@
-import { logger } from "@langfuse/shared/src/server";
-import type { WebhookInput } from "@langfuse/shared/src/server";
-import type { MonitorSeverity } from "@langfuse/shared";
-import type { MonitorWebhookQueueEvent } from "@langfuse/shared/monitors/server";
-import { slackifyMarkdown } from "slackify-markdown";
+import {
+ logger,
+ escapeSlackMrkdwn,
+ type WebhookInput,
+ type SlackMessage,
+} from "@langfuse/shared/src/server";
import { env } from "../../env";
-/** severityVisual maps MonitorSeverity to its Slack emoji + attachment color per RFC §895-900. */
-const severityVisual: Record<
- MonitorSeverity,
- { emoji: string; color: string }
-> = {
- ALERT: { emoji: "🚨", color: "#dc3545" },
- WARNING: { emoji: "⚠️", color: "#ffc107" },
- OK: { emoji: "✅", color: "#28a745" },
- NO_DATA: { emoji: "❓", color: "#6c757d" },
- UNKNOWN: { emoji: "❓", color: "#6c757d" },
- PAUSED: { emoji: "⏸️", color: "#6c757d" },
-};
-
-/** Escape Slack mrkdwn special characters to prevent injection (e.g. <!channel>)
- * @see https://docs.slack.dev/messaging/formatting-message-text/#escaping */
-export function escapeSlackMrkdwn(text: string): string {
- return text
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;");
-}
-
type WebhookInputPayload = WebhookInput["payload"];
type PromptVersionPayload = Extract<
WebhookInputPayload,
{ type: "prompt-version" }
>;
-/** SlackMessage is the shape returned by buildMessage: blocks for Block Kit, optional attachments for the legacy color bar (used by monitor-alert). */
-export interface SlackMessage {
- blocks: any[];
- attachments?: { color: string }[];
-}
-
/**
* Builds Slack Block Kit messages for different Langfuse event types
*/
@@ -153,60 +126,6 @@ export class SlackMessageBuilder {
];
}
- /** buildMonitorMessage renders a MonitorWebhookQueueEvent into Slack Block Kit per RFC §855-902. The processor emits standard markdown; we convert the body to Slack mrkdwn via slackify-markdown. */
- static buildMonitorMessage(envelope: MonitorWebhookQueueEvent): SlackMessage {
- const alert = envelope.payload;
- const { color } = severityVisual[alert.severity];
- // Slack hard-limits header plain_text to 150 chars and rejects longer
- // values with invalid_blocks; the [SEVERITY] prefix already conveys
- // severity, so the header carries the title alone (no severity emoji).
- const title = alert.message.title;
- const headerText = title.length > 150 ? `${title.slice(0, 149)}…` : title;
- const blocks: any[] = [
- {
- type: "header",
- text: {
- type: "plain_text",
- text: headerText,
- emoji: true,
- },
- },
- {
- type: "section",
- text: { type: "mrkdwn", text: slackifyMarkdown(alert.message.body) },
- },
- ...(alert.permalink
- ? [
- {
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View in Langfuse",
- emoji: true,
- },
- url: alert.permalink,
- style: "primary",
- },
- ],
- },
- ]
- : []),
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: `⏱ ${alert.timestamp.toISOString()}`,
- },
- ],
- },
- ];
- return { blocks, attachments: [{ color }] };
- }
-
/**
* Get action-specific configuration (emoji, color, etc.)
*/
@@ -234,8 +153,6 @@ export class SlackMessageBuilder {
switch (payload.type) {
case "prompt-version":
return { blocks: this.buildPromptVersionMessage(payload) };
- case "monitor-alert":
- return this.buildMonitorMessage(payload);
default: {
const unknownType = (payload as { type: string }).type;
logger.warn(`Unsupported Slack message type: ${unknownType}`);
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 14db950e27..7751ec1158 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -31,14 +31,14 @@ import {
logger,
redis,
} from "@langfuse/shared/src/server";
-import { MonitorWebhookQueueEventSchema } from "@langfuse/shared/monitors/server";
+import {
+ MonitorWebhookQueueEventSchema,
+ buildMonitorAlertSlackMessage,
+} from "@langfuse/shared/monitors/server";
import { Processor, Job } from "bullmq";
import { backOff } from "exponential-backoff";
import { env } from "../env";
-import {
- SlackMessageBuilder,
- escapeSlackMrkdwn,
-} from "../features/slack/slackMessageBuilder";
+import { SlackMessageBuilder } from "../features/slack/slackMessageBuilder";
// GitHub repository_dispatch client_payload: max 10 top-level properties and <64KB.
// https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event
@@ -726,24 +726,29 @@ async function executeSlackAction({
const slackConfig = actionConfig.config;
- try {
- // monitor-alert envelopes survive a BullMQ JSON round-trip as plain strings;
- // parse to recover the Dates buildMonitorMessage formats, matching the
- // webhook/github dispatchers' buildWebhookOutboundPayload discipline.
- let payload = input.payload;
- if (payload.type === "monitor-alert") {
- const parsed = MonitorWebhookQueueEventSchema.safeParse(payload);
- if (!parsed.success) {
- throw new InternalServerError(
- `Invalid monitor-alert payload: ${parsed.error.message}`,
- );
- }
- payload = parsed.data;
+ // TODO: unify automation execution log and failure handling across all message types (not scalable yet)
+ // TODO: implement a strategy/policy + registry pattern for different webhook providers.
+ if (input.payload.type === "monitor-alert") {
+ try {
+ await sendSlackMonitorAlert({
+ payload: input.payload,
+ projectId,
+ channelId: slackConfig.channelId,
+ automationId: automation.id,
+ });
+ } catch (error) {
+ logger.error("Error executing Slack action", error);
+ await slackMonitorAlertFailure({ projectId, automation });
}
+ return;
+ }
+ try {
// Build message blocks using predefined formats or custom template
let blocks: any[] = [];
- let attachments: { color: string }[] | undefined;
+ let attachments:
+ | { color: string; fallback?: string; blocks?: any[] }[]
+ | undefined;
// TODO: Custom templates not supported via the UI yet
if (slackConfig.messageTemplate) {
@@ -762,7 +767,7 @@ async function executeSlackAction({
// Use predefined message format if no custom template or template failed
if (blocks.length === 0) {
- const message = SlackMessageBuilder.buildMessage(payload);
+ const message = SlackMessageBuilder.buildMessage(input.payload);
blocks = message.blocks;
attachments = message.attachments;
logger.debug(
@@ -780,75 +785,30 @@ async function executeSlackAction({
channelId: slackConfig.channelId,
blocks,
attachments,
- text:
- payload.type === "monitor-alert"
- ? escapeSlackMrkdwn(payload.payload.message.title)
- : "Langfuse Notification",
+ text: "Langfuse Notification",
});
// Update execution status to completed
- if (input.payload.type === "monitor-alert") {
- try {
- await resetAutomationFailures({
- projectId,
- automationId: automation.id,
- });
- } catch (resetError) {
- logger.warn(
- `Failed to reset automation failure counter after successful delivery for automation ${automation.id} in project ${projectId}`,
- resetError,
- );
- }
- } else {
- 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: {
- channel: sendResult.channel,
- messageTs: sendResult.messageTs,
- },
+ 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: {
+ channel: sendResult.channel,
+ messageTs: sendResult.messageTs,
},
- });
- }
+ },
+ });
} catch (error) {
logger.error("Error executing Slack action", error);
- if (input.payload.type === "monitor-alert") {
- const count = await incrementAutomationFailure({
- projectId,
- automationId: automation.id,
- });
- if (count >= automationFailureThreshold) {
- await prisma.trigger.update({
- where: { id: automation.trigger.id, projectId },
- data: { status: JobConfigState.INACTIVE },
- });
- try {
- await resetAutomationFailures({
- projectId,
- automationId: automation.id,
- });
- } catch (resetError) {
- logger.warn(
- `Failed to reset automation failure counter after auto-disable for automation ${automation.id} in project ${projectId}`,
- resetError,
- );
- }
- logger.warn(
- `Automation ${automation.trigger.id} disabled after ${count} consecutive failures in project ${projectId} (monitor-alert/slack)`,
- );
- }
- return;
- }
-
// Get action config for updating in case of failure
const failureActionConfig = await getActionByIdWithSecrets({
projectId,
@@ -903,6 +863,59 @@ async function executeSlackAction({
}
}
+/** sendSlackMonitorAlert builds and posts a monitor-alert to Slack, then clears the failure streak. */
+async function sendSlackMonitorAlert({
+ payload,
+ projectId,
+ channelId,
+ automationId,
+}: {
+ payload: WebhookInput["payload"];
+ projectId: string;
+ channelId: string;
+ automationId: string;
+}) {
+ const parsed = MonitorWebhookQueueEventSchema.safeParse(payload);
+ if (!parsed.success) {
+ throw new InternalServerError(
+ `Invalid monitor-alert payload: ${parsed.error.message}`,
+ );
+ }
+ const message = buildMonitorAlertSlackMessage(parsed.data.payload);
+ const client =
+ await SlackService.getInstance().getWebClientForProject(projectId);
+ await SlackService.getInstance().sendMessage({
+ client,
+ channelId,
+ ...message,
+ });
+ await resetAutomationFailures({ projectId, automationId });
+}
+
+/** slackMonitorAlertFailure tracks a failed monitor-alert delivery and auto-disables the trigger past the failure threshold. */
+async function slackMonitorAlertFailure({
+ projectId,
+ automation,
+}: {
+ projectId: string;
+ automation: NonNullable<Awaited<ReturnType<typeof getAutomationById>>>;
+}) {
+ const count = await incrementAutomationFailure({
+ projectId,
+ automationId: automation.id,
+ });
+ if (count >= automationFailureThreshold) {
+ await prisma.trigger.update({
+ where: { id: automation.trigger.id, projectId },
+ data: { status: JobConfigState.INACTIVE },
+ });
+ await resetAutomationFailures({ projectId, automationId: automation.id });
+ logger.warn(
+ `Automation ${automation.trigger.id} disabled after ${count} consecutive failures in project ${projectId} (monitor-alert/slack)`,
+ );
+ }
+}
+
const setActionLastFailingExecutionId = async ({
tx,
actionId,