Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: add slack integration (#8073)

Thorsten Spieker3a46283bf23b
diff --git a/.env.dev.example b/.env.dev.example
index 6e49338674..2b3a7388bc 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -83,3 +83,8 @@ NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
# For SDK integration tests to pass, decrease the ingestion queue delay by uncommenting the env vars:
# LANGFUSE_INGESTION_QUEUE_DELAY_MS=10
# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=10
+
+# Slack credentials for development
+SLACK_CLIENT_ID=your_slack_client_id
+SLACK_CLIENT_SECRET=your_slack_client_secret
+SLACK_STATE_SECRET=your_slack_state_secret
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 59e839ae22..94b4a5b14d 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -73,6 +73,8 @@
"@prisma/client": "^6.10.1",
"@react-email/components": "^0.1.0",
"@react-email/render": "^1.1.2",
+ "@slack/oauth": "^2.6.0",
+ "@slack/web-api": "^7.0.0",
"@types/bcryptjs": "^2.4.6",
"axios": "^1.8.2",
"bcryptjs": "^2.4.3",
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index fd48388390..03393de55a 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -139,6 +139,7 @@ export type DashboardWidgetChartType =
(typeof DashboardWidgetChartType)[keyof typeof DashboardWidgetChartType];
export const ActionType = {
WEBHOOK: "WEBHOOK",
+ SLACK: "SLACK",
} as const;
export type ActionType = (typeof ActionType)[keyof typeof ActionType];
export const ActionExecutionStatus = {
@@ -714,6 +715,16 @@ export type Session = {
user_id: string;
expires: Timestamp;
};
+export type SlackIntegration = {
+ id: string;
+ project_id: string;
+ team_id: string;
+ team_name: string;
+ bot_token: string;
+ bot_user_id: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Timestamp;
+};
export type SsoConfig = {
domain: string;
created_at: Generated<Timestamp>;
@@ -826,6 +837,7 @@ export type DB = {
score_configs: ScoreConfig;
scores: LegacyPrismaScore;
Session: Session;
+ slack_integrations: SlackIntegration;
sso_configs: SsoConfig;
table_view_presets: TableViewPreset;
trace_media: TraceMedia;
diff --git a/packages/shared/prisma/migrations/20250717150100_add_slack_integration/migration.sql b/packages/shared/prisma/migrations/20250717150100_add_slack_integration/migration.sql
new file mode 100644
index 0000000000..8d3b731c44
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250717150100_add_slack_integration/migration.sql
@@ -0,0 +1,30 @@
+-- Migration: Add Slack Integration Support
+-- This migration adds support for Slack automation actions by:
+-- 1. Adding SLACK to the ActionType enum
+-- 2. Creating slack_integrations table for centralized token storage
+
+-- AlterEnum
+ALTER TYPE "ActionType" ADD VALUE 'SLACK';
+
+-- CreateTable
+CREATE TABLE "slack_integrations" (
+ "id" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+ "team_id" TEXT NOT NULL,
+ "team_name" TEXT NOT NULL,
+ "bot_token" TEXT NOT NULL,
+ "bot_user_id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "slack_integrations_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "slack_integrations_project_id_key" ON "slack_integrations"("project_id");
+
+-- CreateIndex
+CREATE INDEX "slack_integrations_team_id_idx" ON "slack_integrations"("team_id");
+
+-- AddForeignKey
+ALTER TABLE "slack_integrations" ADD CONSTRAINT "slack_integrations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 2ec7962dc8..e01d07bb8a 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -163,6 +163,7 @@ model Project {
Automation Automation[]
DefaultLlmModel DefaultLlmModel[]
Price Price[]
+ SlackIntegration SlackIntegration?
@@index([orgId])
@@map("projects")
@@ -1298,6 +1299,7 @@ model Automation {
enum ActionType {
WEBHOOK
+ SLACK
// More action types can be added as needed
}
@@ -1338,3 +1340,23 @@ model AutomationExecution {
@@index([projectId])
@@map("automation_executions")
}
+
+// Slack Integration: Stores centralized Slack workspace connection for each project
+// One project can connect to one Slack workspace, supporting multiple channel automations
+model SlackIntegration {
+ id String @id @default(cuid())
+ projectId String @unique @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ // Installation details (encrypted using shared encryption utilities)
+ teamId String @map("team_id") // Slack workspace ID
+ teamName String @map("team_name") // Human-readable workspace name
+ botToken String @map("bot_token") // Encrypted bot token for API calls
+ botUserId String @map("bot_user_id") // Bot user ID for workspace
+
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ @@index([teamId])
+ @@map("slack_integrations")
+}
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index 548cb48e45..9414c19e81 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -30,14 +30,14 @@ export type AutomationDomain = {
};
export type ActionDomain = Omit<Action, "config"> & {
- config: SafeWebhookActionConfig;
+ config: SafeActionConfig;
};
export type ActionDomainWithSecrets = Omit<Action, "config"> & {
- config: WebhookActionConfigWithSecrets;
+ config: ActionConfigWithSecrets;
};
-export const ActionTypeSchema = z.enum(["WEBHOOK"]);
+export const ActionTypeSchema = z.enum(["WEBHOOK", "SLACK"]);
export const AvailableWebhookApiSchema = z.record(
z.enum(["prompt"]),
@@ -52,9 +52,9 @@ export const RequestHeaderSchema = z.object({
export const WebhookActionConfigSchema = z.object({
type: z.literal("WEBHOOK"),
url: z.url(),
- headers: z.record(z.string(), z.string()),
- requestHeaders: z.record(z.string(), RequestHeaderSchema),
- displayHeaders: z.record(z.string(), RequestHeaderSchema),
+ headers: z.record(z.string(), z.string()).optional(), // deprecated field, use requestHeaders instead
+ requestHeaders: z.record(z.string(), RequestHeaderSchema).optional(), // might not exist on legacy webhooks
+ displayHeaders: z.record(z.string(), RequestHeaderSchema).optional(), // might not exist on legacy webhooks
apiVersion: AvailableWebhookApiSchema,
secretKey: z.string(),
displaySecretKey: z.string(),
@@ -78,18 +78,94 @@ export const WebhookActionCreateSchema = WebhookActionConfigSchema.omit({
displayHeaders: true,
});
+export const SlackActionConfigSchema = z.object({
+ type: z.literal("SLACK"),
+ channelId: z.string(),
+ channelName: z.string(),
+ messageTemplate: z.string().optional(),
+});
+
+export type SlackActionConfig = z.infer<typeof SlackActionConfigSchema>;
+
export const ActionConfigSchema = z.discriminatedUnion("type", [
WebhookActionConfigSchema,
+ SlackActionConfigSchema,
]);
export const ActionCreateSchema = z.discriminatedUnion("type", [
WebhookActionCreateSchema,
+ SlackActionConfigSchema,
+]);
+
+export const SafeActionConfigSchema = z.discriminatedUnion("type", [
+ SafeWebhookActionConfigSchema,
+ SlackActionConfigSchema,
]);
export type ActionTypes = z.infer<typeof ActionTypeSchema>;
export type ActionConfig = z.infer<typeof ActionConfigSchema>;
export type ActionCreate = z.infer<typeof ActionCreateSchema>;
+export type SafeActionConfig = z.infer<typeof SafeActionConfigSchema>;
+export type WebhookActionCreate = z.infer<typeof WebhookActionCreateSchema>;
export type WebhookActionConfigWithSecrets = z.infer<
typeof WebhookActionConfigSchema
>;
+
+export type ActionConfigWithSecrets = z.infer<typeof ActionConfigSchema>;
+
+// Type Guards for Runtime Validation
+// Using existing Zod schemas to provide both compile-time and runtime type safety
+
+/**
+ * Type guard to check if a config is a valid webhook configuration with secrets
+ */
+export function isWebhookActionConfig(
+ config: unknown,
+): config is WebhookActionConfigWithSecrets {
+ return WebhookActionConfigSchema.safeParse(config).success;
+}
+
+/**
+ * Type guard to check if a config is a valid Slack configuration
+ */
+export function isSlackActionConfig(
+ config: unknown,
+): config is SlackActionConfig {
+ return SlackActionConfigSchema.safeParse(config).success;
+}
+
+/**
+ * Type guard to check if an entire action has valid webhook configuration
+ */
+export function isWebhookAction(action: {
+ type: string;
+ config: unknown;
+}): action is { type: "WEBHOOK"; config: WebhookActionConfigWithSecrets } {
+ return action.type === "WEBHOOK" && isWebhookActionConfig(action.config);
+}
+
+/**
+ * Type guard for safe webhook config (without secrets)
+ */
+export function isSafeWebhookActionConfig(
+ config: unknown,
+): config is SafeWebhookActionConfig {
+ return SafeWebhookActionConfigSchema.safeParse(config).success;
+}
+
+/**
+ * Converts webhook config with secrets to safe config by only including allowed fields
+ */
+export function convertToSafeWebhookConfig(
+ webhookConfig: WebhookActionConfigWithSecrets,
+): SafeWebhookActionConfig {
+ return {
+ type: webhookConfig.type,
+ url: webhookConfig.url,
+ displayHeaders: webhookConfig.displayHeaders,
+ apiVersion: webhookConfig.apiVersion,
+ displaySecretKey: webhookConfig.displaySecretKey,
+ lastFailingExecutionId: webhookConfig.lastFailingExecutionId,
+ };
+}
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index b9fc789761..8bc9bab8b5 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -172,6 +172,10 @@ const EnvSchema = z.object({
return new Map<string, number>();
}
}),
+
+ SLACK_CLIENT_ID: z.string().optional(),
+ SLACK_CLIENT_SECRET: z.string().optional(),
+ SLACK_STATE_SECRET: z.string().optional(),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 18abbd2f98..467f2ddf8f 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -64,6 +64,8 @@ export * from "./services/DashboardService";
export * from "./services/TableViewService";
export * from "./services/DefaultEvaluationModelService";
export * from "./clickhouse/measureAndReturn";
+export * from "./services/SlackService";
+
export * from "./data-deletion/ingestionFileDeletion";
export * from "./s3";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index c63d184360..b35621efb7 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -168,6 +168,7 @@ export const WebhookInputSchema = z.object({
payload: WebhookOutboundEnvelopeSchema,
});
+export type WebhookInput = z.infer<typeof WebhookInputSchema>;
export const EntityChangeEventSchema = z.discriminatedUnion("entityType", [
z.object({
entityType: z.literal("prompt-version"),
@@ -178,8 +179,6 @@ export const EntityChangeEventSchema = z.discriminatedUnion("entityType", [
}),
// Add other entity types here in the future
]);
-
-export type WebhookInput = z.infer<typeof WebhookInputSchema>;
export type EntityChangeEventType = z.infer<typeof EntityChangeEventSchema>;
export type CreateEvalQueueEventType = z.infer<
diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.ts
index 9b237f2b3e..8271859b7e 100644
--- a/packages/shared/src/server/repositories/automation-repository.ts
+++ b/packages/shared/src/server/repositories/automation-repository.ts
@@ -8,12 +8,16 @@ import {
} from "../../db";
import {
TriggerEventSource,
- WebhookActionConfigWithSecrets,
TriggerDomain,
TriggerEventAction,
ActionDomain,
AutomationDomain,
- SafeWebhookActionConfig,
+ ActionDomainWithSecrets,
+ SafeActionConfig,
+ isWebhookActionConfig,
+ WebhookActionConfigWithSecrets,
+ isSafeWebhookActionConfig,
+ convertToSafeWebhookConfig,
} from "../../domain/automations";
import { FilterState } from "../../types";
import { decryptSecretHeaders, mergeHeaders } from "../utils/headerUtils";
@@ -24,7 +28,7 @@ export const getActionByIdWithSecrets = async ({
}: {
projectId: string;
actionId: string;
-}) => {
+}): Promise<ActionDomainWithSecrets | null> => {
const actionConfig = await prisma.action.findFirst({
where: {
id: actionId,
@@ -36,34 +40,41 @@ export const getActionByIdWithSecrets = async ({
return null;
}
- const config = actionConfig.config as WebhookActionConfigWithSecrets;
-
- // Decrypt secret headers for webhook execution using new structure
- const decryptedHeaders = config.requestHeaders
- ? decryptSecretHeaders(mergeHeaders(config.headers, config.requestHeaders))
- : config.headers
- ? Object.entries(config.headers).reduce(
- (acc, [key, value]) => {
- acc[key] = { secret: false, value };
- return acc;
- },
- {} as Record<string, { secret: boolean; value: string }>,
+ if (isWebhookActionConfig(actionConfig.config)) {
+ const config = actionConfig.config; // Type guard ensures this is WebhookActionConfigWithSecrets
+
+ // Decrypt secret headers for webhook execution using new structure
+ const decryptedHeaders = config.requestHeaders
+ ? decryptSecretHeaders(
+ mergeHeaders(config.headers, config.requestHeaders),
)
- : {};
+ : config.headers
+ ? Object.entries(config.headers).reduce(
+ (acc, [key, value]) => {
+ acc[key] = { secret: false, value };
+ return acc;
+ },
+ {} as Record<string, { secret: boolean; value: string }>,
+ )
+ : {};
- return {
- ...actionConfig,
- config: {
- type: config.type,
- url: config.url,
- requestHeaders: decryptedHeaders,
- displayHeaders: getDisplayHeaders(config),
- apiVersion: config.apiVersion,
- displaySecretKey: config.displaySecretKey,
- secretKey: config.secretKey,
- lastFailingExecutionId: config.lastFailingExecutionId,
- },
- };
+ return {
+ ...actionConfig,
+ config: {
+ type: config.type,
+ url: config.url,
+ requestHeaders: decryptedHeaders,
+ displayHeaders: getDisplayHeaders(config),
+ apiVersion: config.apiVersion,
+ displaySecretKey: config.displaySecretKey,
+ secretKey: config.secretKey,
+ lastFailingExecutionId: config.lastFailingExecutionId,
+ },
+ };
+ }
+
+ // For SLACK and others, return as stored (already safe)
+ return actionConfig as ActionDomainWithSecrets;
};
export const getActionById = async ({
@@ -148,19 +159,21 @@ const getDisplayHeaders = (config: WebhookActionConfigWithSecrets) => {
};
const convertActionToDomain = (action: Action): ActionDomain => {
- const config = action.config as WebhookActionConfigWithSecrets;
+ if (isWebhookActionConfig(action.config)) {
+ const config = action.config;
+ config.displayHeaders = getDisplayHeaders(config);
+ return {
+ ...action,
+ config: convertToSafeWebhookConfig(config),
+ };
+ }
+
+ // For SLACK (or future types) return config as-is
return {
...action,
- config: {
- type: config.type,
- url: config.url,
- displayHeaders: getDisplayHeaders(config),
- apiVersion: config.apiVersion,
- displaySecretKey: config.displaySecretKey,
- lastFailingExecutionId: config.lastFailingExecutionId,
- } as SafeWebhookActionConfig,
- };
+ config: action.config as SafeActionConfig,
+ } as ActionDomain;
};
export const getAutomationById = async ({
@@ -252,7 +265,10 @@ export const getConsecutiveAutomationFailures = async ({
};
// If there's a lastFailingExecutionId, we need to get executions that are newer than that execution
- if (automation.action.config.lastFailingExecutionId) {
+ if (
+ isSafeWebhookActionConfig(automation.action.config) &&
+ automation.action.config.lastFailingExecutionId
+ ) {
// First get the timestamp of the last failing execution
const lastFailingExecution = await prisma.automationExecution.findUnique({
where: {
diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.ts
new file mode 100644
index 0000000000..a45f1f125a
--- /dev/null
+++ b/packages/shared/src/server/services/SlackService.ts
@@ -0,0 +1,386 @@
+/**
+ * Slack Integration Service
+ *
+ * Simplified service that properly uses the official Slack SDK libraries:
+ * - @slack/oauth InstallProvider for OAuth flow management
+ * - @slack/web-api WebClient for Slack API operations
+ * - Metadata-based project-to-team mapping
+ */
+
+import { WebClient } from "@slack/web-api";
+import { InstallProvider } from "@slack/oauth";
+import { logger } from "../logger";
+import { env } from "../../env";
+import { prisma } from "../../db";
+import { encrypt, decrypt } from "../../encryption";
+
+// Types for Slack integration
+export interface SlackChannel {
+ id: string;
+ name: string;
+ isPrivate: boolean;
+ isMember: boolean;
+}
+
+export interface SlackMessageParams {
+ client: WebClient;
+ channelId: string;
+ blocks: any[];
+ text?: string;
+}
+
+export interface SlackMessageResponse {
+ messageTs: string;
+ channel: string;
+}
+
+// Interface for Slack installation metadata
+export interface SlackInstallationMetadata {
+ projectId: string;
+}
+
+/**
+ * Type guard to validate Slack installation metadata
+ */
+function isSlackInstallationMetadata(
+ metadata: unknown,
+): metadata is SlackInstallationMetadata {
+ return (
+ typeof metadata === "object" &&
+ metadata !== null &&
+ "projectId" in metadata &&
+ typeof metadata.projectId === "string" &&
+ metadata.projectId.length > 0
+ );
+}
+
+/**
+ * Helper function to safely parse and validate Slack installation metadata
+ */
+export function parseSlackInstallationMetadata(
+ metadata: unknown,
+): SlackInstallationMetadata {
+ if (typeof metadata !== "string") {
+ throw new Error("Installation metadata must be a string");
+ }
+
+ let parsedMetadata: unknown;
+ try {
+ parsedMetadata = JSON.parse(metadata);
+ } catch {
+ throw new Error("Failed to parse installation metadata as JSON");
+ }
+
+ if (!isSlackInstallationMetadata(parsedMetadata)) {
+ throw new Error(
+ "Invalid installation metadata: missing or invalid projectId",
+ );
+ }
+
+ return parsedMetadata;
+}
+
+/**
+ * Slack Service Class
+ *
+ * Uses InstallProvider for OAuth flow and metadata-based project mapping.
+ * Much simpler than the previous implementation while maintaining all functionality.
+ */
+export class SlackService {
+ private static instance: SlackService | null = null;
+ private installer: InstallProvider;
+
+ private constructor() {
+ this.installer = new InstallProvider({
+ clientId: env.SLACK_CLIENT_ID!,
+ clientSecret: env.SLACK_CLIENT_SECRET!,
+ stateSecret: env.SLACK_STATE_SECRET!,
+ installUrlOptions: {
+ scopes: ["channels:read", "chat:write", "chat:write.public"],
+ },
+ installationStore: {
+ storeInstallation: async (installation) => {
+ try {
+ const metadata = parseSlackInstallationMetadata(
+ installation.metadata,
+ );
+ const projectId = metadata.projectId;
+
+ logger.info("Storing Slack installation for project", {
+ projectId,
+ teamId: installation.team?.id,
+ teamName: installation.team?.name,
+ });
+
+ // Store by projectId (one integration per project)
+ await prisma.slackIntegration.upsert({
+ where: { projectId },
+ create: {
+ projectId,
+ teamId: installation.team?.id!,
+ teamName: installation.team?.name!,
+ botToken: encrypt(installation.bot?.token!),
+ botUserId: installation.bot?.userId!,
+ },
+ update: {
+ teamId: installation.team?.id!,
+ teamName: installation.team?.name!,
+ botToken: encrypt(installation.bot?.token!),
+ botUserId: installation.bot?.userId!,
+ },
+ });
+
+ logger.info("Slack installation stored successfully", {
+ projectId,
+ teamId: installation.team?.id,
+ });
+ } catch (error) {
+ logger.error("Failed to store Slack installation", { error });
+ throw error;
+ }
+ },
+
+ fetchInstallation: async (installQuery) => {
+ try {
+ // Handle both teamId and projectId lookups
+ // When SDK calls with teamId, we treat it as projectId
+ const lookupId = installQuery.teamId;
+
+ if (!lookupId) {
+ throw new Error("No lookup ID provided");
+ }
+
+ const integration = await prisma.slackIntegration.findFirst({
+ where: {
+ OR: [
+ { teamId: lookupId }, // Actual team ID lookup
+ { projectId: lookupId }, // Project ID lookup (our custom usage)
+ ],
+ },
+ });
+
+ if (!integration) {
+ throw new Error("Slack integration not found");
+ }
+
+ // Return full Installation interface as expected by SDK
+ return {
+ team: {
+ id: integration.teamId,
+ name: integration.teamName,
+ },
+ bot: {
+ id: integration.botUserId,
+ token: decrypt(integration.botToken),
+ userId: integration.botUserId,
+ scopes: [],
+ },
+ enterprise: undefined,
+ user: {
+ token: undefined,
+ refreshToken: undefined,
+ expiresAt: undefined,
+ scopes: undefined,
+ id: integration.botUserId,
+ },
+ };
+ } catch (error) {
+ logger.error("Failed to fetch Slack installation", { error });
+ throw error;
+ }
+ },
+
+ deleteInstallation: async (installQuery) => {
+ try {
+ const lookupId = installQuery.teamId;
+
+ if (!lookupId) {
+ throw new Error("No lookup ID provided for deletion");
+ }
+
+ await prisma.slackIntegration.deleteMany({
+ where: {
+ OR: [{ teamId: lookupId }, { projectId: lookupId }],
+ },
+ });
+
+ logger.info("Slack installation deleted successfully", {
+ lookupId,
+ });
+ } catch (error) {
+ logger.error("Failed to delete Slack installation", { error });
+ throw error;
+ }
+ },
+ },
+ });
+ }
+
+ /**
+ * Get singleton instance of SlackService
+ */
+ static getInstance(): SlackService {
+ if (!SlackService.instance) {
+ SlackService.instance = new SlackService();
+ }
+ return SlackService.instance;
+ }
+
+ /**
+ * Get the configured InstallProvider instance for OAuth handling
+ */
+ getInstaller(): InstallProvider {
+ return this.installer;
+ }
+
+ /**
+ * Reset the singleton instance (useful for testing)
+ */
+ static resetInstance(): void {
+ SlackService.instance = null;
+ }
+
+ /**
+ * Delete Slack integration for a project
+ */
+ async deleteIntegration(projectId: string): Promise<void> {
+ try {
+ if (!this.installer.installationStore?.deleteInstallation) {
+ throw new Error("Installation store not configured");
+ }
+
+ await this.installer.installationStore.deleteInstallation({
+ teamId: projectId,
+ isEnterpriseInstall: false,
+ enterpriseId: undefined,
+ });
+
+ logger.info("Slack integration deleted for project", { projectId });
+ } catch (error) {
+ logger.error("Failed to delete Slack integration", { error, projectId });
+ throw new Error(
+ `Failed to delete integration: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ /**
+ * Get WebClient for a specific project
+ */
+ async getWebClientForProject(projectId: string): Promise<WebClient> {
+ try {
+ // Use projectId as the teamId parameter (handled by our fetchInstallation)
+ const auth = await this.installer.authorize({
+ teamId: projectId,
+ isEnterpriseInstall: false,
+ enterpriseId: undefined,
+ });
+
+ if (!auth.botToken) {
+ throw new Error("No bot token found for project");
+ }
+
+ const client = new WebClient(auth.botToken);
+ logger.debug("Created WebClient for project", { projectId });
+
+ return client;
+ } catch (error) {
+ logger.error("Failed to create WebClient for project", {
+ error,
+ projectId,
+ });
+ throw new Error(
+ `Failed to create WebClient: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ /**
+ * Get channels accessible to the bot
+ */
+ async getChannels(client: WebClient): Promise<SlackChannel[]> {
+ try {
+ const result = await client.conversations.list({
+ exclude_archived: true,
+ types: "public_channel",
+ limit: 200,
+ });
+
+ if (!result.ok) {
+ throw new Error(`Slack API error: ${result.error}`);
+ }
+
+ const channels: SlackChannel[] = (result.channels || []).map(
+ (channel) => ({
+ id: channel.id!,
+ name: channel.name!,
+ isPrivate: channel.is_private || false,
+ isMember: channel.is_member || false,
+ }),
+ );
+
+ logger.debug("Retrieved channels from Slack", {
+ channelCount: channels.length,
+ });
+
+ return channels;
+ } catch (error) {
+ logger.error("Failed to fetch channels", { error });
+ throw new Error(
+ `Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ /**
+ * Send a message to a Slack channel
+ */
+ async sendMessage(params: SlackMessageParams): Promise<SlackMessageResponse> {
+ try {
+ const result = await params.client.chat.postMessage({
+ channel: params.channelId,
+ blocks: params.blocks,
+ text: params.text || "Langfuse Notification",
+ unfurl_links: false,
+ unfurl_media: false,
+ });
+
+ if (!result.ok) {
+ throw new Error(`Failed to send message: ${result.error}`);
+ }
+
+ const response = {
+ messageTs: result.ts!,
+ channel: result.channel!,
+ };
+
+ logger.info("Message sent successfully to Slack", {
+ channel: params.channelId,
+ messageTs: response.messageTs,
+ });
+
+ return response;
+ } catch (error) {
+ logger.error("Failed to send message", {
+ error,
+ channelId: params.channelId,
+ });
+ throw new Error(
+ `Failed to send message: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ /**
+ * Validate a WebClient instance
+ */
+ async validateClient(client: WebClient): Promise<boolean> {
+ try {
+ const result = await client.auth.test();
+ return result.ok || false;
+ } catch (error) {
+ logger.warn("Client validation failed", { error });
+ return false;
+ }
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 68d8232473..917c62afa1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -187,6 +187,12 @@ importers:
'@react-email/render':
specifier: ^1.1.2
+ '@slack/oauth':
+ specifier: ^2.6.0
+ version: 2.6.3
+ '@slack/web-api':
+ specifier: ^7.0.0
+ version: 7.9.3
'@types/bcryptjs':
specifier: ^2.4.6
version: 2.4.6
@@ -512,6 +518,12 @@ importers:
'@sentry/nextjs':
specifier: ^8.52.0
+ '@slack/oauth':
+ specifier: ^2.6.0
+ version: 2.6.3
+ '@slack/web-api':
+ specifier: ^7.0.0
+ version: 7.9.3
'@t3-oss/env-nextjs':
specifier: ^0.11.1
@@ -610,7 +622,7 @@ importers:
version: 0.27.4
langchain:
specifier: ^0.3.28
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -900,6 +912,9 @@ importers:
'@prisma/instrumentation':
specifier: ^6.3.0
version: 6.3.0(@opentelemetry/[email protected])
+ '@slack/web-api':
+ specifier: ^7.0.0
+ version: 7.9.3
backoff:
specifier: ^2.5.0
version: 2.5.0
@@ -4682,6 +4697,30 @@ packages:
'@sinonjs/[email protected]':
resolution: {integrity: sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==}
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-DTuBFbqu4gGfajREEMrkq5jBhcnskinhr4+AnfJEk48zhVeEv3XnUKGIX98B74kxhYsIMfApGGySTn7V3b5yBA==}
+ engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-Wz7QYfPAlG/DR+DfABddUZeNgoeY7d1J39OCR2jR+v7VBsB8ezulDK5szTnDDPDwLH5IWhLvXIHlCFZV7MSKgA==}
+ engines: {node: '>= 18', npm: '>= 8.6.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-1amXs6xRkJpoH6zSgjVPgGEJXCibKNff9WNDijcejIuVy1HFAl1adh7lehaGNiHhTWfQkfKxBiF+BGn56kvoFw==}
+ engines: {node: '>=12.13.0', npm: '>=6.12.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-livb1gyG3J8ATLBJ3KjZfjHpTRz9btY1m5cgNuXxWJbhwRB1Gwb8Ly6XLJm2Sy1W6h+vLgqIHg7IwKrF1C1Szg==}
+ engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-dv65crIgdh9ZYHrevLU6XFHTQwTyDmNqEqzuIrV+Vqe/vgiG6w37oex5ePDU1RGm2IJ90H8iOvHFvzdEO/vB+g==}
+ engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-xjnoldVJyoUe61Ltqjr2UVYBolcsTpp5ottqzSI3l41UCaJgHSHIOpGuYps+nhLFvDfGGpDGUeQ7BWiq3+ypqA==}
+ engines: {node: '>= 18', npm: '>= 8.6.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-DhNPnqTqPoG8aZ5dWkFOgsuY+i0GQ3CI6hMmvCoduNsnU9gUZWZBwGfDQsTTB7NvFPkom1df7jMIJWU90kuXXg==}
engines: {node: '>=16.0.0'}
@@ -5361,6 +5400,9 @@ packages:
resolution: {integrity: sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-jkZatu4QVbR60mpIzjINmtS1ZF4a/FqdTUTBeQDVOQ2PYyidtwFKr0B5G6ERukKwliq+7mIXvxyppwzG5EgRYg==}
+
resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==}
@@ -5382,6 +5424,9 @@ packages:
resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-272FMnFGzAVMGtu9tkr29hRL6bZj4Zs1KZNeHLnKqAvp06tAIcarTMwOh8/8bz4FmKRcMxZhZNeUAQsNLoiPhg==}
+
resolution: {integrity: sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==}
@@ -6106,6 +6151,9 @@ packages:
resolution: {integrity: sha512-M0JtH+hlOL5pLQwHOLNYZaXuhqmvS8oExsqB1SBYgA4Dk7u/xx+YdGHXaK5pyUfed5mYXdlYiphWq3G8cRi5JQ==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==}
+
resolution: {integrity: sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==}
@@ -7603,9 +7651,15 @@ packages:
resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==}
+
resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
+ resolution: {integrity: sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==}
+
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
@@ -7806,6 +7860,10 @@ packages:
resolution: {integrity: sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==}
engines: {node: '>= 12.20'}
@@ -8357,6 +8415,9 @@ packages:
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
hasBin: true
+ resolution: {integrity: sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg==}
+
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
@@ -8454,6 +8515,10 @@ packages:
resolution: {integrity: sha512-JNeu1wQsHjyHgn9NcWTaXq6zWSR6hqE0++zhfZlkFBbScNkyvxCdeV8sRkSBaeLKxmbpR21brail63ACNxJ0Tg==}
+ resolution: {integrity: sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
@@ -8810,13 +8875,23 @@ packages:
resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==}
+ engines: {node: '>=12', npm: '>=6'}
+
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
engines: {node: '>=4.0'}
+ resolution: {integrity: sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==}
+
resolution: {integrity: sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==}
+ resolution: {integrity: sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==}
+
resolution: {integrity: sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==}
@@ -9059,9 +9134,21 @@ packages:
resolution: {integrity: sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==}
deprecated: This package is deprecated. Use the optional chaining (?.) operator instead.
+ resolution: {integrity: sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==}
+
resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}
+ resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}
+
+ resolution: {integrity: sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==}
+
+ resolution: {integrity: sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==}
+
resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}
@@ -9071,6 +9158,9 @@ packages:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
+ resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}
+
resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==}
@@ -14575,7 +14665,7 @@ snapshots:
dependencies:
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
chalk: 4.1.2
jest-message-util: 29.7.0
jest-util: 29.7.0
@@ -14660,7 +14750,7 @@ snapshots:
'@jest/transform': 29.7.0
'@jest/types': 29.6.3
'@jridgewell/trace-mapping': 0.3.25
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
chalk: 4.1.2
collect-v8-coverage: 1.0.2
exit: 0.1.2
@@ -17065,6 +17155,60 @@ snapshots:
dependencies:
'@sinonjs/commons': 3.0.1
+ '@slack/[email protected]':
+ dependencies:
+ '@types/node': 20.11.29
+
+ '@slack/[email protected]':
+ dependencies:
+ '@types/node': 20.11.29
+
+ '@slack/[email protected]':
+ dependencies:
+ '@slack/logger': 3.0.0
+ '@slack/web-api': 6.13.0
+ '@types/jsonwebtoken': 8.5.9
+ '@types/node': 20.11.29
+ jsonwebtoken: 9.0.2
+ lodash.isstring: 4.0.1
+ transitivePeerDependencies:
+ - debug
+
+ '@slack/[email protected]': {}
+
+ '@slack/[email protected]':
+ dependencies:
+ '@slack/logger': 3.0.0
+ '@slack/types': 2.15.0
+ '@types/is-stream': 1.1.0
+ '@types/node': 20.11.29
+ axios: 1.8.2
+ eventemitter3: 3.1.2
+ form-data: 2.5.3
+ is-electron: 2.2.2
+ is-stream: 1.1.0
+ p-queue: 6.6.2
+ p-retry: 4.6.2
+ transitivePeerDependencies:
+ - debug
+
+ '@slack/[email protected]':
+ dependencies:
+ '@slack/logger': 4.0.0
+ '@slack/types': 2.15.0
+ '@types/node': 20.11.29
+ '@types/retry': 0.12.0
+ axios: 1.11.0
+ eventemitter3: 5.0.1
+ form-data: 4.0.2
+ is-electron: 2.2.2
+ is-stream: 2.0.1
+ p-queue: 6.6.2
+ p-retry: 4.6.2
+ retry: 0.13.1
+ transitivePeerDependencies:
+ - debug
+
'@smithy/[email protected]':
dependencies:
'@smithy/types': 3.5.0
@@ -17889,11 +18033,11 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/[email protected]': {}
@@ -17903,7 +18047,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/[email protected]': {}
@@ -17970,7 +18114,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/qs': 6.14.0
'@types/range-parser': 1.2.7
'@types/send': 0.17.5
@@ -17997,7 +18141,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/[email protected]': {}
@@ -18007,6 +18151,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 20.11.29
+
'@types/[email protected]': {}
@@ -18032,6 +18180,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 20.11.29
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -18046,11 +18198,11 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
form-data: 4.0.2
@@ -18088,7 +18240,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
pg-protocol: 1.7.0
pg-types: 2.2.0
@@ -18128,7 +18280,7 @@ snapshots:
dependencies:
'@types/caseless': 0.12.5
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/tough-cookie': 4.0.5
form-data: 2.5.3
@@ -18155,7 +18307,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
'@types/[email protected]': {}
@@ -18179,7 +18331,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
optional: true
@@ -18309,7 +18461,7 @@ snapshots:
globby: 11.1.0
is-glob: 4.0.3
minimatch: 9.0.3
- semver: 7.7.1
+ semver: 7.7.2
ts-api-utils: 1.3.0([email protected])
optionalDependencies:
typescript: 5.4.5
@@ -18452,7 +18604,7 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
- eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
@@ -18972,6 +19124,14 @@ snapshots:
+ dependencies:
+ follow-redirects: 1.15.9
+ form-data: 4.0.4
+ proxy-from-env: 1.1.0
+ transitivePeerDependencies:
+ - debug
+
dependencies:
follow-redirects: 1.15.9
@@ -20431,7 +20591,7 @@ snapshots:
eslint-plugin-turbo: 2.5.5([email protected])([email protected])
turbo: 2.5.5
dependencies:
@@ -20522,7 +20682,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -20549,7 +20709,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -20816,8 +20976,12 @@ snapshots:
+
+
@@ -21060,6 +21224,14 @@ snapshots:
es-set-tostringtag: 2.1.0
mime-types: 2.1.35
+ dependencies:
+ asynckit: 0.4.0
+ combined-stream: 1.0.8
+ es-set-tostringtag: 2.1.0
+ hasown: 2.0.2
+ mime-types: 2.1.35
+
dependencies:
node-domexception: 1.0.0
@@ -21695,6 +21867,8 @@ snapshots:
+
@@ -21768,6 +21942,8 @@ snapshots:
dependencies:
protocols: 2.0.2
+
@@ -21845,7 +22021,7 @@ snapshots:
'@babel/parser': 7.24.1
'@istanbuljs/schema': 0.1.3
istanbul-lib-coverage: 3.2.2
- semver: 7.7.1
+ semver: 7.7.2
transitivePeerDependencies:
- supports-color
@@ -21900,7 +22076,7 @@ snapshots:
'@jest/expect': 29.7.0
'@jest/test-result': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
chalk: 4.1.2
co: 4.6.0
dedent: 1.5.1([email protected])
@@ -22060,7 +22236,7 @@ snapshots:
'@jest/environment': 29.7.0
'@jest/fake-timers': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
jest-mock: 29.7.0
jest-util: 29.7.0
@@ -22070,7 +22246,7 @@ snapshots:
dependencies:
'@jest/types': 29.6.3
'@types/graceful-fs': 4.1.9
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
anymatch: 3.1.3
fb-watchman: 2.0.2
graceful-fs: 4.2.11
@@ -22144,7 +22320,7 @@ snapshots:
'@jest/test-result': 29.7.0
'@jest/transform': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
chalk: 4.1.2
emittery: 0.13.1
graceful-fs: 4.2.11
@@ -22172,7 +22348,7 @@ snapshots:
'@jest/test-result': 29.7.0
'@jest/transform': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
chalk: 4.1.2
cjs-module-lexer: 1.4.1
collect-v8-coverage: 1.0.2
@@ -22211,7 +22387,7 @@ snapshots:
jest-util: 29.7.0
natural-compare: 1.4.0
pretty-format: 29.7.0
- semver: 7.7.1
+ semver: 7.7.2
transitivePeerDependencies:
- supports-color
@@ -22237,7 +22413,7 @@ snapshots:
dependencies:
'@jest/test-result': 29.7.0
'@jest/types': 29.6.3
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
ansi-escapes: 4.3.2
chalk: 4.1.2
emittery: 0.13.1
@@ -22252,7 +22428,7 @@ snapshots:
dependencies:
- '@types/node': 20.14.8
+ '@types/node': 20.11.29
jest-util: 29.7.0
merge-stream: 2.0.0
supports-color: 8.1.1
@@ -22392,6 +22568,19 @@ snapshots:
+ dependencies:
+ jws: 3.2.2
+ lodash.includes: 4.3.0
+ lodash.isboolean: 3.0.3
+ lodash.isinteger: 4.0.4
+ lodash.isnumber: 3.0.3
+ lodash.isplainobject: 4.0.6
+ lodash.isstring: 4.0.1
+ lodash.once: 4.1.1
+ ms: 2.1.3
+ semver: 7.7.2
+
dependencies:
array-includes: 3.1.7
@@ -22399,12 +22588,23 @@ snapshots:
object.assign: 4.1.5
object.values: 1.2.0
+ dependencies:
+ buffer-equal-constant-time: 1.0.1
+ ecdsa-sig-formatter: 1.0.11
+ safe-buffer: 5.2.1
+
dependencies:
buffer-equal-constant-time: 1.0.1
ecdsa-sig-formatter: 1.0.11
safe-buffer: 5.2.1
+ dependencies:
+ jwa: 1.4.2
+ safe-buffer: 5.2.1
+
dependencies:
jwa: 2.0.0
@@ -22447,6 +22647,33 @@ snapshots:
+ dependencies:
+ '@langchain/core': 0.3.58([email protected]([email protected]))
+ '@langchain/openai': 0.5.13(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/textsplitters': 0.1.0(@langchain/[email protected]([email protected]([email protected])))
+ js-tiktoken: 1.0.15
+ js-yaml: 4.1.0
+ jsonpointer: 5.0.1
+ openapi-types: 12.1.3
+ p-retry: 4.6.2
+ uuid: 10.0.0
+ yaml: 2.5.1
+ zod: 3.25.62
+ optionalDependencies:
+ '@langchain/anthropic': 0.3.22(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/aws': 0.1.11(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/google-genai': 0.2.12(@langchain/[email protected]([email protected]([email protected])))
+ '@langchain/google-vertexai': 0.2.12(@langchain/[email protected]([email protected]([email protected])))([email protected])
+ axios: 1.11.0
+ cheerio: 1.0.0
+ handlebars: 4.7.8
+ transitivePeerDependencies:
+ - encoding
+ - openai
+ - ws
+
dependencies:
'@langchain/core': 0.3.58([email protected]([email protected]))
@@ -22572,14 +22799,24 @@ snapshots:
+
+
+
+
+
@@ -22652,7 +22889,7 @@ snapshots:
dependencies:
- semver: 7.7.1
+ semver: 7.7.2
diff --git a/web/package.json b/web/package.json
index 49413ae16d..6c7e385aa3 100644
--- a/web/package.json
+++ b/web/package.json
@@ -9,6 +9,7 @@
"scripts": {
"build": "INLINE_RUNTIME_CHUNK=false dotenv -e ../.env -- next build",
"dev": "dotenv -e ../.env -- next dev",
+ "dev:https": "dotenv -e ../.env -- next dev --experimental-https --experimental-https-key ./localhost+1-key.pem --experimental-https-cert ./localhost+1.pem",
"lint": "dotenv -e ../.env -- next lint --max-warnings 0",
"lint:fix": "dotenv -e ../.env -- next lint --fix",
"clean": "rm -rf node_modules",
@@ -83,6 +84,8 @@
"@radix-ui/react-tooltip": "^1.2.7",
"@remixicon/react": "^4.2.0",
"@sentry/nextjs": "^8.52.0",
+ "@slack/oauth": "^2.6.0",
+ "@slack/web-api": "^7.0.0",
"@t3-oss/env-nextjs": "^0.11.1",
"@tailwindcss/container-queries": "^0.1.1",
"@tanstack/react-query": "^4.36.1",
diff --git a/web/public/icon1024.png b/web/public/icon1024.png
new file mode 100644
index 0000000000..c1dce6ae93
Binary files /dev/null and b/web/public/icon1024.png differ
diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/async/automations-trpc.servertest.ts
index a126c97384..7e3cad70ce 100644
--- a/web/src/__tests__/async/automations-trpc.servertest.ts
+++ b/web/src/__tests__/async/automations-trpc.servertest.ts
@@ -12,6 +12,7 @@ import {
JobConfigState,
type SafeWebhookActionConfig,
type WebhookActionConfigWithSecrets,
+ isWebhookAction,
} from "@langfuse/shared";
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import { generateWebhookSecret } from "@langfuse/shared/encryption";
@@ -204,11 +205,10 @@ describe("automations trpc", () => {
"x-api-key": encrypt("secret-api-key-123"),
authorization: encrypt("Bearer secret-token-456"),
},
- secretHeaderKeys: ["x-api-key", "authorization"],
displayHeaders: {
- "content-type": "application/json",
- "x-api-key": "secr***123",
- authorization: "Bear***456",
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "secr***123" },
+ authorization: { secret: true, value: "Bear***456" },
},
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
@@ -232,13 +232,14 @@ describe("automations trpc", () => {
});
expect(response).toHaveLength(1);
- const automationConfig = response[0].action.config;
+ const automationConfig = response[0].action
+ .config as SafeWebhookActionConfig;
// Should have display values, not encrypted values
expect(automationConfig.displayHeaders).toEqual({
- "content-type": "application/json",
- "x-api-key": "secr***123",
- authorization: "Bear***456",
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "secr***123" },
+ authorization: { secret: true, value: "Bear***456" },
});
// Should NOT have the raw headers with encrypted values
@@ -321,7 +322,9 @@ describe("automations trpc", () => {
type: "WEBHOOK",
url: "https://example.com/webhook",
headers: { "Content-Type": "application/json" },
- displayHeaders: { "Content-Type": "application/json" },
+ displayHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -353,20 +356,22 @@ describe("automations trpc", () => {
}),
});
+ const actionConfig = response.action.config as SafeWebhookActionConfig;
+
// check that the action does not have a secret key in the config
- expect(response.action.config).not.toHaveProperty("secretKey");
- expect(response.action.config).toHaveProperty("displaySecretKey");
- expect(response.action.config.url).toBe("https://example.com/webhook");
- expect(response.action.config).not.toHaveProperty("headers");
- expect(response.action.config.displayHeaders).toEqual({
- "Content-Type": "application/json",
- });
- expect(response.action.config.apiVersion).toEqual({ prompt: "v1" });
- expect(response.action.config.type).toBe("WEBHOOK");
- expect(response.action.config.displaySecretKey).toBe(displaySecretKey);
- expect(response.action.config).not.toHaveProperty("headers");
- expect(response.action.config).not.toHaveProperty("decryptedHeaders");
- expect(response.action.config).not.toHaveProperty("requestHeaders");
+ expect(actionConfig).not.toHaveProperty("secretKey");
+ expect(actionConfig).toHaveProperty("displaySecretKey");
+ expect(actionConfig.url).toBe("https://example.com/webhook");
+ expect(actionConfig).not.toHaveProperty("headers");
+ expect(actionConfig.displayHeaders).toEqual({
+ "Content-Type": { secret: false, value: "application/json" },
+ });
+ expect(actionConfig.apiVersion).toEqual({ prompt: "v1" });
+ expect(actionConfig.type).toBe("WEBHOOK");
+ expect(actionConfig.displaySecretKey).toBe(displaySecretKey);
+ expect(actionConfig).not.toHaveProperty("headers");
+ expect(actionConfig).not.toHaveProperty("decryptedHeaders");
+ expect(actionConfig).not.toHaveProperty("requestHeaders");
});
it("should not expose secret headers in single automation response", async () => {
@@ -398,11 +403,10 @@ describe("automations trpc", () => {
"x-custom": "public-value",
"x-secret": encrypt("secret-value-789"),
},
- secretHeaderKeys: ["x-secret"],
displayHeaders: {
- "content-type": "application/json",
- "x-custom": "public-value",
- "x-secret": "secr***789",
+ "content-type": { secret: false, value: "application/json" },
+ "x-custom": { secret: false, value: "public-value" },
+ "x-secret": { secret: true, value: "secr***789" },
},
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
@@ -425,13 +429,13 @@ describe("automations trpc", () => {
automationId: automation.id,
});
- const config = response.action.config;
+ const config = response.action.config as SafeWebhookActionConfig;
// Should have display values
expect(config.displayHeaders).toEqual({
- "content-type": "application/json",
- "x-custom": "public-value",
- "x-secret": "secr***789",
+ "content-type": { secret: false, value: "application/json" },
+ "x-custom": { secret: false, value: "public-value" },
+ "x-secret": { secret: true, value: "secr***789" },
});
// Should NOT have raw encrypted headers
@@ -488,7 +492,7 @@ describe("automations trpc", () => {
automationId: automation.id,
});
- const config = response.action.config;
+ const config = response.action.config as SafeWebhookActionConfig;
// Should have display values with all legacy header values returned
// Legacy headers are converted to the new format with secret: false
@@ -629,6 +633,7 @@ describe("automations trpc", () => {
type: "WEBHOOK",
url: "https://example.com/mixed-headers",
});
+ expect(isWebhookAction(createdAction as any)).toBe(true);
// Headers should be encrypted for secret ones, plain for others
const config = createdAction?.config as WebhookActionConfigWithSecrets;
@@ -795,6 +800,85 @@ describe("automations trpc", () => {
}),
).rejects.toThrow("Name is required");
});
+
+ it("should create a new Slack automation", async () => {
+ const { project, caller } = await prepare();
+
+ // Create Slack integration first
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const response = await caller.automations.createAutomation({
+ projectId: project.id,
+ name: "New Slack Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "SLACK",
+ actionConfig: {
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ messageTemplate: JSON.stringify([
+ {
+ type: "section",
+ text: { type: "mrkdwn", text: "Custom template" },
+ },
+ ]),
+ },
+ });
+
+ expect(response.trigger).toMatchObject({
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ status: JobConfigState.ACTIVE,
+ });
+
+ expect(response.action).toMatchObject({
+ projectId: project.id,
+ type: "SLACK",
+ config: expect.objectContaining({
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ }),
+ });
+
+ // Ensure no bot token is exposed in response
+ expect(JSON.stringify(response)).not.toContain("xoxb-");
+ });
+
+ it("should fail to create Slack automation without integration", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.automations.createAutomation({
+ projectId: project.id,
+ name: "Invalid Slack Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "SLACK",
+ actionConfig: {
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ },
+ }),
+ ).rejects.toThrow(
+ "Slack integration not found. Please connect your Slack workspace first.",
+ );
+ });
});
describe("automations.updateAutomation", () => {
@@ -922,9 +1006,9 @@ describe("automations trpc", () => {
"x-case-key": { secret: false, value: "some-value" },
},
displayHeaders: {
- "content-type": "application/json",
- "x-old-header": "old-value",
- "x-case-key": "some-value",
+ "content-type": { secret: false, value: "application/json" },
+ "x-old-header": { secret: false, value: "old-value" },
+ "x-case-key": { secret: false, value: "some-value" },
},
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
@@ -963,19 +1047,20 @@ describe("automations trpc", () => {
apiVersion: { prompt: "v1" },
},
});
+ const actionConfig = response.action.config as SafeWebhookActionConfig;
// Verify the API response contains safe display values
- expect(response.action.config.displayHeaders).toMatchObject({
+ expect(actionConfig.displayHeaders).toMatchObject({
"content-type": { secret: false, value: "application/json" }, // header preserved
"x-public": { secret: false, value: "new-public-value" }, // new public header
"x-secret-key": { secret: true, value: "new-...-123" }, // new secret header
"x-Case-KEY": { secret: false, value: "new-value" }, // matched existing key, but new value
});
- expect(response.action.config.displayHeaders).not.toHaveProperty(
+ expect(actionConfig.displayHeaders).not.toHaveProperty(
"x-old-header", // header deleted
);
- expect(response.action.config.displayHeaders).not.toHaveProperty(
+ expect(actionConfig.displayHeaders).not.toHaveProperty(
"x-case-key", // new case replaced the old header name
);
@@ -1083,9 +1168,10 @@ describe("automations trpc", () => {
apiVersion: { prompt: "v1" },
},
});
+ const actionConfig = response.action.config as SafeWebhookActionConfig;
// Verify the API response contains safe display values reflecting the switch
- expect(response.action.config.displayHeaders).toMatchObject({
+ expect(actionConfig.displayHeaders).toMatchObject({
"x-currently-public": { secret: true, value: "now-...alue" },
"x-currently-secret": { secret: false, value: "now-public-value" },
});
@@ -1097,7 +1183,7 @@ describe("automations trpc", () => {
where: { id: action.id },
});
- const config = updatedAction?.config as any;
+ const config = updatedAction?.config as WebhookActionConfigWithSecrets;
// x-currently-public should now be encrypted (was plain, now secret)
expect(config.requestHeaders["x-currently-public"].value).not.toBe(
@@ -1283,14 +1369,13 @@ describe("automations trpc", () => {
apiVersion: { prompt: "v1" },
},
});
+ const actionConfig = response.action.config as SafeWebhookActionConfig;
// Verify the URL was updated
- expect(response.action.config.url).toBe(
- "https://example.com/new-webhook-url",
- );
+ expect(actionConfig.url).toBe("https://example.com/new-webhook-url");
// Verify secret headers were preserved
- expect(response.action.config.displayHeaders).toMatchObject({
+ expect(actionConfig.displayHeaders).toMatchObject({
"content-type": { secret: false, value: "application/json" },
"x-api-key": { secret: true, value: "secr...-123" },
authorization: { secret: true, value: "Bear...-456" },
@@ -1388,8 +1473,10 @@ describe("automations trpc", () => {
},
});
+ const actionConfig = response.action.config as SafeWebhookActionConfig;
+
// Verify the API response
- expect(response.action.config.displayHeaders).toMatchObject({
+ expect(actionConfig.displayHeaders).toMatchObject({
"content-type": { secret: false, value: "application/json" },
"x-api-key": { secret: true, value: "new-...-key" },
});
diff --git a/web/src/__tests__/async/slack-integration.servertest.ts b/web/src/__tests__/async/slack-integration.servertest.ts
new file mode 100644
index 0000000000..cc04051a7b
--- /dev/null
+++ b/web/src/__tests__/async/slack-integration.servertest.ts
@@ -0,0 +1,554 @@
+import { prisma } from "@langfuse/shared/src/db";
+import type { Session } from "next-auth";
+import { encrypt } from "@langfuse/shared/encryption";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { appRouter } from "@/src/server/api/root";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+
+// Mock SlackService
+jest.mock("@langfuse/shared/src/server", () => {
+ const actual = jest.requireActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ SlackService: {
+ getInstance: jest.fn(),
+ },
+ };
+});
+
+const __orgIds: string[] = [];
+let mockSlackService: any;
+
+const prepare = async () => {
+ const { project, org } = await createOrgProjectAndApiKey();
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Demo User",
+ organizations: [
+ {
+ id: org.id,
+ name: org.name,
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: [
+ {
+ id: project.id,
+ role: "ADMIN",
+ retentionDays: 30,
+ deletedAt: null,
+ name: project.name,
+ metadata: {},
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: true,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:hobby",
+ },
+ };
+
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ __orgIds.push(org.id);
+
+ return { project, org, session, ctx, caller };
+};
+
+describe("Slack Integration", () => {
+ beforeAll(async () => {
+ // Import mocked SlackService
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Create mock service instance
+ mockSlackService = {
+ getWebClientForProject: jest.fn(),
+ sendMessage: jest.fn(),
+ getChannels: jest.fn(),
+ validateClient: jest.fn(),
+ deleteIntegration: jest.fn(),
+ };
+
+ // Setup the getInstance mock to return our mock service
+ (SlackService.getInstance as jest.Mock).mockReturnValue(mockSlackService);
+ });
+
+ afterAll(async () => {
+ await prisma.organization.deleteMany({
+ where: {
+ id: { in: __orgIds },
+ },
+ });
+ });
+
+ describe("Slack tRPC Router", () => {
+ describe("getIntegrationStatus", () => {
+ it("should return connected status for valid integration", async () => {
+ mockSlackService.validateClient.mockResolvedValue(true);
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token-secret"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.getIntegrationStatus({
+ projectId: project.id,
+ });
+
+ expect(result).toMatchObject({
+ isConnected: true,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botUserId: "U123456",
+ installUrl: null,
+ });
+
+ // πŸ”’ CRITICAL: Ensure no bot token is exposed
+ expect(JSON.stringify(result)).not.toContain("xoxb-test-token-secret");
+ expect(result).not.toHaveProperty("botToken");
+ });
+
+ it("should return disconnected status when no integration exists", async () => {
+ const { caller, project } = await prepare();
+
+ const result = await caller.slack.getIntegrationStatus({
+ projectId: project.id,
+ });
+
+ expect(result).toMatchObject({
+ isConnected: false,
+ teamId: null,
+ teamName: null,
+ installUrl: expect.stringContaining(
+ `/api/public/slack/install?projectId=${project.id}`,
+ ),
+ });
+
+ // πŸ”’ Ensure no sensitive data is present
+ expect(JSON.stringify(result)).not.toContain("xoxb-");
+ });
+
+ it("should return disconnected status for invalid integration", async () => {
+ mockSlackService.validateClient.mockResolvedValue(false);
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration with invalid token
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-invalid-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.getIntegrationStatus({
+ projectId: project.id,
+ });
+
+ expect(result).toMatchObject({
+ isConnected: false,
+ teamId: "T123456",
+ teamName: "Test Team",
+ error:
+ "Integration is invalid. Please reconnect your Slack workspace.",
+ });
+
+ // πŸ”’ CRITICAL: Ensure no bot token is exposed even for invalid integrations
+ expect(JSON.stringify(result)).not.toContain("xoxb-invalid-token");
+ });
+ });
+
+ describe("getChannels", () => {
+ it("should fetch channels for valid integration", async () => {
+ const mockChannels = [
+ { id: "C123456", name: "general", isPrivate: false, isMember: true },
+ { id: "C789012", name: "random", isPrivate: false, isMember: true },
+ {
+ id: "C345678",
+ name: "private-channel",
+ isPrivate: true,
+ isMember: true,
+ },
+ ];
+
+ mockSlackService.getChannels.mockResolvedValue(mockChannels);
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-valid-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.getChannels({
+ projectId: project.id,
+ });
+
+ expect(result).toMatchObject({
+ channels: mockChannels,
+ teamId: "T123456",
+ teamName: "Test Team",
+ });
+
+ // πŸ”’ CRITICAL: Ensure no bot token is exposed in channel data
+ expect(JSON.stringify(result)).not.toContain("xoxb-valid-token");
+ expect(result).not.toHaveProperty("botToken");
+ });
+
+ it("should throw NOT_FOUND for missing integration", async () => {
+ const { caller, project } = await prepare();
+
+ await expect(
+ caller.slack.getChannels({ projectId: project.id }),
+ ).rejects.toThrow("Slack integration not found");
+ });
+
+ it("should handle Slack API failures gracefully", async () => {
+ mockSlackService.getChannels.mockRejectedValue(
+ new Error("Slack API error"),
+ );
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ await expect(
+ caller.slack.getChannels({ projectId: project.id }),
+ ).rejects.toThrow(
+ "Failed to fetch channels. Please check your Slack connection and try again.",
+ );
+ });
+ });
+
+ describe("sendTestMessage", () => {
+ it("should send test message successfully", async () => {
+ const mockClient = { auth: { test: jest.fn() } };
+ mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);
+ mockSlackService.sendMessage.mockResolvedValue({
+ messageTs: "1234567890.123456",
+ channel: "C123456",
+ });
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.sendTestMessage({
+ projectId: project.id,
+ channelId: "C123456",
+ channelName: "general",
+ });
+
+ expect(result).toMatchObject({
+ success: true,
+ messageTs: "1234567890.123456",
+ channel: "C123456",
+ });
+
+ // Verify SlackService was called with proper parameters
+ expect(mockSlackService.sendMessage).toHaveBeenCalledWith({
+ client: expect.any(Object),
+ channelId: "C123456",
+ blocks: expect.any(Array),
+ text: "Test message from Langfuse",
+ });
+
+ // πŸ”’ CRITICAL: Ensure no bot token is exposed in test results
+ expect(JSON.stringify(result)).not.toContain("xoxb-test-token");
+ });
+
+ it("should create audit log entry", async () => {
+ const mockClient = { auth: { test: jest.fn() } };
+ mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);
+ mockSlackService.sendMessage.mockResolvedValue({
+ messageTs: "1234567890.123456",
+ channel: "C123456",
+ });
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ const integration = await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ await caller.slack.sendTestMessage({
+ projectId: project.id,
+ channelId: "C123456",
+ channelName: "general",
+ });
+
+ // Verify audit log was created
+ const auditLog = await prisma.auditLog.findFirst({
+ where: {
+ projectId: project.id,
+ resourceType: "slackIntegration",
+ resourceId: integration.id,
+ action: "create",
+ },
+ });
+
+ expect(auditLog).toBeDefined();
+ const afterData = auditLog?.after ? JSON.parse(auditLog.after) : null;
+ expect(afterData).toMatchObject({
+ action: "test_message_sent",
+ channelId: "C123456",
+ channelName: "general",
+ messageTs: "1234567890.123456",
+ });
+
+ // πŸ”’ Ensure audit log doesn't contain tokens
+ expect(JSON.stringify(afterData)).not.toContain("xoxb-");
+ });
+ });
+
+ describe("disconnect", () => {
+ it("should remove integration and audit log it", async () => {
+ mockSlackService.deleteIntegration.mockResolvedValue(undefined);
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ const integration = await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.disconnect({
+ projectId: project.id,
+ });
+
+ expect(result).toMatchObject({
+ success: true,
+ });
+
+ // Verify SlackService was called
+ expect(mockSlackService.deleteIntegration).toHaveBeenCalledWith(
+ project.id,
+ );
+
+ // Verify audit log was created
+ const auditLog = await prisma.auditLog.findFirst({
+ where: {
+ projectId: project.id,
+ resourceType: "slackIntegration",
+ resourceId: integration.id,
+ action: "delete",
+ },
+ });
+
+ expect(auditLog).toBeDefined();
+ const beforeData = auditLog?.before
+ ? JSON.parse(auditLog.before)
+ : null;
+ expect(beforeData).toMatchObject({
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ });
+
+ // πŸ”’ CRITICAL: Ensure audit log doesn't expose encrypted bot token
+ expect(JSON.stringify(beforeData)).not.toContain("xoxb-");
+ // But encrypted token should be in the audit log for recovery purposes
+ expect(beforeData).toHaveProperty("botToken");
+ });
+
+ it("should handle missing integration gracefully", async () => {
+ const { caller, project } = await prepare();
+
+ await expect(
+ caller.slack.disconnect({ projectId: project.id }),
+ ).rejects.toThrow("Slack integration not found");
+ });
+ });
+ });
+
+ describe("Slack Security", () => {
+ it("should encrypt bot tokens in database", async () => {
+ const { project } = await prepare();
+
+ const originalToken = "xoxb-secret-bot-token-12345";
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt(originalToken),
+ botUserId: "U123456",
+ },
+ });
+
+ // Verify token is encrypted in database
+ const rawIntegration = await prisma.slackIntegration.findUnique({
+ where: { projectId: project.id },
+ });
+
+ expect(rawIntegration?.botToken).toBeDefined();
+ expect(rawIntegration?.botToken).not.toBe(originalToken);
+ expect(rawIntegration?.botToken).not.toContain("xoxb-secret-bot-token");
+
+ // Verify the encrypted token can be decrypted back to original
+ const { decrypt } = await import("@langfuse/shared/encryption");
+ const decryptedToken = decrypt(rawIntegration!.botToken);
+ expect(decryptedToken).toBe(originalToken);
+ });
+
+ it("should NEVER expose raw bot tokens in any API response", async () => {
+ mockSlackService.validateClient.mockResolvedValue(true);
+ mockSlackService.getChannels.mockResolvedValue([
+ { id: "C123456", name: "general", isPrivate: false, isMember: true },
+ ]);
+ mockSlackService.sendMessage.mockResolvedValue({
+ messageTs: "1234567890.123456",
+ channel: "C123456",
+ });
+
+ const { caller, project } = await prepare();
+
+ const secretToken = "xoxb-extremely-secret-token-abcdef123456";
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt(secretToken),
+ botUserId: "U123456",
+ },
+ });
+
+ // Test all tRPC endpoints
+ const results = await Promise.all([
+ caller.slack.getIntegrationStatus({ projectId: project.id }),
+ caller.slack.getChannels({ projectId: project.id }),
+ caller.slack.sendTestMessage({
+ projectId: project.id,
+ channelId: "C123456",
+ channelName: "general",
+ }),
+ ]);
+
+ results.forEach((result) => {
+ const resultText = JSON.stringify(result);
+
+ // πŸ”’ CRITICAL: Ensure no raw token appears anywhere in response
+ expect(resultText).not.toContain(secretToken);
+ expect(resultText).not.toContain("xoxb-extremely-secret-token");
+ });
+ });
+
+ it("should NEVER set unencrypted tokens in cookies", async () => {
+ const { caller, project } = await prepare();
+
+ // Test tRPC calls (cookies would be set at HTTP layer, not tRPC layer)
+ const result = await caller.slack.getIntegrationStatus({
+ projectId: project.id,
+ });
+
+ // πŸ”’ Ensure tRPC result doesn't contain any token fields that could leak to cookies
+ expect(JSON.stringify(result)).not.toContain("xoxb-");
+ expect(result).not.toHaveProperty("botToken");
+ expect(result).not.toHaveProperty("token");
+ });
+
+ it("should sanitize tokens from error messages", async () => {
+ const secretToken = "xoxb-secret-error-token-999";
+
+ // Mock SlackService to throw error containing token
+ mockSlackService.getChannels.mockRejectedValue(
+ new Error(`Authentication failed for token ${secretToken}`),
+ );
+
+ const { caller, project } = await prepare();
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt(secretToken),
+ botUserId: "U123456",
+ },
+ });
+
+ try {
+ await caller.slack.getChannels({ projectId: project.id });
+ throw new Error("Expected error to be thrown");
+ } catch (error) {
+ const errorMessage =
+ error instanceof TRPCError ? error.message : String(error);
+
+ // πŸ”’ CRITICAL: Error messages should not contain raw tokens
+ expect(errorMessage).not.toContain(secretToken);
+ expect(errorMessage).not.toContain("xoxb-secret-error-token");
+
+ // Should still indicate there was an error, just sanitized
+ expect(errorMessage).toContain("Failed to fetch channels.");
+ }
+ });
+ });
+});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 7a0cc2b26f..6165185e6f 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -269,6 +269,10 @@ export const env = createEnv({
LANGFUSE_UI_VISIBLE_PRODUCT_MODULES: z.string().optional(),
// UI customization - comma-separated list of hidden product modules
LANGFUSE_UI_HIDDEN_PRODUCT_MODULES: z.string().optional(),
+
+ SLACK_CLIENT_ID: z.string().optional(),
+ SLACK_CLIENT_SECRET: z.string().optional(),
+ SLACK_STATE_SECRET: z.string().optional(),
},
/**
@@ -536,6 +540,9 @@ export const env = createEnv({
NEXT_PUBLIC_BASE_PATH: process.env.NEXT_PUBLIC_BASE_PATH,
LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT:
process.env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
+ SLACK_CLIENT_ID: process.env.SLACK_CLIENT_ID,
+ SLACK_CLIENT_SECRET: process.env.SLACK_CLIENT_SECRET,
+ SLACK_STATE_SECRET: process.env.SLACK_STATE_SECRET,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 6670be7a95..3af4e8e919 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -37,6 +37,7 @@ export type AuditableResource =
| "batchAction"
| "automation"
| "action"
+ | "slackIntegration"
// legacy resources
| "membership";
diff --git a/web/src/features/automations/components/WebhookButton.tsx b/web/src/features/automations/components/AutomationButton.tsx
similarity index 78%
rename from web/src/features/automations/components/WebhookButton.tsx
rename to web/src/features/automations/components/AutomationButton.tsx
index 9b11e082be..4abcf4cf99 100644
--- a/web/src/features/automations/components/WebhookButton.tsx
+++ b/web/src/features/automations/components/AutomationButton.tsx
@@ -4,7 +4,7 @@ import { Zap, Loader2 } from "lucide-react";
import { type ButtonProps } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
-export const WebhookButton = ({
+export const AutomationButton = ({
projectId,
...buttonProps
}: {
@@ -15,22 +15,21 @@ export const WebhookButton = ({
scope: "automations:read",
});
- const numberOfWebHooks = api.automations.count.useQuery({
+ const numberOfAutomations = api.automations.count.useQuery({
projectId,
- type: "WEBHOOK",
});
- const numberIndicator = numberOfWebHooks.isLoading ? (
+ const numberIndicator = numberOfAutomations.isLoading ? (
<span className="ml-1.5 inline-flex w-6 items-center justify-center rounded-sm bg-transparent px-1 text-xs">
<Loader2 className="h-3 w-3 animate-spin" />
</span>
) : (
<span
className={
- "ml-1.5 inline-flex w-6 items-center justify-center rounded-sm bg-input px-1 text-xs shadow-sm @6xl:inline @6xl:hidden"
+ "ml-1.5 inline-flex w-6 items-center justify-center rounded-sm bg-input px-1 text-xs shadow-sm @6xl:inline"
}
>
- {numberOfWebHooks.data}
+ {numberOfAutomations.data}
</span>
);
@@ -39,12 +38,12 @@ export const WebhookButton = ({
href={`/project/${projectId}/automations`}
icon={<Zap className="h-4 w-4" aria-hidden="true" />}
hasAccess={hasAccess}
- title="Webhooks"
+ title="Automations"
variant="outline"
{...buttonProps}
>
<span className="hidden md:ml-1 md:inline">
- Webhooks
+ Automations
{numberIndicator}
</span>
</ActionButton>
diff --git a/web/src/features/automations/components/AutomationDetails.tsx b/web/src/features/automations/components/AutomationDetails.tsx
index 631b12f55f..da4bbbdbe6 100644
--- a/web/src/features/automations/components/AutomationDetails.tsx
+++ b/web/src/features/automations/components/AutomationDetails.tsx
@@ -72,13 +72,15 @@ export const AutomationDetails: React.FC<AutomationDetailsProps> = ({
};
if (isLoading) {
- return <div className="py-4 text-center">Loading webhook details...</div>;
+ return (
+ <div className="py-4 text-center">Loading automation details...</div>
+ );
}
if (!automation) {
return (
<div className="py-4 text-center text-muted-foreground">
- Webhook not found.
+ Automation not found.
</div>
);
}
@@ -92,16 +94,7 @@ export const AutomationDetails: React.FC<AutomationDetailsProps> = ({
filter: automation.trigger.filter as FilterState,
eventActions: automation.trigger.eventActions,
},
- action: {
- ...automation.action,
- config: automation.action.config as {
- type: "WEBHOOK";
- url: string;
- displayHeaders: Record<string, { secret: boolean; value: string }>;
- apiVersion: Record<"prompt", "v1">;
- displaySecretKey: string;
- },
- },
+ action: automation.action,
};
return (
diff --git a/web/src/features/automations/components/AutomationSidebar.tsx b/web/src/features/automations/components/AutomationSidebar.tsx
index bb01b93120..c79d0be0bc 100644
--- a/web/src/features/automations/components/AutomationSidebar.tsx
+++ b/web/src/features/automations/components/AutomationSidebar.tsx
@@ -31,7 +31,7 @@ export const AutomationSidebar: React.FC<AutomationSidebarProps> = ({
)}
>
<div className="p-4 text-center text-sm text-muted-foreground">
- Loading webhooks...
+ Loading automations...
</div>
</div>
);
@@ -46,7 +46,7 @@ export const AutomationSidebar: React.FC<AutomationSidebarProps> = ({
)}
>
<div className="p-4 text-center text-sm text-muted-foreground">
- No webhooks configured. Create your first webhook to automate
+ No automations configured. Create your first automation to streamline
workflows.
</div>
</div>
@@ -99,7 +99,9 @@ export const AutomationSidebar: React.FC<AutomationSidebarProps> = ({
{" β†’ "}
{automation.action.type === "WEBHOOK"
? "Webhook"
- : "Annotation Queue"}
+ : automation.action.type === "SLACK"
+ ? "Slack"
+ : "Annotation Queue"}
</p>
</div>
</div>
diff --git a/web/src/features/automations/components/actions/ActionHandlerRegistry.ts b/web/src/features/automations/components/actions/ActionHandlerRegistry.ts
index 35dc92391c..6ec122c3d1 100644
--- a/web/src/features/automations/components/actions/ActionHandlerRegistry.ts
+++ b/web/src/features/automations/components/actions/ActionHandlerRegistry.ts
@@ -2,6 +2,7 @@ import { type ActionType } from "@langfuse/shared";
import { type FieldValues } from "react-hook-form";
import { type BaseActionHandler } from "./BaseActionHandler";
import { WebhookActionHandler } from "./WebhookActionHandler";
+import { SlackActionHandler } from "./SlackActionHandler";
export class ActionHandlerRegistry {
private static handlers: Map<ActionType, BaseActionHandler<FieldValues>> =
@@ -10,6 +11,7 @@ export class ActionHandlerRegistry {
static {
// Initialize handlers in static block
this.handlers.set("WEBHOOK", new WebhookActionHandler());
+ this.handlers.set("SLACK", new SlackActionHandler());
}
static getHandler<T extends FieldValues = FieldValues>(
diff --git a/web/src/features/automations/components/actions/SlackActionForm.tsx b/web/src/features/automations/components/actions/SlackActionForm.tsx
new file mode 100644
index 0000000000..d6fa47035a
--- /dev/null
+++ b/web/src/features/automations/components/actions/SlackActionForm.tsx
@@ -0,0 +1,133 @@
+import { Input } from "@/src/components/ui/input";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { type UseFormReturn } from "react-hook-form";
+import { type ActionDomain } from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+import { SlackConnectionCard } from "@/src/features/slack/components/SlackConnectionCard";
+import {
+ ChannelSelector,
+ type SlackChannel,
+} from "@/src/features/slack/components/ChannelSelector";
+import { SlackTestMessageButton } from "@/src/features/slack/components/SlackTestMessageButton";
+import { useState } from "react";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+interface SlackActionFormProps {
+ form: UseFormReturn<any>;
+ disabled: boolean;
+ projectId: string;
+ action?: ActionDomain;
+}
+
+export const SlackActionForm: React.FC<SlackActionFormProps> = ({
+ form,
+ disabled,
+ projectId,
+}) => {
+ const [selectedChannel, setSelectedChannel] = useState<SlackChannel | null>(
+ null,
+ );
+
+ // Get Slack integration status
+ const { data: integrationStatus } = api.slack.getIntegrationStatus.useQuery(
+ { projectId },
+ { enabled: !!projectId },
+ );
+
+ // Check user permissions
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+
+ // Handle channel selection
+ const handleChannelSelect = (channel: SlackChannel) => {
+ form.setValue("slack.channelId", channel.id);
+ form.setValue("slack.channelName", channel.name);
+ setSelectedChannel(channel);
+ };
+
+ // Handle connection status change
+ const handleConnectionChange = (connected: boolean) => {
+ if (!connected) {
+ // Clear channel selection when disconnected
+ form.setValue("slack.channelId", "");
+ form.setValue("slack.channelName", "");
+ setSelectedChannel(null);
+ }
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Slack Connection Card */}
+ <SlackConnectionCard
+ projectId={projectId}
+ disabled={disabled}
+ onConnectionChange={handleConnectionChange}
+ showConnectButton={true}
+ />
+
+ {/* Channel Selection - Only show when connected */}
+ {integrationStatus?.isConnected && (
+ <div className="space-y-4">
+ <FormField
+ control={form.control}
+ name="slack.channelId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Channel</FormLabel>
+ <FormControl>
+ <div className="max-w-md">
+ <ChannelSelector
+ projectId={projectId}
+ selectedChannelId={field.value}
+ onChannelSelect={handleChannelSelect}
+ disabled={disabled}
+ placeholder="Select a channel"
+ showRefreshButton={true}
+ />
+ </div>
+ </FormControl>
+ <FormDescription>
+ Select the Slack channel where notifications will be sent.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Hidden field for channel name */}
+ <FormField
+ control={form.control}
+ name="slack.channelName"
+ render={({ field }) => <Input type="hidden" {...field} />}
+ />
+
+ {/* Test Message Button - Only show when a channel is selected */}
+ {selectedChannel && (
+ <div className="flex items-center gap-3 pt-2">
+ <SlackTestMessageButton
+ projectId={projectId}
+ selectedChannel={selectedChannel}
+ hasAccess={hasAccess}
+ disabled={disabled}
+ size="sm"
+ buttonText="Test Channel"
+ />
+ <p className="text-sm text-muted-foreground">
+ Test this channel to verify the bot can send messages.
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/features/automations/components/actions/SlackActionHandler.ts b/web/src/features/automations/components/actions/SlackActionHandler.ts
new file mode 100644
index 0000000000..3c303a2c63
--- /dev/null
+++ b/web/src/features/automations/components/actions/SlackActionHandler.ts
@@ -0,0 +1,92 @@
+import React from "react";
+import { type UseFormReturn } from "react-hook-form";
+import { type BaseActionHandler } from "./BaseActionHandler";
+import { SlackActionForm } from "./SlackActionForm";
+import {
+ type AutomationDomain,
+ type SlackActionConfig,
+ type ActionCreate,
+ type ActionDomain,
+} from "@langfuse/shared";
+import { z } from "zod/v4";
+
+// Define the form schema for Slack actions
+const SlackActionFormSchema = z.object({
+ slack: z.object({
+ channelId: z.string().min(1, "Channel is required"),
+ channelName: z.string().min(1, "Channel name is required"),
+ messageTemplate: z.string().optional(),
+ }),
+});
+
+type SlackActionFormData = z.infer<typeof SlackActionFormSchema>;
+
+export class SlackActionHandler
+ implements BaseActionHandler<SlackActionFormData>
+{
+ actionType = "SLACK" as const;
+
+ getDefaultValues(automation?: AutomationDomain): SlackActionFormData {
+ if (automation?.action?.type === "SLACK") {
+ const config = automation.action.config as SlackActionConfig;
+ return {
+ slack: {
+ channelId: config.channelId,
+ channelName: config.channelName,
+ messageTemplate: config.messageTemplate || undefined,
+ },
+ };
+ }
+
+ return {
+ slack: {
+ channelId: "",
+ channelName: "",
+ messageTemplate: undefined,
+ },
+ };
+ }
+
+ validateFormData(formData: SlackActionFormData): {
+ isValid: boolean;
+ errors?: string[];
+ } {
+ const errors: string[] = [];
+
+ if (!formData.slack?.channelId) {
+ errors.push("Slack channel is required");
+ }
+
+ if (!formData.slack?.channelName) {
+ errors.push("Channel name is required");
+ }
+
+ return {
+ isValid: errors.length === 0,
+ errors: errors.length > 0 ? errors : undefined,
+ };
+ }
+
+ buildActionConfig(formData: SlackActionFormData): ActionCreate {
+ return {
+ type: "SLACK",
+ channelId: formData.slack?.channelId || "",
+ channelName: formData.slack?.channelName || "",
+ messageTemplate: formData.slack?.messageTemplate || undefined,
+ };
+ }
+
+ renderForm(props: {
+ form: UseFormReturn<SlackActionFormData>;
+ disabled: boolean;
+ projectId: string;
+ action?: ActionDomain;
+ }) {
+ return React.createElement(SlackActionForm, {
+ form: props.form,
+ disabled: props.disabled,
+ projectId: props.projectId,
+ action: props.action,
+ });
+ }
+}
diff --git a/web/src/features/automations/components/actions/WebhookActionForm.tsx b/web/src/features/automations/components/actions/WebhookActionForm.tsx
index 3e4376309d..aeafb28608 100644
--- a/web/src/features/automations/components/actions/WebhookActionForm.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionForm.tsx
@@ -22,6 +22,7 @@ import {
type ActionDomain,
type ActionDomainWithSecrets,
AvailableWebhookApiSchema,
+ type SafeWebhookActionConfig,
WebhookDefaultHeaders,
} from "@langfuse/shared";
import { api } from "@/src/utils/api";
@@ -320,7 +321,9 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
<div className="flex-1">
<CodeView
className="bg-muted/50"
- content={action.config.displaySecretKey}
+ content={
+ (action.config as SafeWebhookActionConfig).displaySecretKey
+ }
defaultCollapsed={false}
/>
</div>
diff --git a/web/src/features/automations/components/actions/index.ts b/web/src/features/automations/components/actions/index.ts
index 3d7199df3a..6d326b41f5 100644
--- a/web/src/features/automations/components/actions/index.ts
+++ b/web/src/features/automations/components/actions/index.ts
@@ -1,3 +1,4 @@
export { type BaseActionHandler } from "./BaseActionHandler";
export { WebhookActionHandler } from "./WebhookActionHandler";
+export { SlackActionHandler } from "./SlackActionHandler";
export { ActionHandlerRegistry } from "./ActionHandlerRegistry";
diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsx
index 0c1842c9db..f15b184629 100644
--- a/web/src/features/automations/components/automationForm.tsx
+++ b/web/src/features/automations/components/automationForm.tsx
@@ -46,6 +46,13 @@ import { ActionHandlerRegistry } from "./actions";
import { webhookSchema } from "./actions/WebhookActionForm";
import { MultiSelect } from "@/src/features/filters/components/multi-select";
+// Define Slack action schema
+const slackSchema = z.object({
+ channelId: z.string().min(1, "Channel is required"),
+ channelName: z.string().min(1, "Channel name is required"),
+ messageTemplate: z.string().optional(),
+});
+
// Define the TriggerEventSource enum directly in this file to match the backend
enum TriggerEventSource {
Prompt = "prompt",
@@ -67,7 +74,10 @@ const formSchema = z.discriminatedUnion("actionType", [
actionType: z.literal("WEBHOOK"),
webhook: webhookSchema,
}),
- // add more action types here
+ baseFormSchema.extend({
+ actionType: z.literal("SLACK"),
+ slack: slackSchema,
+ }),
]);
type FormValues = z.infer<typeof formSchema>;
@@ -116,7 +126,7 @@ export const AutomationForm = ({
// Get the action type for the form when editing
const getActionType = () => {
- if (isEditing && automation?.action?.type) {
+ if (automation?.action?.type) {
return automation.action.type as ActionTypes;
}
return "WEBHOOK";
@@ -128,7 +138,8 @@ export const AutomationForm = ({
const today = new Date().toLocaleString("sv").split("T")[0]; // YYYY-MM-DD
const baseValues = {
- name: isEditing && automation ? automation.name : `Webhook ${today}`,
+ name:
+ isEditing && automation ? automation.name : `${actionType} ${today}`,
eventSource: automation
? automation.trigger.eventSource
: TriggerEventSource.Prompt,
@@ -157,6 +168,20 @@ export const AutomationForm = ({
},
},
};
+ } else if (actionType === "SLACK") {
+ // Use action handler to get default values with proper typing
+ const handler = ActionHandlerRegistry.getHandler("SLACK");
+ const slackDefaults = handler.getDefaultValues(automation);
+ return {
+ ...baseValues,
+ actionType: "SLACK" as const,
+ eventSource: TriggerEventSource.Prompt,
+ slack: {
+ channelId: slackDefaults.slack.channelId || "",
+ channelName: slackDefaults.slack.channelName || "",
+ messageTemplate: slackDefaults.slack.messageTemplate || "",
+ },
+ };
} else {
throw new Error("Invalid action type");
}
@@ -243,15 +268,28 @@ export const AutomationForm = ({
// Update button text based on if we're editing an existing automation
const submitButtonText =
- isEditing && automation ? "Update Webhook" : "Save Webhook";
+ isEditing && automation ? "Update Automation" : "Save Automation";
// Update required fields based on action type
const handleActionTypeChange = (value: ActionTypes) => {
setActiveTab(value.toLowerCase());
form.setValue("actionType", value);
- const handler = ActionHandlerRegistry.getHandler("WEBHOOK");
- const defaultValues = handler.getDefaultValues();
- form.setValue("webhook", defaultValues.webhook);
+
+ if (value === "WEBHOOK") {
+ const handler = ActionHandlerRegistry.getHandler("WEBHOOK");
+ const defaultValues = handler.getDefaultValues();
+ form.setValue("webhook", defaultValues.webhook);
+ } else if (value === "SLACK") {
+ const handler = ActionHandlerRegistry.getHandler("SLACK");
+ const defaultValues = handler.getDefaultValues();
+ form.setValue("slack", defaultValues.slack);
+ }
+
+ // If we are creating a new automation, update the default name
+ if (!automation) {
+ const today = new Date().toLocaleString("sv").split("T")[0];
+ form.setValue("name", `${value} ${today}`);
+ }
};
// Handle cancel button click
@@ -462,7 +500,9 @@ export const AutomationForm = ({
<SelectItem key={actionType} value={actionType}>
{actionType === "WEBHOOK"
? "Webhook"
- : "Annotation Queue"}
+ : actionType === "SLACK"
+ ? "Slack"
+ : "Annotation Queue"}
</SelectItem>
),
)}
diff --git a/web/src/features/automations/components/automations.tsx b/web/src/features/automations/components/automations.tsx
index 5799cec65a..87637300e8 100644
--- a/web/src/features/automations/components/automations.tsx
+++ b/web/src/features/automations/components/automations.tsx
@@ -318,9 +318,9 @@ export default function AutomationsPage() {
<div className="h-full p-6">
<div className="flex h-full items-center justify-center text-muted-foreground">
<div className="text-center">
- <h3 className="text-lg font-medium">Select a webhook</h3>
+ <h3 className="text-lg font-medium">Select an automation</h3>
<p className="mt-2 text-sm">
- Choose a webhook from the sidebar to view its details and
+ Choose an automation from the sidebar to view its details and
execution history.
</p>
</div>
@@ -332,7 +332,7 @@ export default function AutomationsPage() {
return (
<Page
headerProps={{
- title: "Webhooks",
+ title: "Automations",
breadcrumb: [
{
name: "Prompts",
@@ -342,7 +342,7 @@ export default function AutomationsPage() {
actionButtonsRight: (
<Button onClick={handleCreateAutomation}>
<Plus className="mr-2 h-4 w-4" />
- Create Webhook
+ Create Automation
</Button>
),
}}
diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.ts
index dc72902b5f..9f41192bf3 100644
--- a/web/src/features/automations/server/router.ts
+++ b/web/src/features/automations/server/router.ts
@@ -2,12 +2,13 @@ import { createTRPCRouter } from "@/src/server/api/trpc";
import { protectedProjectProcedure } from "@/src/server/api/trpc";
import { z } from "zod/v4";
import {
- type WebhookActionConfigWithSecrets,
ActionCreateSchema,
ActionType,
- ActionTypeSchema,
JobConfigState,
singleFilter,
+ isSafeWebhookActionConfig,
+ isWebhookAction,
+ convertToSafeWebhookConfig,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { v4 } from "uuid";
@@ -19,10 +20,7 @@ import {
logger,
} from "@langfuse/shared/src/server";
import { generateWebhookSecret, encrypt } from "@langfuse/shared/encryption";
-import {
- processWebhookActionConfig,
- convertToSafeWebhookConfig,
-} from "./webhookHelpers";
+import { processWebhookActionConfig } from "./webhookHelpers";
import { TRPCError } from "@trpc/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
@@ -95,6 +93,13 @@ export const automationsRouter = createTRPCRouter({
});
}
+ if (!isSafeWebhookActionConfig(existingAction.config)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: `Invalid webhook configuration for action ${input.actionId}`,
+ });
+ }
+
// Generate new webhook secret
const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =
generateWebhookSecret();
@@ -114,7 +119,7 @@ export const automationsRouter = createTRPCRouter({
// Update action config with new secret
const updatedConfig = {
- ...(existingAction.config as any),
+ ...existingAction.config,
secretKey: encrypt(newSecretKey),
displaySecretKey: newDisplaySecretKey,
};
@@ -248,12 +253,31 @@ export const automationsRouter = createTRPCRouter({
const triggerId = v4();
const actionId = v4();
- // Process webhook action configuration using helper
- const { finalActionConfig, newUnencryptedWebhookSecret } =
- await processWebhookActionConfig({
+ // Build action config depending on action type
+ let finalActionConfig = input.actionConfig;
+ let newUnencryptedWebhookSecret: string | undefined = undefined;
+
+ if (input.actionType === "WEBHOOK") {
+ const webhookResult = await processWebhookActionConfig({
actionConfig: input.actionConfig,
projectId: input.projectId,
});
+ finalActionConfig = webhookResult.finalActionConfig;
+ newUnencryptedWebhookSecret = webhookResult.newUnencryptedWebhookSecret;
+ } else if (input.actionType === "SLACK") {
+ // Validate that Slack integration exists for this project
+ const slackIntegration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!slackIntegration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message:
+ "Slack integration not found. Please connect your Slack workspace first.",
+ });
+ }
+ }
const [trigger, action, automation] = await ctx.prisma.$transaction(
async (tx) => {
@@ -310,9 +334,9 @@ export const automationsRouter = createTRPCRouter({
return {
action: {
...action,
- config: convertToSafeWebhookConfig(
- action.config as WebhookActionConfigWithSecrets,
- ),
+ config: isWebhookAction(action)
+ ? convertToSafeWebhookConfig(action.config)
+ : action.config,
},
trigger,
automation,
@@ -342,12 +366,29 @@ export const automationsRouter = createTRPCRouter({
});
}
- // Process webhook action configuration using helper
- const { finalActionConfig } = await processWebhookActionConfig({
- actionConfig: input.actionConfig,
- actionId: existingAutomation.action.id,
- projectId: input.projectId,
- });
+ let finalActionConfig = input.actionConfig;
+
+ if (input.actionType === "WEBHOOK") {
+ const webhookResult = await processWebhookActionConfig({
+ actionConfig: input.actionConfig,
+ actionId: existingAutomation.action.id,
+ projectId: input.projectId,
+ });
+ finalActionConfig = webhookResult.finalActionConfig;
+ } else if (input.actionType === "SLACK") {
+ // Validate that Slack integration exists for this project
+ const slackIntegration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!slackIntegration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message:
+ "Slack integration not found. Please connect your Slack workspace first.",
+ });
+ }
+ }
const [action, trigger, automation] = await ctx.prisma.$transaction(
async (tx) => {
@@ -419,9 +460,9 @@ export const automationsRouter = createTRPCRouter({
return {
action: {
...action,
- config: convertToSafeWebhookConfig(
- action.config as WebhookActionConfigWithSecrets,
- ),
+ config: isWebhookAction(action)
+ ? convertToSafeWebhookConfig(action.config)
+ : action.config,
},
trigger,
automation,
@@ -496,7 +537,7 @@ export const automationsRouter = createTRPCRouter({
}),
count: protectedProjectProcedure
- .input(z.object({ projectId: z.string(), type: ActionTypeSchema }))
+ .input(z.object({ projectId: z.string() }))
.query(async ({ ctx, input }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -507,7 +548,6 @@ export const automationsRouter = createTRPCRouter({
const count = await ctx.prisma.action.count({
where: {
projectId: input.projectId,
- ...(input.type === "WEBHOOK" && { type: "WEBHOOK" }),
},
});
diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.ts
index bfef83120c..cc6c599741 100644
--- a/web/src/features/automations/server/webhookHelpers.ts
+++ b/web/src/features/automations/server/webhookHelpers.ts
@@ -6,8 +6,9 @@ import {
import {
type ActionCreate,
type ActionConfig,
- type SafeWebhookActionConfig,
type WebhookActionConfigWithSecrets,
+ type WebhookActionCreate,
+ isWebhookActionConfig,
} from "@langfuse/shared";
import {
getActionByIdWithSecrets,
@@ -42,22 +43,32 @@ export async function processWebhookActionConfig({
})) ?? undefined)
: undefined;
+ let existingActionConfig: WebhookActionConfigWithSecrets | undefined;
+ if (existingAction) {
+ if (!isWebhookActionConfig(existingAction.config)) {
+ throw new Error(
+ `Existing action ${actionId} does not have valid webhook configuration`,
+ );
+ }
+ existingActionConfig = existingAction.config;
+ }
+
const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =
generateWebhookSecret();
// Process headers and generate final action config
const finalActionConfig = processWebhookHeaders(
actionConfig,
- existingAction?.config as WebhookActionConfigWithSecrets | undefined,
+ existingActionConfig,
);
return {
finalActionConfig: {
...finalActionConfig,
- secretKey: existingAction?.config.secretKey ?? encrypt(newSecretKey),
+ secretKey: existingActionConfig?.secretKey ?? encrypt(newSecretKey),
displaySecretKey:
- existingAction?.config.displaySecretKey ?? newDisplaySecretKey,
+ existingActionConfig?.displaySecretKey ?? newDisplaySecretKey,
},
- newUnencryptedWebhookSecret: existingAction?.config.secretKey
+ newUnencryptedWebhookSecret: existingActionConfig?.secretKey
? undefined
: newSecretKey,
};
@@ -72,9 +83,9 @@ export async function processWebhookActionConfig({
* 5. Generating display values for secret headers
*/
function processWebhookHeaders(
- actionConfig: ActionCreate,
+ actionConfig: WebhookActionCreate,
existingConfig: WebhookActionConfigWithSecrets | undefined,
-): ActionConfig {
+): WebhookActionConfigWithSecrets {
// Get existing headers for comparison
const existingLegacyHeaders = existingConfig?.headers ?? {}; // legacy headers
const existingRequestHeaders = existingConfig?.requestHeaders ?? {}; // new headers
@@ -166,18 +177,3 @@ export function extractWebhookSecret(
return undefined;
}
}
-
-/**
- * Converts webhook config with secrets to safe config by only including allowed fields
- */
-export function convertToSafeWebhookConfig(
- webhookConfig: WebhookActionConfigWithSecrets,
-): SafeWebhookActionConfig {
- return {
- type: webhookConfig.type,
- url: webhookConfig.url,
- displayHeaders: webhookConfig.displayHeaders,
- apiVersion: webhookConfig.apiVersion,
- displaySecretKey: webhookConfig.displaySecretKey,
- };
-}
diff --git a/web/src/features/slack/README.md b/web/src/features/slack/README.md
new file mode 100644
index 0000000000..011b0808f1
--- /dev/null
+++ b/web/src/features/slack/README.md
@@ -0,0 +1,112 @@
+# Slack Integration Setup Guide
+
+This guide walks you through setting up and testing the Langfuse Slack integration for local development.
+
+## Prerequisites
+
+- Node.js and pnpm installed
+- Access to a Slack workspace where you can create apps
+- macOS (for mkcert installation)
+
+## Setup Steps
+
+### 1. Create a Slack App
+
+1. Go to [Slack API Apps page](https://api.slack.com/apps)
+2. Click "Create New App" β†’ "From an app manifest"
+3. Select your workspace
+4. Copy the contents of `app_manifest.json` from this directory and paste it into the manifest editor
+5. Click "Create" to create your app
+
+### 2. (Optional) Add App Icon
+
+1. In your Slack app settings, go to "Basic Information"
+2. Upload the Langfuse icon from `web/public/icon1024.png` as your app's avatar
+3. This will make your app more recognizable in Slack
+
+### 3. Configure Environment Variables
+
+1. In your Slack app settings, go to "Basic Information"
+2. Copy the **Client ID** and **Client Secret**
+3. Add these to your `.env` file:
+ ```bash
+ SLACK_CLIENT_ID=your_client_id_here
+ SLACK_CLIENT_SECRET=your_client_secret_here
+ ```
+
+### 4. Set Up HTTPS for Local Development
+
+The Slack OAuth flow requires HTTPS. Set up local certificates:
+
+```bash
+# Install mkcert
+brew install mkcert
+
+# Install the local CA
+mkcert -install
+
+# Generate certificates for localhost
+mkcert localhost 127.0.0.1
+
+# Move certificates to web directory
+mv localhost+1*.pem web/
+```
+
+### 5. Start Development Server
+
+From the repository root, run:
+
+```bash
+pnpm run dev:https
+```
+
+This starts the Next.js development server with HTTPS enabled on `https://localhost:3000`.
+
+### 6. Test the Integration
+
+1. Navigate to your Langfuse project settings
+2. Look for the Slack integration section
+3. Click "Connect to Slack" to initiate the OAuth flow
+4. Authorize the app in your Slack workspace
+5. Test sending a message using the "Send Test Message" button
+
+## Troubleshooting
+
+### Common Issues
+
+- **"Invalid redirect URI"**: Ensure your Slack app's OAuth redirect URLs include `https://localhost:3000/api/public/slack/oauth`
+- **Certificate errors**: Make sure you've installed the mkcert CA and moved the certificates to the `web/` directory
+- **Environment variables not found**: Verify your `.env` file is in the correct location and contains the Slack credentials
+
+### SSL Certificate Issues
+
+If you encounter SSL certificate warnings in your browser:
+
+1. Make sure you ran `mkcert -install` to install the local CA
+2. Try accessing `https://localhost:3000` directly and accept the certificate
+3. Restart your development server after certificate changes
+
+## Features
+
+The Slack integration provides:
+
+- **Real-time alerts**: Get notified about critical errors and anomalies
+- **Prompt monitoring**: Receive alerts on prompt edits and creations
+- **Direct links**: Jump from Slack messages directly to prompts in Langfuse
+- **Channel configuration**: Set up different notification channels per project
+- **Test messages**: Verify your integration is working correctly
+
+## Development Notes
+
+- The integration uses Slack's OAuth 2.0 flow for secure authentication
+- Webhook endpoints are available at `/api/public/slack/install`
+- OAuth callback is handled at `/api/public/slack/oauth`
+- All Slack API interactions are handled through the `SlackService` in the shared package
+
+## Production Deployment
+
+For production deployment, ensure:
+
+- Update the OAuth redirect URLs in your Slack app to include your production domain
+- Set up proper SSL certificates for your production environment
+- Configure environment variables in your production environment
diff --git a/web/src/features/slack/app_manifest.json b/web/src/features/slack/app_manifest.json
new file mode 100644
index 0000000000..655185090a
--- /dev/null
+++ b/web/src/features/slack/app_manifest.json
@@ -0,0 +1,31 @@
+{
+ "display_information": {
+ "name": "Langfuse",
+ "description": "Receive real-time alerts and insights from Langfuse directly in Slack. Monitor traces, errors, and performance effortlessly.",
+ "background_color": "#0a60b5",
+ "long_description": "The Langfuse Slack App keeps your team in sync by delivering real-time observability and alerts directly to your Slack channels. Whether you’re monitoring AI traces, catching runtime errors, or tracking latency and performance metrics, Langfuse ensures that you’re always in the loop.\r\n\r\nWith flexible configuration per project, you can:\r\n\tβ€’\tGet notified about critical errors and anomalies\r\n\tβ€’\tReceive alerts on trace completions, slow response times, or quality degradations\r\n\tβ€’\tQuickly jump from a Slack message to the exact trace in Langfuse\r\n\tβ€’\tKeep dev, ops, and ML teams aligned without context switching\r\n\r\nStay on top of your LLM applications β€” without leaving Slack."
+ },
+ "features": {
+ "bot_user": {
+ "display_name": "Langfuse",
+ "always_online": false
+ }
+ },
+ "oauth_config": {
+ "redirect_urls": [
+ "https://localhost:3000/api/public/slack/oauth",
+ "https://cloud.langfuse.com/api/public/slack/oauth",
+ "https://us.cloud.langfuse.com/api/public/slack/oauth",
+ "https://hipaa.cloud.langfuse.com/api/public/slack/oauth",
+ "https://staging.langfuse.com/api/public/slack/oauth"
+ ],
+ "scopes": {
+ "bot": ["channels:read", "chat:write", "chat:write.public"]
+ }
+ },
+ "settings": {
+ "org_deploy_enabled": false,
+ "socket_mode_enabled": false,
+ "token_rotation_enabled": false
+ }
+}
diff --git a/web/src/features/slack/components/ChannelSelector.tsx b/web/src/features/slack/components/ChannelSelector.tsx
new file mode 100644
index 0000000000..33143c2c7f
--- /dev/null
+++ b/web/src/features/slack/components/ChannelSelector.tsx
@@ -0,0 +1,295 @@
+import React, { useState, useMemo } from "react";
+import { RefreshCw, Search, Hash, Lock } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+
+import { Select, SelectTrigger, SelectValue } from "@/src/components/ui/select";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/src/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { api } from "@/src/utils/api";
+
+/**
+ * Represents a Slack channel
+ */
+export interface SlackChannel {
+ id: string;
+ name: string;
+ isPrivate: boolean;
+ isMember: boolean;
+}
+
+/**
+ * Props for the ChannelSelector component
+ */
+interface ChannelSelectorProps {
+ /** Project ID for the Slack integration */
+ projectId: string;
+ /** Currently selected channel ID */
+ selectedChannelId?: string;
+ /** Callback when a channel is selected */
+ onChannelSelect: (channel: SlackChannel) => void;
+ /** Whether the component is disabled */
+ disabled?: boolean;
+ /** Placeholder text for the selector */
+ placeholder?: string;
+ /** Whether to show only channels the bot is a member of */
+ memberOnly?: boolean;
+ /** Custom filter function for channels */
+ filterChannels?: (channel: SlackChannel) => boolean;
+ /** Whether to show the refresh button */
+ showRefreshButton?: boolean;
+}
+
+/**
+ * A dropdown component for selecting Slack channels with search and filtering capabilities.
+ *
+ * This component handles:
+ * - Fetching available channels from the Slack API
+ * - Providing search functionality to filter channels
+ * - Displaying channel type indicators (public/private)
+ * - Showing membership status for each channel
+ * - Handling loading and error states
+ * - Refreshing the channel list
+ *
+ * The component uses a command palette style interface for better UX when dealing with
+ * many channels. It supports both keyboard navigation and mouse interaction.
+ *
+ * @param projectId - The project ID for the Slack integration
+ * @param selectedChannelId - Currently selected channel ID
+ * @param onChannelSelect - Callback when a channel is selected
+ * @param disabled - Whether the component should be disabled
+ * @param placeholder - Placeholder text for the selector
+ * @param memberOnly - Whether to show only channels the bot is a member of
+ * @param filterChannels - Custom filter function for channels
+ * @param showRefreshButton - Whether to show the refresh button
+ */
+export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
+ projectId,
+ selectedChannelId,
+ onChannelSelect,
+ disabled = false,
+ placeholder = "Select a channel",
+ memberOnly = false,
+ filterChannels,
+ showRefreshButton = true,
+}) => {
+ const [open, setOpen] = useState(false);
+ const [searchValue, setSearchValue] = useState("");
+ const [isRefreshing, setIsRefreshing] = useState(false);
+
+ // Get available channels
+ const {
+ data: channelsData,
+ isLoading,
+ error,
+ refetch: refetchChannels,
+ } = api.slack.getChannels.useQuery(
+ { projectId },
+ {
+ enabled: !!projectId,
+ // Keep data fresh
+ staleTime: 5 * 60 * 1000, // 5 minutes
+ },
+ );
+
+ // Handle refresh
+ const handleRefresh = async () => {
+ setIsRefreshing(true);
+ try {
+ await refetchChannels();
+ } finally {
+ setIsRefreshing(false);
+ }
+ };
+
+ // Filter and search channels
+ const filteredChannels = useMemo(() => {
+ if (!channelsData?.channels) return [];
+
+ let channels = channelsData.channels;
+
+ // Apply member filter if requested
+ if (memberOnly) {
+ channels = channels.filter((channel) => channel.isMember);
+ }
+
+ // Apply custom filter if provided
+ if (filterChannels) {
+ channels = channels.filter(filterChannels);
+ }
+
+ // Apply search filter
+ if (searchValue.trim()) {
+ const searchTerm = searchValue.toLowerCase().trim();
+ channels = channels.filter((channel) =>
+ channel.name.toLowerCase().includes(searchTerm),
+ );
+ }
+
+ // Sort channels: public channels first, then private, then by name
+ return channels.sort((a, b) => {
+ if (a.isPrivate !== b.isPrivate) {
+ return a.isPrivate ? 1 : -1;
+ }
+ return a.name.localeCompare(b.name);
+ });
+ }, [channelsData?.channels, memberOnly, filterChannels, searchValue]);
+
+ // Get selected channel info
+ const selectedChannel = useMemo(() => {
+ if (!selectedChannelId || !channelsData?.channels) return null;
+ return channelsData.channels.find(
+ (channel) => channel.id === selectedChannelId,
+ );
+ }, [selectedChannelId, channelsData?.channels]);
+
+ // Handle channel selection
+ const handleChannelSelect = (channel: SlackChannel) => {
+ onChannelSelect(channel);
+ setOpen(false);
+ setSearchValue("");
+ };
+
+ // Render channel item
+ const renderChannelItem = (channel: SlackChannel) => (
+ <div className="flex w-full items-center gap-2">
+ {channel.isPrivate ? (
+ <Lock className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <Hash className="h-4 w-4 text-muted-foreground" />
+ )}
+ <span className="flex-1 truncate">{channel.name}</span>
+ </div>
+ );
+
+ // Handle loading state
+ if (isLoading) {
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Select disabled>
+ <SelectTrigger>
+ <SelectValue placeholder="Loading channels..." />
+ </SelectTrigger>
+ </Select>
+ {showRefreshButton && (
+ <Button variant="outline" size="sm" disabled>
+ <RefreshCw className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // Handle error state
+ if (error) {
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Select disabled>
+ <SelectTrigger>
+ <SelectValue placeholder="Error loading channels" />
+ </SelectTrigger>
+ </Select>
+ {showRefreshButton && (
+ <Button variant="outline" size="sm" onClick={handleRefresh}>
+ <RefreshCw className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ <Alert>
+ <AlertDescription>
+ Failed to load channels. Please check your Slack connection and try
+ again.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="w-full justify-between"
+ disabled={disabled}
+ >
+ {selectedChannel ? (
+ renderChannelItem(selectedChannel)
+ ) : (
+ <span className="text-muted-foreground">{placeholder}</span>
+ )}
+ <Search className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0" align="start">
+ <Command>
+ <CommandInput
+ placeholder="Search channels..."
+ value={searchValue}
+ onValueChange={setSearchValue}
+ />
+ <CommandList>
+ <CommandEmpty>
+ {searchValue
+ ? "No channels match your search."
+ : "No channels available."}
+ </CommandEmpty>
+ <CommandGroup>
+ {filteredChannels.map((channel) => (
+ <CommandItem
+ key={channel.id}
+ value={channel.id}
+ onSelect={() => handleChannelSelect(channel)}
+ className="cursor-pointer"
+ >
+ {renderChannelItem(channel)}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+
+ {showRefreshButton && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleRefresh}
+ disabled={disabled || isRefreshing}
+ >
+ <RefreshCw
+ className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`}
+ />
+ </Button>
+ )}
+ </div>
+
+ {/* Channel stats */}
+ {channelsData?.channels && (
+ <div className="text-xs text-muted-foreground">
+ {filteredChannels.length} of {channelsData.channels.length} channels
+ {memberOnly && " (member only)"}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/features/slack/components/SlackConnectButton.tsx b/web/src/features/slack/components/SlackConnectButton.tsx
new file mode 100644
index 0000000000..8d13a44eae
--- /dev/null
+++ b/web/src/features/slack/components/SlackConnectButton.tsx
@@ -0,0 +1,190 @@
+import React, { useState, useEffect, useRef } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Slack } from "lucide-react";
+import { api } from "@/src/utils/api";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+
+/**
+ * Props for the SlackConnectButton component
+ */
+interface SlackConnectButtonProps {
+ /** Project ID for the Slack integration */
+ projectId: string;
+ /** Whether the button should be disabled */
+ disabled?: boolean;
+ /** Button variant */
+ variant?: "default" | "outline" | "ghost" | "secondary";
+ /** Button size */
+ size?: "default" | "sm" | "lg";
+ /** Custom button text */
+ buttonText?: string;
+ /** Callback when connection is successful */
+ onSuccess?: () => void;
+ /** Callback when connection fails */
+ onError?: (error: Error) => void;
+ /** Whether to show the button text */
+ showText?: boolean;
+}
+
+/**
+ * Simplified Slack Connect Button
+ *
+ * Uses direct navigation to OAuth URL instead of complex popup handling.
+ * The SlackService handles the OAuth flow and redirects back to the correct page.
+ */
+export const SlackConnectButton: React.FC<SlackConnectButtonProps> = ({
+ projectId,
+ disabled = false,
+ variant = "default",
+ size = "default",
+ buttonText = "Connect Slack",
+ onSuccess,
+ onError,
+ showText = true,
+}) => {
+ const [isConnecting, setIsConnecting] = useState(false);
+ const popupRef = useRef<Window | null>(null);
+ const intervalRef = useRef<NodeJS.Timeout | null>(null);
+ const messageHandlerRef = useRef<((event: MessageEvent) => void) | null>(
+ null,
+ );
+
+ // Get integration status
+ const { data: integrationStatus } = api.slack.getIntegrationStatus.useQuery(
+ { projectId },
+ { enabled: !!projectId },
+ );
+
+ // Cleanup effect for component unmount
+ useEffect(() => {
+ return () => {
+ // Clean up popup if it's still open
+ if (popupRef.current && !popupRef.current.closed) {
+ popupRef.current.close();
+ }
+
+ // Clean up interval
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ }
+
+ // Clean up event listener
+ if (messageHandlerRef.current) {
+ window.removeEventListener("message", messageHandlerRef.current);
+ }
+ };
+ }, []);
+
+ // Handle connect button click
+ const handleConnect = async () => {
+ if (!integrationStatus?.installUrl) {
+ const errorMessage = "Install URL not available. Please try again.";
+ onError?.(new Error(errorMessage));
+ showErrorToast("Connection Failed", errorMessage);
+ return;
+ }
+
+ setIsConnecting(true);
+
+ try {
+ // Open OAuth flow in popup window
+ const popup = window.open(
+ integrationStatus.installUrl,
+ "slack-oauth",
+ "width=600,height=700,scrollbars=yes,resizable=yes",
+ );
+
+ if (!popup) {
+ throw new Error("Popup blocked. Please allow popups and try again.");
+ }
+
+ // Store popup reference
+ popupRef.current = popup;
+
+ // Listen for messages from popup
+ const handleMessage = (event: MessageEvent) => {
+ // Verify origin for security
+ if (event.origin !== window.location.origin) {
+ return;
+ }
+
+ if (event.data.type === "slack-oauth-success") {
+ popup.close();
+ setIsConnecting(false);
+
+ showSuccessToast({
+ title: "Slack Connected",
+ description: `Successfully connected to ${event.data.teamName}.`,
+ });
+
+ onSuccess?.();
+
+ // Clean up event listener and interval
+ window.removeEventListener("message", handleMessage);
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ } else if (event.data.type === "slack-oauth-error") {
+ popup.close();
+ setIsConnecting(false);
+
+ showErrorToast("Connection Failed", event.data.error);
+ onError?.(new Error(event.data.error));
+
+ // Clean up event listener and interval
+ window.removeEventListener("message", handleMessage);
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ }
+ };
+
+ // Store message handler reference
+ messageHandlerRef.current = handleMessage;
+
+ // Add message listener
+ window.addEventListener("message", handleMessage);
+
+ // Also listen for popup being closed manually
+ const checkClosed = setInterval(() => {
+ if (popup.closed) {
+ setIsConnecting(false);
+ window.removeEventListener("message", handleMessage);
+ clearInterval(checkClosed);
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ intervalRef.current = null;
+ }
+ }, 1000);
+
+ // Store interval reference
+ intervalRef.current = checkClosed;
+ } catch (error) {
+ setIsConnecting(false);
+ const errorMessage =
+ error instanceof Error ? error.message : "Failed to connect to Slack";
+ onError?.(new Error(errorMessage));
+ showErrorToast("Connection Failed", errorMessage);
+ }
+ };
+
+ return (
+ <Button
+ onClick={handleConnect}
+ disabled={disabled || isConnecting || !integrationStatus?.installUrl}
+ variant={variant}
+ size={size}
+ className="flex items-center gap-2"
+ >
+ <Slack className="h-4 w-4" />
+ {showText && <span>{isConnecting ? "Connecting..." : buttonText}</span>}
+ </Button>
+ );
+};
diff --git a/web/src/features/slack/components/SlackConnectionCard.tsx b/web/src/features/slack/components/SlackConnectionCard.tsx
new file mode 100644
index 0000000000..90006a2bd6
--- /dev/null
+++ b/web/src/features/slack/components/SlackConnectionCard.tsx
@@ -0,0 +1,223 @@
+import React from "react";
+import { CheckCircle, AlertCircle } from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/src/components/ui/card";
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { api } from "@/src/utils/api";
+import { SlackConnectButton } from "@/src/features/slack/components/SlackConnectButton";
+import { SlackDisconnectButton } from "@/src/features/slack/components/SlackDisconnectButton";
+
+/**
+ * Props for the SlackConnectionCard component
+ */
+interface SlackConnectionCardProps {
+ /** Project ID for the Slack integration */
+ projectId: string;
+ /** Whether the component is disabled */
+ disabled?: boolean;
+ /** Optional callback when connection status changes */
+ onConnectionChange?: (connected: boolean) => void;
+ /** Whether to show the connect button in the card */
+ showConnectButton?: boolean;
+}
+
+/**
+ * A reusable card component that displays Slack connection status and management controls.
+ *
+ * This component handles:
+ * - Displaying current connection status
+ * - Showing team information when connected
+ * - Providing connection and disconnection actions
+ * - Handling error states with appropriate messaging
+ *
+ * The component automatically fetches the integration status and updates when the connection changes.
+ *
+ * @param projectId - The project ID for the Slack integration
+ * @param disabled - Whether the component should be disabled
+ * @param onConnectionChange - Optional callback when connection status changes
+ * @param showConnectButton - Whether to show the connect button in the card (default: true)
+ */
+export const SlackConnectionCard: React.FC<SlackConnectionCardProps> = ({
+ projectId,
+ disabled = false,
+ onConnectionChange,
+ showConnectButton = true,
+}) => {
+ // Get Slack integration status
+ const {
+ data: integrationStatus,
+ isLoading,
+ refetch: refetchStatus,
+ error: statusError,
+ } = api.slack.getIntegrationStatus.useQuery(
+ { projectId },
+ {
+ enabled: !!projectId,
+ // Refetch every 30 seconds to keep status up to date
+ refetchInterval: 30000,
+ },
+ );
+
+ // Handle connection status change
+ const handleConnectionChange = (connected: boolean) => {
+ refetchStatus();
+ onConnectionChange?.(connected);
+ };
+
+ // Handle loading state
+ if (isLoading) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Slack Connection
+ </CardTitle>
+ <CardDescription>Checking connection status...</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-center gap-2 text-muted-foreground">
+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
+ <span>Loading...</span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ // Handle error state
+ if (statusError) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Slack Connection
+ </CardTitle>
+ <CardDescription>Error loading connection status</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>
+ Failed to load Slack integration status. Please try again.
+ </AlertDescription>
+ </Alert>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ // Handle not connected state
+ if (!integrationStatus?.isConnected) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Slack Connection
+ </CardTitle>
+ <CardDescription>
+ Connect your Slack workspace to send notifications
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {integrationStatus?.error && (
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>{integrationStatus.error}</AlertDescription>
+ </Alert>
+ )}
+
+ <div className="space-y-2">
+ <p className="text-sm text-muted-foreground">
+ Connect your Slack workspace to enable real-time notifications for
+ your automations.
+ </p>
+
+ {showConnectButton && (
+ <SlackConnectButton
+ projectId={projectId}
+ disabled={disabled}
+ onSuccess={() => handleConnectionChange(true)}
+ onError={(error: Error) => {
+ console.error("Slack connection error:", error);
+ }}
+ />
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ // Handle connected state
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Slack Connection
+ </CardTitle>
+ <CardDescription>Connected to your Slack workspace</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {/* Connection Status */}
+ <div className="flex items-center gap-2">
+ <CheckCircle className="h-4 w-4 text-green-500" />
+ <span className="text-sm font-medium">Connected</span>
+ </div>
+
+ {/* Team Information */}
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Workspace:</span>
+ <Badge variant="secondary" className="text-xs">
+ {integrationStatus.teamName}
+ </Badge>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Team ID:</span>
+ <Badge variant="outline" className="font-mono text-xs">
+ {integrationStatus.teamId}
+ </Badge>
+ </div>
+
+ {integrationStatus.botUserId && (
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">Bot User:</span>
+ <Badge variant="outline" className="font-mono text-xs">
+ {integrationStatus.botUserId}
+ </Badge>
+ </div>
+ )}
+ </div>
+
+ {/* Management Actions */}
+ <div className="flex gap-2 pt-2">
+ <SlackDisconnectButton
+ projectId={projectId}
+ disabled={disabled}
+ onSuccess={() => handleConnectionChange(false)}
+ onError={(error: Error) => {
+ console.error("Slack disconnection error:", error);
+ }}
+ />
+
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => refetchStatus()}
+ disabled={disabled}
+ >
+ Refresh Status
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/web/src/features/slack/components/SlackDisconnectButton.tsx b/web/src/features/slack/components/SlackDisconnectButton.tsx
new file mode 100644
index 0000000000..5d2ded9c63
--- /dev/null
+++ b/web/src/features/slack/components/SlackDisconnectButton.tsx
@@ -0,0 +1,228 @@
+import React, { useState } from "react";
+import { Unlink, AlertTriangle, Loader2 } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { api } from "@/src/utils/api";
+
+/**
+ * Props for the SlackDisconnectButton component
+ */
+interface SlackDisconnectButtonProps {
+ /** Project ID for the Slack integration */
+ projectId: string;
+ /** Whether the button is disabled */
+ disabled?: boolean;
+ /** Button variant */
+ variant?:
+ | "default"
+ | "outline"
+ | "secondary"
+ | "destructive"
+ | "ghost"
+ | "link";
+ /** Button size */
+ size?: "default" | "sm" | "lg" | "icon";
+ /** Custom button text */
+ buttonText?: string;
+ /** Callback when disconnection is successful */
+ onSuccess?: () => void;
+ /** Callback when disconnection fails */
+ onError?: (error: Error) => void;
+ /** Whether to show confirmation dialog */
+ showConfirmation?: boolean;
+ /** Whether to show the button text */
+ showText?: boolean;
+}
+
+/**
+ * A button component that handles disconnecting the Slack integration.
+ *
+ * This component handles:
+ * - Showing a confirmation dialog before disconnecting
+ * - Calling the disconnect API endpoint
+ * - Providing loading states during the disconnection process
+ * - Displaying appropriate success/error messages
+ * - Calling success/error callbacks
+ *
+ * The component includes safety measures to prevent accidental disconnection:
+ * - Confirmation dialog with clear warning about consequences
+ * - Information about what happens when disconnecting
+ * - Option to cancel the operation
+ *
+ * @param projectId - The project ID for the Slack integration
+ * @param disabled - Whether the button should be disabled
+ * @param variant - Button variant (default: "destructive")
+ * @param size - Button size (default: "sm")
+ * @param buttonText - Custom button text (default: "Disconnect")
+ * @param onSuccess - Callback when disconnection is successful
+ * @param onError - Callback when disconnection fails
+ * @param showConfirmation - Whether to show confirmation dialog (default: true)
+ * @param showText - Whether to show the button text (default: true)
+ */
+export const SlackDisconnectButton: React.FC<SlackDisconnectButtonProps> = ({
+ projectId,
+ disabled = false,
+ variant = "destructive",
+ size = "sm",
+ buttonText = "Disconnect",
+ onSuccess,
+ onError,
+ showConfirmation = true,
+ showText = true,
+}) => {
+ const [isDisconnecting, setIsDisconnecting] = useState(false);
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+
+ // Disconnect mutation
+ const disconnectMutation = api.slack.disconnect.useMutation({
+ onSuccess: () => {
+ setIsDisconnecting(false);
+ setIsDialogOpen(false);
+
+ showSuccessToast({
+ title: "Slack Disconnected",
+ description: "Successfully disconnected from your Slack workspace.",
+ });
+
+ onSuccess?.();
+ },
+ onError: (error: any) => {
+ setIsDisconnecting(false);
+
+ const errorMessage = error.message || "Failed to disconnect from Slack";
+
+ showErrorToast("Disconnection Failed", errorMessage);
+
+ onError?.(new Error(errorMessage));
+ },
+ });
+
+ // Handle disconnect action
+ const handleDisconnect = async () => {
+ if (isDisconnecting) return;
+
+ setIsDisconnecting(true);
+
+ try {
+ await disconnectMutation.mutateAsync({ projectId });
+ } catch (error) {
+ // Error handling is done in the mutation callbacks
+ console.error("Disconnect error:", error);
+ }
+ };
+
+ // Handle button click
+ const handleClick = () => {
+ if (showConfirmation) {
+ setIsDialogOpen(true);
+ } else {
+ handleDisconnect();
+ }
+ };
+
+ const buttonContent = (
+ <>
+ {isDisconnecting ? (
+ <Loader2
+ className={
+ showText ? "mr-2 h-4 w-4 animate-spin" : "h-4 w-4 animate-spin"
+ }
+ />
+ ) : (
+ <Unlink className={showText ? "mr-2 h-4 w-4" : "h-4 w-4"} />
+ )}
+ {showText && (isDisconnecting ? "Disconnecting..." : buttonText)}
+ </>
+ );
+
+ if (showConfirmation) {
+ return (
+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant={variant}
+ size={size}
+ onClick={handleClick}
+ disabled={disabled || isDisconnecting}
+ >
+ {buttonContent}
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <AlertTriangle className="h-5 w-5 text-destructive" />
+ Disconnect Slack Integration
+ </DialogTitle>
+ <DialogDescription className="space-y-2">
+ <p>
+ Are you sure you want to disconnect your Slack workspace from
+ this project?
+ </p>
+ <div className="space-y-2 rounded-md bg-muted p-3">
+ <p className="text-sm font-medium">This will:</p>
+ <ul className="ml-4 space-y-1 text-sm">
+ <li>β€’ Remove the bot from your Slack workspace</li>
+ <li>β€’ Disable all existing Slack automations</li>
+ <li>β€’ Stop all future Slack notifications</li>
+ <li>β€’ Delete stored workspace credentials</li>
+ </ul>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ You can reconnect at any time, but you&apos;ll need to
+ reconfigure your automations.
+ </p>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => setIsDialogOpen(false)}
+ disabled={isDisconnecting}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleDisconnect}
+ disabled={isDisconnecting}
+ >
+ {isDisconnecting ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Disconnecting...
+ </>
+ ) : (
+ <>
+ <Unlink className="mr-2 h-4 w-4" />
+ Disconnect
+ </>
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+ }
+
+ return (
+ <Button
+ variant={variant}
+ size={size}
+ onClick={handleClick}
+ disabled={disabled || isDisconnecting}
+ >
+ {buttonContent}
+ </Button>
+ );
+};
diff --git a/web/src/features/slack/components/SlackTestMessageButton.tsx b/web/src/features/slack/components/SlackTestMessageButton.tsx
new file mode 100644
index 0000000000..513d5d3b69
--- /dev/null
+++ b/web/src/features/slack/components/SlackTestMessageButton.tsx
@@ -0,0 +1,108 @@
+import React from "react";
+import { Button } from "@/src/components/ui/button";
+import { Zap } from "lucide-react";
+import { api } from "@/src/utils/api";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { type SlackChannel } from "./ChannelSelector";
+
+/**
+ * Props for the SlackTestMessageButton component
+ */
+interface SlackTestMessageButtonProps {
+ /** Project ID for the Slack integration */
+ projectId: string;
+ /** Selected channel to send test message to */
+ selectedChannel: SlackChannel | null;
+ /** Whether the button should be disabled */
+ disabled?: boolean;
+ /** Button variant */
+ variant?: "default" | "outline" | "ghost" | "secondary";
+ /** Button size */
+ size?: "default" | "sm" | "lg";
+ /** Custom button text */
+ buttonText?: string;
+ /** Callback when test message is sent successfully */
+ onSuccess?: () => void;
+ /** Callback when test message fails */
+ onError?: (error: Error) => void;
+ /** Whether to show the button text */
+ showText?: boolean;
+ /** Whether the user has access to send test messages */
+ hasAccess?: boolean;
+}
+
+/**
+ * Reusable Slack Test Message Button
+ *
+ * Sends a test message to the selected Slack channel to verify the integration
+ * is working properly. Includes proper loading states and error handling.
+ */
+export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
+ projectId,
+ selectedChannel,
+ disabled = false,
+ variant = "default",
+ size = "default",
+ buttonText = "Send Test Message",
+ onSuccess,
+ onError,
+ showText = true,
+ hasAccess = true,
+}) => {
+ // Test message mutation
+ const testMessageMutation = api.slack.sendTestMessage.useMutation({
+ onSuccess: () => {
+ showSuccessToast({
+ title: "Test Message Sent",
+ description: "Test message sent successfully to the selected channel.",
+ });
+ onSuccess?.();
+ },
+ onError: (error) => {
+ showErrorToast("Failed to Send Test Message", error.message);
+ onError?.(new Error(error.message));
+ },
+ });
+
+ // Handle test message
+ const handleTestMessage = async () => {
+ if (!selectedChannel) return;
+
+ try {
+ await testMessageMutation.mutateAsync({
+ projectId,
+ channelId: selectedChannel.id,
+ channelName: selectedChannel.name,
+ });
+ } catch (error) {
+ // Error handling is done in the mutation
+ }
+ };
+
+ // Determine if button should be disabled
+ const isDisabled =
+ disabled || !hasAccess || testMessageMutation.isLoading || !selectedChannel;
+
+ return (
+ <Button
+ onClick={handleTestMessage}
+ disabled={isDisabled}
+ variant={variant}
+ size={size}
+ className="flex items-center gap-2"
+ >
+ {testMessageMutation.isLoading ? (
+ <>
+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
+ {showText && <span>Sending...</span>}
+ </>
+ ) : (
+ <>
+ <Zap className="h-4 w-4" />
+ {showText && <span>{buttonText}</span>}
+ </>
+ )}
+ </Button>
+ );
+};
diff --git a/web/src/features/slack/server/oauth-handlers.ts b/web/src/features/slack/server/oauth-handlers.ts
new file mode 100644
index 0000000000..ca8c72fbf4
--- /dev/null
+++ b/web/src/features/slack/server/oauth-handlers.ts
@@ -0,0 +1,77 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import {
+ SlackService,
+ parseSlackInstallationMetadata,
+} from "@langfuse/shared/src/server";
+import { logger } from "@langfuse/shared/src/server";
+
+/**
+ * SlackOAuthHandlers
+ *
+ * Handles Next.js-specific OAuth flow for Slack integration.
+ * Uses the configured InstallProvider from SlackService to avoid duplication.
+ */
+/**
+ * Handle OAuth install path using the shared InstallProvider
+ */
+export async function handleInstallPath(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ projectId: string,
+) {
+ try {
+ // Use InstallProvider's handleInstallPath method to render the installation page
+ // This method will:
+ // 1. Generate the OAuth URL with proper state parameter
+ // 2. Set session cookies for state validation
+ // 3. Render the installation page with "Add to Slack" button
+ return await SlackService.getInstance()
+ .getInstaller()
+ .handleInstallPath(req, res, undefined, {
+ scopes: ["channels:read", "chat:write", "chat:write.public"],
+ metadata: JSON.stringify({ projectId: projectId }),
+ });
+ } catch (error) {
+ logger.error("Install path handler failed", { error, projectId });
+ throw error;
+ }
+}
+
+/**
+ * Handle OAuth callback using the shared InstallProvider
+ */
+export async function handleCallback(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ try {
+ return await SlackService.getInstance()
+ .getInstaller()
+ .handleCallback(req, res, {
+ success: async (installation) => {
+ const metadata = parseSlackInstallationMetadata(
+ installation?.metadata,
+ );
+ const projectId = metadata.projectId;
+
+ logger.info("OAuth callback successful", {
+ projectId,
+ teamId: installation.team?.id,
+ teamName: installation.team?.name,
+ });
+
+ // Redirect to project-specific Slack settings page
+ const redirectUrl = `/project/${projectId}/settings/integrations/slack?success=true&team_name=${encodeURIComponent(installation.team?.name || "")}`;
+ res.redirect(redirectUrl);
+ },
+
+ failure: async (error) => {
+ logger.error("OAuth callback failed", { error: error.message });
+ throw error;
+ },
+ });
+ } catch (error) {
+ logger.error("OAuth callback handler failed", { error });
+ throw error;
+ }
+}
diff --git a/web/src/features/slack/server/router.ts b/web/src/features/slack/server/router.ts
new file mode 100644
index 0000000000..70d7dca709
--- /dev/null
+++ b/web/src/features/slack/server/router.ts
@@ -0,0 +1,330 @@
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { z } from "zod/v4";
+import { SlackService } from "@langfuse/shared/src/server";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { logger } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+
+export const slackRouter = createTRPCRouter({
+ /**
+ * Get Slack integration status for a project
+ */
+ getIntegrationStatus: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "automations:read",
+ });
+
+ const integration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!integration) {
+ return {
+ isConnected: false,
+ teamId: null,
+ teamName: null,
+ installUrl: `/api/public/slack/install?projectId=${input.projectId}`,
+ };
+ }
+
+ try {
+ const slackService = SlackService.getInstance();
+ const client = await slackService.getWebClientForProject(
+ input.projectId,
+ );
+ const isValid = await slackService.validateClient(client);
+
+ if (!isValid) {
+ logger.warn("Invalid Slack integration found", {
+ projectId: input.projectId,
+ teamId: integration.teamId,
+ });
+
+ return {
+ isConnected: false,
+ teamId: integration.teamId,
+ teamName: integration.teamName,
+ installUrl: `/api/public/slack/install?projectId=${input.projectId}`,
+ error:
+ "Integration is invalid. Please reconnect your Slack workspace.",
+ };
+ }
+
+ return {
+ isConnected: true,
+ teamId: integration.teamId,
+ teamName: integration.teamName,
+ botUserId: integration.botUserId,
+ installUrl: null,
+ };
+ } catch (error) {
+ logger.warn("Failed to validate Slack integration", {
+ projectId: input.projectId,
+ teamId: integration.teamId,
+ error,
+ });
+
+ return {
+ isConnected: false,
+ teamId: integration.teamId,
+ teamName: integration.teamName,
+ installUrl: `/api/public/slack/install?projectId=${input.projectId}`,
+ error:
+ "Failed to validate integration. Please reconnect your Slack workspace.",
+ };
+ }
+ }),
+
+ /**
+ * Get channels for a project's Slack integration
+ */
+ getChannels: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "automations:read",
+ });
+
+ const integration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Slack integration not found for this project",
+ });
+ }
+
+ try {
+ const slackService = SlackService.getInstance();
+ const client = await slackService.getWebClientForProject(
+ input.projectId,
+ );
+ const channels = await slackService.getChannels(client);
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "slackIntegration",
+ resourceId: integration.id,
+ action: "read",
+ after: { action: "channels_fetched", channelCount: channels.length },
+ });
+
+ return {
+ channels,
+ teamId: integration.teamId,
+ teamName: integration.teamName,
+ };
+ } catch (error) {
+ logger.error("Failed to fetch channels", {
+ error,
+ projectId: input.projectId,
+ });
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Failed to fetch channels. Please check your Slack connection and try again.",
+ });
+ }
+ }),
+
+ /**
+ * Disconnect Slack integration for a project
+ */
+ disconnect: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "automations:CUD",
+ });
+
+ const integration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Slack integration not found for this project",
+ });
+ }
+
+ try {
+ await SlackService.getInstance().deleteIntegration(input.projectId);
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "slackIntegration",
+ resourceId: integration.id,
+ action: "delete",
+ before: integration,
+ });
+
+ logger.info("Slack integration disconnected", {
+ projectId: input.projectId,
+ teamId: integration.teamId,
+ });
+
+ return { success: true };
+ } catch (error) {
+ logger.error("Failed to disconnect Slack integration", {
+ error,
+ projectId: input.projectId,
+ });
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Failed to disconnect Slack integration. Please try again.",
+ });
+ }
+ }),
+
+ /**
+ * Send a test message to a Slack channel
+ */
+ sendTestMessage: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ channelId: z.string(),
+ channelName: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "automations:CUD",
+ });
+
+ const integration = await ctx.prisma.slackIntegration.findUnique({
+ where: { projectId: input.projectId },
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Slack integration not found for this project",
+ });
+ }
+
+ try {
+ const client = await SlackService.getInstance().getWebClientForProject(
+ input.projectId,
+ );
+
+ const testBlocks = [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "πŸŽ‰ Test Message from Langfuse",
+ emoji: true,
+ },
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "Hello from Langfuse! This is a test message to verify your Slack integration is working properly.",
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Project:*\n${input.projectId}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Channel:*\n#${input.channelName}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*User:*\n${ctx.session.user.name || ctx.session.user.email}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toISOString()}`,
+ },
+ ],
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "Open Langfuse",
+ emoji: true,
+ },
+ url: `${process.env.NEXTAUTH_URL}/project/${input.projectId}`,
+ style: "primary",
+ },
+ ],
+ },
+ ];
+
+ const result = await SlackService.getInstance().sendMessage({
+ client,
+ channelId: input.channelId,
+ blocks: testBlocks,
+ text: "Test message from Langfuse",
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "slackIntegration",
+ resourceId: integration.id,
+ action: "create",
+ after: {
+ action: "test_message_sent",
+ channelId: input.channelId,
+ channelName: input.channelName,
+ messageTs: result.messageTs,
+ },
+ });
+
+ logger.info("Test message sent successfully", {
+ projectId: input.projectId,
+ channelId: input.channelId,
+ channelName: input.channelName,
+ messageTs: result.messageTs,
+ });
+
+ return {
+ success: true,
+ messageTs: result.messageTs,
+ channel: result.channel,
+ };
+ } catch (error) {
+ logger.error("Failed to send test message", {
+ error,
+ projectId: input.projectId,
+ channelId: input.channelId,
+ });
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Failed to send test message. Please check your Slack connection and channel permissions.",
+ });
+ }
+ }),
+});
diff --git a/web/src/pages/api/public/slack/install/index.ts b/web/src/pages/api/public/slack/install/index.ts
new file mode 100644
index 0000000000..dab9712028
--- /dev/null
+++ b/web/src/pages/api/public/slack/install/index.ts
@@ -0,0 +1,41 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { handleInstallPath } from "@/src/features/slack/server/oauth-handlers";
+import { logger } from "@langfuse/shared/src/server";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ try {
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "GET") {
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ // Extract projectId from query parameters
+ const projectId = req.query.projectId as string;
+
+ if (!projectId) {
+ return res.status(400).json({ error: "Missing projectId parameter" });
+ }
+
+ logger.info("Slack install request received", { projectId });
+
+ // Let SlackOAuthHandlers handle the installation page rendering
+ // This includes:
+ // - Generating the OAuth URL with proper state
+ // - Setting session cookies for state validation
+ // - Rendering the installation page
+ return await handleInstallPath(req, res, projectId);
+ } catch (error) {
+ logger.error("Install handler failed", { error });
+
+ // Fallback response for unexpected errors
+ return res.status(500).json({
+ error: "Internal server error",
+ message: "Failed to handle Slack installation request",
+ });
+ }
+}
diff --git a/web/src/pages/api/public/slack/oauth/index.ts b/web/src/pages/api/public/slack/oauth/index.ts
new file mode 100644
index 0000000000..0f8c36b932
--- /dev/null
+++ b/web/src/pages/api/public/slack/oauth/index.ts
@@ -0,0 +1,30 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { handleCallback } from "@/src/features/slack/server/oauth-handlers";
+import { logger } from "@langfuse/shared/src/server";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ try {
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "GET") {
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ // Let SlackOAuthHandlers handle the entire OAuth callback flow
+ // This includes:
+ // - Validating the OAuth parameters
+ // - Exchanging code for tokens
+ // - Storing the installation
+ // - Redirecting to the appropriate page
+ return await handleCallback(req, res);
+ } catch (error) {
+ logger.error("OAuth callback handler failed", { error });
+
+ // Fallback redirect on unexpected errors
+ return res.redirect("/settings/slack?error=unexpected_error");
+ }
+}
diff --git a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
index 839e8367f1..363f8a918f 100644
--- a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
@@ -12,7 +12,7 @@ import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
import PromptMetrics from "./metrics";
import { useQueryParams, StringParam } from "use-query-params";
import React from "react";
-import { WebhookButton } from "@/src/features/automations/components/WebhookButton";
+import { AutomationButton } from "@/src/features/automations/components/AutomationButton";
export default function PromptsWithFolder() {
const router = useRouter();
@@ -90,7 +90,7 @@ export default function PromptsWithFolder() {
},
actionButtonsRight: (
<>
- {projectId && <WebhookButton projectId={projectId} />}
+ {projectId && <AutomationButton projectId={projectId} />}
<ActionButton
icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
hasAccess={hasCUDAccess}
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index b4de547aae..e2512ff5aa 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -26,6 +26,7 @@ import { ModelsSettings } from "@/src/features/models/components/ModelSettings";
import ConfigureRetention from "@/src/features/projects/components/ConfigureRetention";
import ContainerPage from "@/src/components/layouts/container-page";
import ProtectedLabelsSettings from "@/src/features/prompts/components/ProtectedLabelsSettings";
+import { Slack } from "lucide-react";
type ProjectSettingsPage = {
title: string;
@@ -307,6 +308,26 @@ const Integrations = (props: { projectId: string }) => {
</Button>
</div>
</Card>
+
+ <Card className="p-3">
+ <div className="mb-4 flex items-center gap-2">
+ <Slack className="h-5 w-5 text-foreground" />
+ <span className="font-semibold">Slack</span>
+ </div>
+ <p className="mb-4 text-sm text-primary">
+ Connect a Slack workspace and create channel automations to receive
+ Langfuse alerts natively in Slack.
+ </p>
+ <div className="flex items-center gap-2">
+ <ActionButton
+ variant="secondary"
+ hasAccess={hasAccess}
+ href={`/project/${props.projectId}/settings/integrations/slack`}
+ >
+ Configure
+ </ActionButton>
+ </div>
+ </Card>
</div>
</div>
);
diff --git a/web/src/pages/project/[projectId]/settings/integrations/slack.tsx b/web/src/pages/project/[projectId]/settings/integrations/slack.tsx
new file mode 100644
index 0000000000..7c81ec5479
--- /dev/null
+++ b/web/src/pages/project/[projectId]/settings/integrations/slack.tsx
@@ -0,0 +1,182 @@
+import ContainerPage from "@/src/components/layouts/container-page";
+import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { AutomationButton } from "@/src/features/automations/components/AutomationButton";
+import { SlackConnectionCard } from "@/src/features/slack/components/SlackConnectionCard";
+import {
+ ChannelSelector,
+ type SlackChannel,
+} from "@/src/features/slack/components/ChannelSelector";
+import { SlackTestMessageButton } from "@/src/features/slack/components/SlackTestMessageButton";
+import { api } from "@/src/utils/api";
+import { useRouter } from "next/router";
+import { useState, useEffect } from "react";
+import { Badge } from "@/src/components/ui/badge";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/src/components/ui/card";
+
+export default function SlackIntegrationSettings() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ // Handle popup OAuth completion
+ useEffect(() => {
+ // Check if this page is opened in a popup window
+ const isPopup = window.opener && window.opener !== window;
+
+ if (isPopup) {
+ // Check for OAuth completion parameters
+ const urlParams = new URLSearchParams(window.location.search);
+ const success = urlParams.get("success");
+ const error = urlParams.get("error");
+ const teamName = urlParams.get("team_name");
+
+ if (success === "true") {
+ // Send success message to parent window
+ window.opener.postMessage(
+ {
+ type: "slack-oauth-success",
+ teamName: teamName || "your Slack workspace",
+ },
+ window.location.origin,
+ );
+
+ // Close popup
+ window.close();
+ } else if (error) {
+ // Send error message to parent window
+ window.opener.postMessage(
+ {
+ type: "slack-oauth-error",
+ error: error,
+ },
+ window.location.origin,
+ );
+
+ // Close popup
+ window.close();
+ }
+ }
+ }, [router.query]);
+
+ const { data: integrationStatus, isInitialLoading } =
+ api.slack.getIntegrationStatus.useQuery(
+ { projectId },
+ { enabled: !!projectId },
+ );
+
+ const status = isInitialLoading
+ ? undefined
+ : integrationStatus?.isConnected
+ ? "active"
+ : "inactive";
+
+ const [selectedChannel, setSelectedChannel] = useState<SlackChannel | null>(
+ null,
+ );
+
+ // Check user permissions
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Slack Integration",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
+ actionButtonsRight: <AutomationButton projectId={projectId} />,
+ }}
+ >
+ <div className="space-y-6">
+ {/* Connection Configuration */}
+ <SlackConnectionCard projectId={projectId} showConnectButton={true} />
+
+ {/* Test Channel Section - Only show when connected */}
+ {integrationStatus?.isConnected && (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Test Integration
+ </CardTitle>
+ <CardDescription>
+ Test your Slack integration by sending a message to a channel.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div>
+ <h4 className="mb-2 text-sm font-medium">
+ Select Test Channel
+ </h4>
+ <div className="max-w-md">
+ <ChannelSelector
+ projectId={projectId}
+ selectedChannelId={selectedChannel?.id}
+ onChannelSelect={setSelectedChannel}
+ placeholder="Choose a channel to test"
+ showRefreshButton={true}
+ />
+ </div>
+ </div>
+
+ {selectedChannel && (
+ <div className="space-y-4 border-t pt-4">
+ <div>
+ <h4 className="mb-3 text-sm font-medium">
+ Channel Information
+ </h4>
+ <div className="grid gap-4 md:grid-cols-2">
+ <div>
+ <p className="text-sm font-medium">Channel Name</p>
+ <p className="text-sm text-muted-foreground">
+ #{selectedChannel.name}
+ </p>
+ </div>
+ <div>
+ <p className="text-sm font-medium">Channel Type</p>
+ <Badge variant="outline" className="text-xs">
+ {selectedChannel.isPrivate ? "Private" : "Public"}
+ </Badge>
+ </div>
+ <div>
+ <p className="text-sm font-medium">Channel ID</p>
+ <p className="font-mono text-sm text-muted-foreground">
+ {selectedChannel.id}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <SlackTestMessageButton
+ projectId={projectId}
+ selectedChannel={selectedChannel}
+ hasAccess={hasAccess}
+ disabled={false}
+ />
+ </div>
+ </div>
+ )}
+
+ {!selectedChannel && (
+ <div className="text-sm text-muted-foreground">
+ Select a channel above to view its details and test message
+ delivery.
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ </ContainerPage>
+ );
+}
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index d88921839c..c2d61932ad 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -41,6 +41,7 @@ import { TableViewPresetsRouter } from "@/src/server/api/routers/tableViewPreset
import { automationsRouter } from "@/src/features/automations/server/router";
import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";
import { plainRouter } from "@/src/features/support-chat/trpc/plain";
+import { slackRouter } from "@/src/features/slack/server/router";
/**
* This is the primary router for your server.
@@ -89,6 +90,7 @@ export const appRouter = createTRPCRouter({
dashboardWidgets: dashboardWidgetRouter,
TableViewPresets: TableViewPresetsRouter,
automations: automationsRouter,
+ slack: slackRouter,
plain: plainRouter,
});
diff --git a/worker/package.json b/worker/package.json
index 33df0aaff5..64ea124365 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -38,6 +38,7 @@
"@opentelemetry/resources": "^1.26.0",
"@opentelemetry/sdk-node": "^0.53.0",
"@prisma/instrumentation": "^6.3.0",
+ "@slack/web-api": "^7.0.0",
"backoff": "^2.5.0",
"bullmq": "^5.34.10",
"cors": "^2.8.5",
diff --git a/worker/src/__tests__/promptVersionProcessor.test.ts b/worker/src/__tests__/promptVersionProcessor.test.ts
index a34a70ecce..12487a73d0 100644
--- a/worker/src/__tests__/promptVersionProcessor.test.ts
+++ b/worker/src/__tests__/promptVersionProcessor.test.ts
@@ -41,6 +41,7 @@ describe("promptVersionChangeWorker", () => {
projectId,
type: ActionType.WEBHOOK,
config: {
+ type: "WEBHOOK",
url: "https://webhook.example.com/test",
headers: {},
method: "POST",
@@ -133,6 +134,7 @@ describe("promptVersionChangeWorker", () => {
projectId,
type: ActionType.WEBHOOK,
config: {
+ type: "WEBHOOK",
url: "https://webhook.example.com/test",
headers: {},
method: "POST",
diff --git a/worker/src/__tests__/slack-message-builder.test.ts b/worker/src/__tests__/slack-message-builder.test.ts
new file mode 100644
index 0000000000..eb33e00a73
--- /dev/null
+++ b/worker/src/__tests__/slack-message-builder.test.ts
@@ -0,0 +1,254 @@
+import { describe, it, expect } from "vitest";
+import { SlackMessageBuilder } from "../features/slack/slackMessageBuilder";
+import type { WebhookInput } from "@langfuse/shared/src/server";
+
+describe("SlackMessageBuilder", () => {
+ const mockPromptPayload: WebhookInput["payload"] = {
+ action: "created",
+ type: "prompt-version",
+ prompt: {
+ id: "prompt-123",
+ name: "test-prompt",
+ version: 2,
+ projectId: "project-456",
+ type: "text",
+ labels: ["production", "v2"],
+ tags: ["ai", "completion"],
+ commitMessage: "Added new context handling",
+ createdAt: new Date("2023-12-15T10:30:00Z"),
+ updatedAt: new Date("2023-12-15T10:30:00Z"),
+ createdBy: "user-123",
+ isActive: true,
+ prompt: { text: "Hello {{name}}" },
+ config: { temperature: 0.7 },
+ },
+ };
+
+ describe("buildPromptVersionMessage", () => {
+ it("should build complete prompt-version message with all fields", () => {
+ const blocks =
+ SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);
+
+ expect(blocks).toHaveLength(6); // header, main, details, commit, actions, footer
+
+ // Check header block
+ expect(blocks[0]).toMatchObject({
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "✨ Prompt created",
+ emoji: true,
+ },
+ });
+
+ // Check main content
+ expect(blocks[1]).toMatchObject({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*test-prompt* (version 2) has been *created*",
+ },
+ });
+
+ // Check details section with fields
+ expect(blocks[2]).toMatchObject({
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: "*Type:*\ntext",
+ },
+ {
+ type: "mrkdwn",
+ text: "*Version:*\n2",
+ },
+ {
+ type: "mrkdwn",
+ text: "*Labels:*\nproduction, v2",
+ },
+ {
+ type: "mrkdwn",
+ text: "*Tags:*\nai, completion",
+ },
+ ],
+ });
+
+ // Check commit message section
+ expect(blocks[3]).toMatchObject({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*Commit Message:*\n> Added new context handling",
+ },
+ });
+
+ // Check action buttons
+ expect(blocks[4]).toMatchObject({
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View Prompt",
+ emoji: true,
+ },
+ url: expect.stringContaining(
+ "/project/project-456/prompts/test-prompt?version=2",
+ ),
+ style: "primary",
+ },
+ ],
+ });
+
+ // Check footer
+ expect(blocks[5]).toMatchObject({
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: expect.stringMatching(/πŸ•’ .+ \| Langfuse/),
+ },
+ ],
+ });
+ });
+
+ it("should handle missing optional fields gracefully", () => {
+ const minimalPayload: WebhookInput["payload"] = {
+ action: "updated",
+ type: "prompt-version",
+ prompt: {
+ id: "prompt-123",
+ name: "minimal-prompt",
+ version: 1,
+ projectId: "project-456",
+ type: "chat",
+ labels: [],
+ tags: [],
+ commitMessage: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ createdBy: "user-123",
+ isActive: true,
+ prompt: null,
+ config: null,
+ },
+ };
+
+ const blocks =
+ SlackMessageBuilder.buildPromptVersionMessage(minimalPayload);
+
+ expect(blocks).toHaveLength(5); // No commit message section
+
+ // Check labels and tags show "None"
+ const detailsSection = blocks[2];
+ expect(detailsSection.fields[2].text).toBe("*Labels:*\nNone");
+ expect(detailsSection.fields[3].text).toBe("*Tags:*\nNone");
+
+ // Ensure no commit message section
+ expect(
+ blocks.find((block) => block.text?.text?.includes("*Commit Message:*")),
+ ).toBeUndefined();
+ });
+
+ it("should generate correct action emojis for different actions", () => {
+ const testCases = [
+ { action: "created", expectedEmoji: "✨" },
+ { action: "updated", expectedEmoji: "πŸ“" },
+ { action: "deleted", expectedEmoji: "πŸ—‘οΈ" },
+ { action: "unknown", expectedEmoji: "πŸ“‹" },
+ ];
+
+ testCases.forEach(({ action, expectedEmoji }) => {
+ const payload = { ...mockPromptPayload, action: action as any };
+ const blocks = SlackMessageBuilder.buildPromptVersionMessage(payload);
+
+ expect(blocks[0].text.text).toBe(`${expectedEmoji} Prompt ${action}`);
+ });
+ });
+
+ it("should generate correct URLs for different environments", () => {
+ const expectedUrl =
+ process.env.NODE_ENV === "test"
+ ? "https://staging.langfuse.com"
+ : process.env.NODE_ENV === "production"
+ ? "https://cloud.langfuse.com"
+ : "https://localhost:3000";
+
+ let blocks =
+ SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);
+ expect(blocks[4].elements[0].url).toContain(expectedUrl);
+ });
+ });
+
+ describe("buildFallbackMessage", () => {
+ it("should build simple fallback message for unknown event types", () => {
+ const unknownPayload = {
+ action: "triggered",
+ type: "unknown-event" as any,
+ };
+
+ const blocks = SlackMessageBuilder.buildFallbackMessage(
+ unknownPayload as any,
+ );
+
+ expect(blocks).toHaveLength(2);
+
+ expect(blocks[0]).toMatchObject({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*Langfuse Notification*\nunknown-event event: *triggered*",
+ },
+ });
+
+ expect(blocks[1]).toMatchObject({
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: expect.stringMatching(/πŸ•’ .+ \| Langfuse/),
+ },
+ ],
+ });
+ });
+ });
+
+ describe("buildMessage", () => {
+ it("should route prompt-version events to prompt message builder", () => {
+ const blocks = SlackMessageBuilder.buildMessage(mockPromptPayload);
+
+ // Should be a full prompt message (6 blocks with commit message)
+ expect(blocks).toHaveLength(6);
+ expect(blocks[0].text.text).toContain("Prompt created");
+ });
+
+ it("should route unknown events to fallback message builder", () => {
+ const unknownPayload = {
+ action: "executed",
+ type: "trace-evaluation" as any,
+ };
+
+ const blocks = SlackMessageBuilder.buildMessage(unknownPayload as any);
+
+ // Should be a fallback message (2 blocks)
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0].text.text).toContain("Langfuse Notification");
+ });
+
+ it("should handle errors gracefully and return fallback", () => {
+ // Create a payload that would cause an error (missing required fields)
+ const malformedPayload = {
+ action: "created",
+ type: "prompt-version",
+ prompt: null, // This should cause an error
+ } as any;
+
+ const blocks = SlackMessageBuilder.buildMessage(malformedPayload);
+
+ // Should fallback to simple message
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0].text.text).toContain("Langfuse Notification");
+ });
+ });
+});
diff --git a/worker/src/__tests__/slack-processor.test.ts b/worker/src/__tests__/slack-processor.test.ts
new file mode 100644
index 0000000000..71b77ed1cb
--- /dev/null
+++ b/worker/src/__tests__/slack-processor.test.ts
@@ -0,0 +1,465 @@
+import {
+ describe,
+ it,
+ expect,
+ beforeEach,
+ beforeAll,
+ afterAll,
+ vi,
+} from "vitest";
+import { v4 } from "uuid";
+import {
+ ActionExecutionStatus,
+ JobConfigState,
+ PromptDomain,
+ SlackActionConfig,
+} from "@langfuse/shared";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { encrypt } from "@langfuse/shared/encryption";
+import { executeWebhook } from "../queues/webhooks";
+import type { WebhookInput } from "@langfuse/shared/src/server";
+
+// Mock SlackService
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ SlackService: {
+ getInstance: vi.fn(),
+ },
+ };
+});
+
+describe("Slack Processor", () => {
+ let projectId: string;
+ let triggerId: string;
+ let actionId: string;
+ let automationId: string;
+ let promptId: string;
+ let executionId: string;
+ let mockSlackService: any;
+
+ beforeAll(async () => {
+ // Import mocked SlackService
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Create mock service instance
+ mockSlackService = {
+ getWebClientForProject: vi.fn(),
+ sendMessage: vi.fn(),
+ };
+
+ // Setup the getInstance mock to return our mock service
+ (SlackService.getInstance as any).mockReturnValue(mockSlackService);
+
+ // Setup default mock implementations
+ mockSlackService.getWebClientForProject.mockResolvedValue({
+ chat: { postMessage: vi.fn() },
+ });
+
+ mockSlackService.sendMessage.mockResolvedValue({
+ messageTs: "1234567890.123456",
+ channel: "C123456",
+ });
+ });
+
+ beforeEach(async () => {
+ // Reset mocks
+ vi.clearAllMocks();
+
+ // Create test project
+ ({ projectId } = await createOrgProjectAndApiKey());
+
+ // Create Slack integration
+ await prisma.slackIntegration.create({
+ data: {
+ projectId,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ // Create test prompt
+ promptId = v4();
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ projectId,
+ name: "test-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Hello {{name}}" },
+ createdBy: "test-user",
+ },
+ });
+
+ // Create test trigger
+ triggerId = v4();
+ await prisma.trigger.create({
+ data: {
+ id: triggerId,
+ projectId,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+
+ // Create test Slack action
+ actionId = v4();
+ await prisma.action.create({
+ data: {
+ id: actionId,
+ projectId,
+ type: "SLACK",
+ config: {
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ } as SlackActionConfig,
+ },
+ });
+
+ // Link trigger to action
+ automationId = v4();
+ await prisma.automation.create({
+ data: {
+ id: automationId,
+ projectId,
+ triggerId,
+ actionId,
+ name: "Test Slack Automation",
+ },
+ });
+
+ executionId = v4();
+ });
+
+ afterAll(async () => {
+ vi.restoreAllMocks();
+ });
+
+ describe("executeSlack function", () => {
+ it("should execute slack action successfully", async () => {
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: fullPrompt as PromptDomain,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: slackInput.executionId,
+ input: slackInput,
+ },
+ });
+
+ await executeWebhook(slackInput);
+
+ // Verify SlackService was called correctly
+ expect(SlackService.getInstance).toHaveBeenCalled();
+ expect(mockSlackService.getWebClientForProject).toHaveBeenCalledWith(
+ projectId,
+ );
+ expect(mockSlackService.sendMessage).toHaveBeenCalledWith({
+ client: expect.any(Object),
+ channelId: "C123456",
+ blocks: expect.any(Array),
+ text: "Langfuse Notification",
+ });
+
+ // Verify database execution record was updated
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ expect(execution?.output).toMatchObject({
+ channel: "C123456",
+ messageTs: "1234567890.123456",
+ });
+ expect(execution?.startedAt).toBeDefined();
+ expect(execution?.finishedAt).toBeDefined();
+ });
+
+ it("should handle missing automation gracefully", async () => {
+ const nonExistentAutomationId = v4();
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId: nonExistentAutomationId,
+ executionId,
+ payload: {
+ prompt: { id: promptId } as PromptDomain,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ // Should not throw an error, but return gracefully
+ await expect(executeWebhook(slackInput)).resolves.toBeUndefined();
+
+ // Verify that no SlackService calls were made
+ const { SlackService } = await import("@langfuse/shared/src/server");
+ expect(SlackService.getInstance).not.toHaveBeenCalled();
+ expect(mockSlackService.getWebClientForProject).not.toHaveBeenCalled();
+ expect(mockSlackService.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("should use custom template when provided", async () => {
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Update action to include custom message template
+ const customTemplate = [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "Custom Slack template message",
+ },
+ },
+ ];
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: {
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ messageTemplate: JSON.stringify(customTemplate),
+ } as SlackActionConfig,
+ },
+ });
+
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: fullPrompt as any,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: executionId,
+ input: slackInput,
+ },
+ });
+
+ await executeWebhook(slackInput);
+
+ // Verify custom template was used
+ expect(mockSlackService.sendMessage).toHaveBeenCalledWith({
+ client: expect.any(Object),
+ channelId: "C123456",
+ blocks: customTemplate,
+ text: "Langfuse Notification",
+ });
+ });
+
+ it("should fallback to default message on template error", async () => {
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Update action with invalid JSON template
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: {
+ type: "SLACK",
+ channelId: "C123456",
+ channelName: "general",
+ messageTemplate: "invalid-json-template",
+ } as SlackActionConfig,
+ },
+ });
+
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: fullPrompt as PromptDomain,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: executionId,
+ input: slackInput,
+ },
+ });
+
+ await executeWebhook(slackInput);
+
+ // Verify default message was used (should have multiple blocks from SlackMessageBuilder)
+ expect(mockSlackService.sendMessage).toHaveBeenCalledWith({
+ client: expect.any(Object),
+ channelId: "C123456",
+ blocks: expect.any(Array),
+ text: "Langfuse Notification",
+ });
+
+ // Verify execution completed successfully despite template error
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("should disable trigger after 4 consecutive failures", async () => {
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Mock SlackService to throw errors
+ mockSlackService.sendMessage.mockRejectedValue(
+ new Error("Slack API error"),
+ );
+
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Execute Slack action 5 times to trigger consecutive failures
+ for (let i = 0; i < 5; i++) {
+ const executionId = v4();
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: v4(),
+ input: {
+ promptName: "test-prompt",
+ promptVersion: 1,
+ action: "created",
+ type: "prompt-version",
+ },
+ },
+ });
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: fullPrompt as PromptDomain,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await executeWebhook(slackInput);
+
+ // Verify execution was marked as error
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ expect(execution?.error).toContain("Slack API error");
+ }
+
+ // Verify trigger was disabled after 4 consecutive failures
+ const trigger = await prisma.trigger.findUnique({
+ where: { id: triggerId },
+ });
+ expect(trigger?.status).toBe(JobConfigState.INACTIVE);
+ });
+
+ it("should handle SlackService errors gracefully", async () => {
+ const { SlackService } = await import("@langfuse/shared/src/server");
+
+ // Mock SlackService to throw an error
+ mockSlackService.getWebClientForProject.mockRejectedValue(
+ new Error("Failed to get Slack client"),
+ );
+
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const slackInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: fullPrompt as PromptDomain,
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: executionId,
+ input: slackInput,
+ },
+ });
+
+ await executeWebhook(slackInput);
+
+ // Verify execution was marked as error
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ expect(execution?.error).toContain("Failed to get Slack client");
+ });
+ });
+});
diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.ts
index 2116ab8a89..55055f9a5e 100644
--- a/worker/src/__tests__/webhooks.test.ts
+++ b/worker/src/__tests__/webhooks.test.ts
@@ -342,7 +342,7 @@ describe("Webhook Integration Tests", () => {
};
await expect(executeWebhook(webhookInput)).rejects.toThrow(
- "Webhook config has no secret key, failing webhook execution",
+ "Action config is not a valid webhook configuration",
);
const execution = await prisma.automationExecution.findUnique({
diff --git a/worker/src/features/entityChange/promptVersionProcessor.ts b/worker/src/features/entityChange/promptVersionProcessor.ts
index 4aadef51eb..35b47daac0 100644
--- a/worker/src/features/entityChange/promptVersionProcessor.ts
+++ b/worker/src/features/entityChange/promptVersionProcessor.ts
@@ -98,8 +98,18 @@ export const promptVersionProcessor = async (
}
await Promise.all(
- trigger.actionIds.map(async (actionId) =>
- executeWebhookAction({
+ trigger.actionIds.map(async (actionId) => {
+ const actionConfig = await getActionById({
+ projectId: event.projectId,
+ actionId,
+ });
+
+ if (!actionConfig) {
+ logger.error(`Action ${actionId} not found`);
+ return;
+ }
+
+ await enqueueAutomationAction({
promptData: {
...event.prompt,
resolutionGraph: null,
@@ -108,8 +118,8 @@ export const promptVersionProcessor = async (
triggerId: trigger.id,
actionId,
projectId: event.projectId,
- }),
- ),
+ });
+ }),
);
} catch (error) {
logger.error(
@@ -127,9 +137,10 @@ export const promptVersionProcessor = async (
};
/**
- * Execute a webhook action for a prompt version change
+ * Enqueue an automation action for a prompt version change.
+ * Handles both webhook and Slack actions by enqueueing to the same webhook queue.
*/
-async function executeWebhookAction({
+async function enqueueAutomationAction({
promptData,
action,
triggerId,
@@ -142,16 +153,7 @@ async function executeWebhookAction({
actionId: string;
projectId: string;
}): Promise<void> {
- // Get action configuration
- const actionConfig = await getActionById({
- projectId,
- actionId,
- });
-
- if (!actionConfig) {
- throw new Error(`Action ${actionId} not found`);
- }
-
+ // Get automations for this action
const automations = await getAutomations({
projectId,
actionId,
@@ -166,13 +168,13 @@ async function executeWebhookAction({
const executionId = v4();
// Create execution record
- const execution = await prisma.automationExecution.create({
+ await prisma.automationExecution.create({
data: {
id: executionId,
projectId,
automationId: automations[0].id,
- triggerId: triggerId,
- actionId: actionId,
+ triggerId,
+ actionId,
status: ActionExecutionStatus.PENDING,
sourceId: promptData.id,
input: {
@@ -186,17 +188,17 @@ async function executeWebhookAction({
});
logger.debug(
- `Created action execution ${execution.id} for project ${projectId} and trigger ${triggerId} and action ${actionId}`,
+ `Created automation execution ${executionId} for project ${projectId} and action ${actionId}`,
);
- // Queue webhook
+ // Queue to webhook processor (handles both webhook and Slack actions)
await WebhookQueue.getInstance()?.add(QueueName.WebhookQueue, {
timestamp: new Date(),
id: v4(),
payload: {
projectId,
automationId: automations[0].id,
- executionId: executionId,
+ executionId,
payload: {
action: action as TriggerEventAction,
type: "prompt-version",
diff --git a/worker/src/features/slack/slackMessageBuilder.ts b/worker/src/features/slack/slackMessageBuilder.ts
new file mode 100644
index 0000000000..8d64865a08
--- /dev/null
+++ b/worker/src/features/slack/slackMessageBuilder.ts
@@ -0,0 +1,170 @@
+import { logger } from "@langfuse/shared/src/server";
+import type { WebhookInput } from "@langfuse/shared/src/server";
+import { env } from "../../env";
+
+/**
+ * Builds Slack Block Kit messages for different Langfuse event types
+ */
+export class SlackMessageBuilder {
+ /**
+ * Build Block Kit message for prompt version events
+ */
+ static buildPromptVersionMessage(payload: WebhookInput["payload"]): any[] {
+ const { action, prompt } = payload;
+
+ // Determine action emoji and color
+ const actionConfig = this.getActionConfig(action);
+
+ // generate url base
+ const urlBase =
+ env.NODE_ENV === "development"
+ ? "https://localhost:3000"
+ : env.NODE_ENV === "test"
+ ? "https://staging.langfuse.com"
+ : "https://cloud.langfuse.com";
+
+ // Build the main message blocks
+ const blocks = [
+ // Header block with emoji and action
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `${actionConfig.emoji} Prompt ${action}`,
+ emoji: true,
+ },
+ },
+ // Main content section
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*${prompt.name}* (version ${prompt.version}) has been *${action}*`,
+ },
+ },
+ // Details section with key information
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Type:*\n${prompt.type}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Version:*\n${prompt.version}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Labels:*\n${prompt.labels.length > 0 ? prompt.labels.join(", ") : "None"}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Tags:*\n${prompt.tags.length > 0 ? prompt.tags.join(", ") : "None"}`,
+ },
+ ],
+ },
+ // Commit message if available
+ ...(prompt.commitMessage
+ ? [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Commit Message:*\n> ${prompt.commitMessage}`,
+ },
+ },
+ ]
+ : []),
+ // Action buttons
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View Prompt",
+ emoji: true,
+ },
+ url: `${urlBase}/project/${prompt.projectId}/prompts/${encodeURIComponent(prompt.name)}?version=${prompt.version}`,
+ style: "primary",
+ },
+ ],
+ },
+ // Footer with timestamp
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `πŸ•’ ${new Date().toLocaleString()} | Langfuse`,
+ },
+ ],
+ },
+ ];
+
+ return blocks;
+ }
+
+ /**
+ * Build a simple fallback message for unsupported event types
+ */
+ static buildFallbackMessage(payload: WebhookInput["payload"]): any[] {
+ return [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Langfuse Notification*\n${payload.type} event: *${payload.action}*`,
+ },
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `πŸ•’ ${new Date().toLocaleString()} | Langfuse`,
+ },
+ ],
+ },
+ ];
+ }
+
+ /**
+ * Get action-specific configuration (emoji, color, etc.)
+ */
+ private static getActionConfig(action: string): {
+ emoji: string;
+ color?: string;
+ } {
+ switch (action.toLowerCase()) {
+ case "created":
+ return { emoji: "✨", color: "good" };
+ case "updated":
+ return { emoji: "πŸ“", color: "warning" };
+ case "deleted":
+ return { emoji: "πŸ—‘οΈ", color: "danger" };
+ default:
+ return { emoji: "πŸ“‹" };
+ }
+ }
+
+ /**
+ * Main entry point - builds appropriate message for event type
+ */
+ static buildMessage(payload: WebhookInput["payload"]): any[] {
+ try {
+ switch (payload.type) {
+ case "prompt-version":
+ return this.buildPromptVersionMessage(payload);
+ default:
+ logger.warn(`Unsupported Slack message type: ${payload.type}`);
+ return this.buildFallbackMessage(payload);
+ }
+ } catch (error) {
+ logger.error("Error building Slack message", { error, payload });
+ return this.buildFallbackMessage(payload);
+ }
+ }
+}
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 8ae4228df9..a0cdc14edc 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -5,6 +5,8 @@ import {
ActionExecutionStatus,
LangfuseNotFoundError,
JobConfigState,
+ isSlackActionConfig,
+ isWebhookAction,
} from "@langfuse/shared";
import { decrypt, createSignatureHeader } from "@langfuse/shared/encryption";
import { prisma } from "@langfuse/shared/src/db";
@@ -14,13 +16,17 @@ import {
WebhookInput,
getAutomationById,
getActionByIdWithSecrets,
+ getActionById,
getConsecutiveAutomationFailures,
+ SlackService,
logger,
} from "@langfuse/shared/src/server";
import { Processor, Job } from "bullmq";
import { backOff } from "exponential-backoff";
import { env } from "../env";
+import { SlackMessageBuilder } from "../features/slack/slackMessageBuilder";
+// Handles both webhook and slack actions
export const webhookProcessor: Processor = async (
job: Job<TQueueJobTypes[QueueName.WebhookQueue]>,
) => {
@@ -34,14 +40,10 @@ export const webhookProcessor: Processor = async (
// TODO: Webhook outgoing API versioning
export const executeWebhook = async (input: WebhookInput) => {
- const executionStart = new Date();
-
- const { projectId, automationId, executionId } = input;
- let httpStatus: number | undefined;
- let responseBody: string | undefined;
+ const { projectId, automationId } = input;
try {
- logger.debug(`Executing webhook for automation ${automationId}`);
+ logger.debug(`Executing action for automation ${automationId}`);
const automation = await getAutomationById({
projectId,
@@ -55,22 +57,68 @@ export const executeWebhook = async (input: WebhookInput) => {
return;
}
+ // Route to appropriate handler based on action type
+ if (automation.action.type === "WEBHOOK") {
+ await executeWebhookAction({
+ input,
+ automation,
+ });
+ } else if (automation.action.type === "SLACK") {
+ await executeSlackAction({
+ input,
+ automation,
+ });
+ } else {
+ throw new InternalServerError(
+ `Unsupported action type: ${automation.action.type}`,
+ );
+ }
+
+ logger.debug(
+ `Action executed successfully for action ${automation.action.id}`,
+ );
+ } catch (error) {
+ logger.error("Error executing action", error);
+ throw error;
+ }
+};
+
+/**
+ * Execute webhook action with HTTP request and signature validation
+ */
+async function executeWebhookAction({
+ input,
+ automation,
+}: {
+ input: WebhookInput;
+ automation: Awaited<ReturnType<typeof getAutomationById>>;
+}) {
+ if (!automation) return;
+
+ const { projectId, executionId } = input;
+ const executionStart = new Date();
+ let httpStatus: number | undefined;
+ let responseBody: string | undefined;
+
+ try {
const actionConfig = await getActionByIdWithSecrets({
projectId,
actionId: automation.action.id,
});
if (!actionConfig) {
- throw new Error("Action config not found");
+ throw new InternalServerError("Action config not found");
}
- if (actionConfig.config.type !== "WEBHOOK") {
- throw new InternalServerError("Action config is not a webhook");
+ if (!isWebhookAction(actionConfig)) {
+ throw new InternalServerError(
+ "Action config is not a valid webhook configuration",
+ );
}
- // TypeScript now knows actionConfig.config is WebhookActionConfig
const webhookConfig = actionConfig.config;
+ // Validate and prepare webhook payload
const validatedPayload = PromptWebhookOutboundSchema.safeParse({
id: input.executionId,
timestamp: new Date(),
@@ -97,8 +145,10 @@ export const executeWebhook = async (input: WebhookInput) => {
const requestHeaders: Record<string, string> = {};
// Add webhook config headers first
- for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {
- requestHeaders[key] = value.value;
+ if (webhookConfig.requestHeaders) {
+ for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {
+ requestHeaders[key] = value.value;
+ }
}
// Add default headers with precedence
@@ -106,33 +156,19 @@ export const executeWebhook = async (input: WebhookInput) => {
requestHeaders[key] = value;
}
- if (!webhookConfig.secretKey) {
- logger.warn(
- `Webhook config for action ${automation.action.id} has no secret key, failing webhook execution`,
- );
- throw new InternalServerError(
- "Webhook config has no secret key, failing webhook execution",
+ try {
+ const decryptedSecret = decrypt(webhookConfig.secretKey);
+ const signature = createSignatureHeader(webhookPayload, decryptedSecret);
+ requestHeaders["x-langfuse-signature"] = signature;
+ } catch (error) {
+ logger.error(
+ "Failed to decrypt webhook secret or generate signature",
+ error,
);
+ throw new InternalServerError("Failed to generate webhook signature");
}
- if (webhookConfig.secretKey) {
- try {
- const decryptedSecret = decrypt(webhookConfig.secretKey);
-
- const signature = createSignatureHeader(
- webhookPayload,
- decryptedSecret,
- );
- requestHeaders["x-langfuse-signature"] = signature;
- } catch (error) {
- logger.error(
- "Failed to decrypt webhook secret or generate signature",
- error,
- );
- throw new InternalServerError("Failed to generate webhook signature");
- }
- }
-
+ // Execute webhook with retries
await backOff(
async () => {
logger.debug(
@@ -181,11 +217,11 @@ export const executeWebhook = async (input: WebhookInput) => {
}
},
{
- numOfAttempts: 4, // no retries for webhook calls via BullMQ
+ numOfAttempts: 4,
},
);
- // Update action execution status on success
+ // Update execution status on success
await prisma.automationExecution.update({
where: {
projectId,
@@ -199,34 +235,17 @@ export const executeWebhook = async (input: WebhookInput) => {
finishedAt: new Date(),
},
});
-
- logger.debug(
- `Webhook executed successfully for action ${automation.action.id}`,
- );
} catch (error) {
- logger.error("Error executing webhook", error);
-
- const automation = await getAutomationById({
- projectId,
- automationId,
- });
-
- if (!automation) {
- logger.warn(
- `Automation ${automationId} not found for project ${projectId}. We ack the job and will not retry.`,
- );
- return;
- }
+ logger.error("Error executing webhook action", error);
+ // Handle webhook action failure with retry logic and trigger disabling
const shouldRetryJob =
error instanceof LangfuseNotFoundError ||
error instanceof InternalServerError;
if (shouldRetryJob) {
- logger.warn(
- `Retrying bullmq for webhook job for action ${automation.action.id}`,
- );
- throw error;
+ logger.warn(`Retrying BullMQ for webhook action ${automation.action.id}`);
+ throw error; // Trigger BullMQ retry
}
// Get action config for updating in case of failure
@@ -240,7 +259,7 @@ export const executeWebhook = async (input: WebhookInput) => {
return;
}
- // Update action execution status and check if we should disable trigger
+ // Update execution status and check if we should disable trigger
await prisma.$transaction(async (tx) => {
// Update execution status
await tx.automationExecution.update({
@@ -266,7 +285,7 @@ export const executeWebhook = async (input: WebhookInput) => {
// Check consecutive failures from execution history
const consecutiveFailures = await getConsecutiveAutomationFailures({
- automationId,
+ automationId: automation.id,
projectId,
});
@@ -300,7 +319,156 @@ export const executeWebhook = async (input: WebhookInput) => {
});
logger.debug(
- `Webhook failed for action ${automation.action.id} in project ${projectId}`,
+ `Webhook action failed for action ${automation.action.id} in project ${projectId}`,
);
}
-};
+}
+
+/**
+ * Execute Slack action with message sending via SlackService
+ */
+async function executeSlackAction({
+ input,
+ automation,
+}: {
+ input: WebhookInput;
+ automation: Awaited<ReturnType<typeof getAutomationById>>;
+}) {
+ if (!automation) return;
+
+ const { projectId, executionId } = input;
+ const executionStart = new Date();
+
+ try {
+ const actionConfig = await getActionById({
+ projectId,
+ actionId: automation.action.id,
+ });
+
+ if (!actionConfig) {
+ throw new InternalServerError("Action config not found");
+ }
+
+ if (!isSlackActionConfig(actionConfig.config)) {
+ throw new InternalServerError(
+ "Action config is not a valid Slack configuration",
+ );
+ }
+
+ const slackConfig = actionConfig.config;
+
+ // Build message blocks using predefined formats or custom template
+ let blocks: any[] = [];
+
+ // TODO: Custom templates not supported via the UI yet
+ if (slackConfig.messageTemplate) {
+ try {
+ blocks = JSON.parse(slackConfig.messageTemplate);
+ logger.debug(
+ `Using custom message template for action ${automation.action.id}`,
+ );
+ } catch (error) {
+ logger.warn(
+ `Invalid Slack messageTemplate JSON for action ${automation.action.id}. Using default format`,
+ { error: error instanceof Error ? error.message : "Unknown error" },
+ );
+ }
+ }
+
+ // Use predefined message format if no custom template or template failed
+ if (blocks.length === 0) {
+ blocks = SlackMessageBuilder.buildMessage(input.payload);
+ logger.debug(
+ `Using predefined message format for action ${automation.action.id}`,
+ );
+ }
+
+ // Get Slack WebClient for project via centralized SlackService
+ const client =
+ await SlackService.getInstance().getWebClientForProject(projectId);
+
+ // Send message
+ const sendResult = await SlackService.getInstance().sendMessage({
+ client,
+ channelId: slackConfig.channelId,
+ blocks,
+ text: "Langfuse Notification",
+ });
+
+ // Update execution status to completed
+ 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);
+
+ // Get action config for updating in case of failure
+ const failureActionConfig = await getActionByIdWithSecrets({
+ projectId,
+ actionId: automation.action.id,
+ });
+
+ if (!failureActionConfig) {
+ logger.error("Action config not found for failure handling");
+ return;
+ }
+
+ // Update execution status and disable trigger
+ await prisma.$transaction(async (tx) => {
+ // Update execution status
+ await tx.automationExecution.update({
+ where: {
+ id: executionId,
+ projectId,
+ triggerId: automation.trigger.id,
+ actionId: automation.action.id,
+ },
+ data: {
+ status: ActionExecutionStatus.ERROR,
+ startedAt: executionStart,
+ finishedAt: new Date(),
+ error: error instanceof Error ? error.message : "Unknown error",
+ },
+ });
+
+ // Update trigger to inactive status
+ await tx.trigger.update({
+ where: { id: automation.trigger.id, projectId },
+ data: { status: JobConfigState.INACTIVE },
+ });
+
+ // Update action config to store the failing execution ID
+ await tx.action.update({
+ where: { id: automation.action.id, projectId },
+ data: {
+ config: {
+ ...failureActionConfig.config,
+ lastFailingExecutionId: executionId,
+ },
+ },
+ });
+
+ logger.warn(
+ `Automation ${automation.trigger.id} disabled after 1 failure in project ${projectId}`,
+ );
+ });
+
+ logger.debug(
+ `Slack action failed for action ${automation.action.id} in project ${projectId}`,
+ );
+ }
+}