🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(slack): marketplace review – link buttons and private channel visibility (#19075)
Tobias Wochinger6343bd819089
diff --git a/packages/shared/prisma/migrations/20261020120000_add_slack_integration_installer/migration.sql b/packages/shared/prisma/migrations/20261020120000_add_slack_integration_installer/migration.sqlnew file mode 100644index 0000000000..1768d55315--- /dev/null+++ b/packages/shared/prisma/migrations/20261020120000_add_slack_integration_installer/migration.sql@@ -0,0 +1,2 @@+ALTER TABLE "slack_integrations" ADD COLUMN IF NOT EXISTS "installer_user_id" TEXT,+ADD COLUMN IF NOT EXISTS "installer_slack_user_id" TEXT;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 5e3a21a337..e18e2c2a54 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -2164,6 +2164,10 @@ model SlackIntegration {botToken String @map("bot_token") // Encrypted bot token for API callsbotUserId String @map("bot_user_id") // Bot user ID for workspace+ // Only the installer may list and use private channels, since the bot token sees every private channel it was invited to+ installerUserId String? @map("installer_user_id") // Langfuse user who connected Slack+ installerSlackUserId String? @map("installer_slack_user_id") // Slack user who authorized the install+createdAt DateTime @default(now()) @map("created_at")updatedAt DateTime @default(now()) @updatedAt @map("updated_at")diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.tsindex 246c416631..3bbf81e6b8 100644--- a/packages/shared/src/domain/automations.ts+++ b/packages/shared/src/domain/automations.ts@@ -106,6 +106,8 @@ export const SlackActionConfigSchema = z.object({channelId: z.string(),channelName: z.string(),messageTemplate: z.string().optional(),+ // Set server-side on save; private channel names are masked for everyone but the installer+ isPrivate: z.boolean().optional(),});export type SlackActionConfig = z.infer<typeof SlackActionConfigSchema>;diff --git a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.tsindex 9fb3e8454d..1b548e32ae 100644--- a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts+++ b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.test.ts@@ -22,7 +22,7 @@ const mockMonitorAlert: MonitorAlert = {};describe("buildMonitorAlertSlackMessage", () => {- it("ALERT: red attachment; linked title; body mrkdwn; timestamp; neutral view button", () => {+ it("ALERT: red attachment; linked title; body mrkdwn; timestamp; view link", () => {const { blocks, attachments } =buildMonitorAlertSlackMessage(mockMonitorAlert);expect(blocks).toEqual([]);@@ -44,12 +44,10 @@ describe("buildMonitorAlertSlackMessage", () => {expect(inner[1].text.text).toContain("*count(observations.value)*");expect(inner[2]).toMatchObject({ type: "context" });expect(inner[2].elements[0].text).toContain("2026-05-18T12:01:00.000Z");- expect(inner[3]).toMatchObject({ type: "actions" });- expect(inner[3].elements[0]).toMatchObject({- type: "button",- url: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",- });- expect(inner[3].elements[0].style).toBeUndefined();+ expect(inner[3]).toMatchObject({ type: "section" });+ expect(inner[3].text.text).toContain(+ "<https://cloud.langfuse.com/project/proj_01/monitors/mon_01|View in Langfuse>",+ );});it.each([@@ -74,41 +72,30 @@ describe("buildMonitorAlertSlackMessage", () => {);});- it("renders a plain bold title and omits the button when permalink is absent", () => {+ it("renders a plain bold title and omits the link when permalink is absent", () => {const { attachments } = buildMonitorAlertSlackMessage({...mockMonitorAlert,permalink: undefined,});const inner = attachments![0].blocks!;expect(inner[0].text.text).toBe("*High error rate*");- expect(inner.some((b: any) => b.type === "actions")).toBe(false);+ expect(JSON.stringify(inner)).not.toContain("View in Langfuse");expect(inner.some((b: any) => b.type === "context")).toBe(true);});- it("adds a 'View observations' button to the windowed data table when dataPermalink is set (observations view)", () => {+ it("adds a 'View observations' link to the windowed data table when dataPermalink is set (observations view)", () => {const dataPermalink ="https://cloud.langfuse.com/project/proj_01/observations?dateRange=1779450930000-1779451230000";const { attachments } = buildMonitorAlertSlackMessage({...mockMonitorAlert,dataPermalink,});- const actions = attachments![0].blocks!.find(- (b: any) => b.type === "actions",- );- expect(actions.elements).toHaveLength(2);- // Config button kept.- expect(actions.elements[0]).toMatchObject({- text: { text: "View in Langfuse" },- url: mockMonitorAlert.permalink,- });- // Windowed data-table button added.- expect(actions.elements[1]).toMatchObject({- text: { text: "View observations" },- url: dataPermalink,- });+ const links = linkText(attachments);+ expect(links).toContain(`<${mockMonitorAlert.permalink}|View in Langfuse>`);+ expect(links).toContain(`<${dataPermalink}|View observations>`);});- it("labels the data button 'View scores' for a scores view", () => {+ it("labels the data link 'View scores' for a scores view", () => {const dataPermalink ="https://cloud.langfuse.com/project/proj_01/scores?dateRange=1779450930000-1779451230000";const { attachments } = buildMonitorAlertSlackMessage({@@ -116,26 +103,17 @@ describe("buildMonitorAlertSlackMessage", () => {view: "scores-numeric",dataPermalink,});- const actions = attachments![0].blocks!.find(- (b: any) => b.type === "actions",- );- expect(actions.elements).toHaveLength(2);- expect(actions.elements[1]).toMatchObject({- text: { text: "View scores" },- url: dataPermalink,- });+ expect(linkText(attachments)).toContain(`<${dataPermalink}|View scores>`);});- it("keeps only the config button when dataPermalink is absent", () => {+ it("keeps only the config link when dataPermalink is absent", () => {const { attachments } = buildMonitorAlertSlackMessage(mockMonitorAlert);- const actions = attachments![0].blocks!.find(- (b: any) => b.type === "actions",+ expect(linkText(attachments)).toBe(+ `:arrow_right: *<${mockMonitorAlert.permalink}|View in Langfuse>*`,);- expect(actions.elements).toHaveLength(1);- expect(actions.elements[0].text.text).toBe("View in Langfuse");});- it("explains an unavailable score link while retaining the alert action", () => {+ it("explains an unavailable score link while retaining the alert link", () => {const { attachments } = buildMonitorAlertSlackMessage({...mockMonitorAlert,view: "scores-numeric",@@ -144,16 +122,31 @@ describe("buildMonitorAlertSlackMessage", () => {expect(blocks[1].text.text).toContain("A filtered scores link is unavailable",);- const actions = blocks.find((block: any) => block.type === "actions");- expect(actions.elements).toHaveLength(1);- expect(actions.elements[0].url).toBe(mockMonitorAlert.permalink);+ expect(linkText(attachments)).toBe(+ `:arrow_right: *<${mockMonitorAlert.permalink}|View in Langfuse>*`,+ );+ });++ it("explains a score link that does not fit in the link section", () => {+ const dataPermalink = `https://cloud.langfuse.com/project/proj_01/scores?filter=${"a".repeat(2900)}`;+ const { attachments } = buildMonitorAlertSlackMessage({+ ...mockMonitorAlert,+ view: "scores-numeric",+ dataPermalink,+ });+ expect(attachments![0].blocks![1].text.text).toContain(+ "A filtered scores link is unavailable",+ );+ expect(linkText(attachments)).toBe(+ `:arrow_right: *<${mockMonitorAlert.permalink}|View in Langfuse>*`,+ );});// buildAlert only sets dataPermalink for breaching severities, so recovery// (OK) and NO_DATA notifications arrive here with dataPermalink undefined and- // must render no secondary data button — recovery messages stay unchanged.+ // must render no secondary data link — recovery messages stay unchanged.it.each(["OK", "NO_DATA"] as const)(- "renders no secondary data button for a %s (non-breach) alert",+ "renders no secondary data link for a %s (non-breach) alert",(severity) => {const { attachments } = buildMonitorAlertSlackMessage({...mockMonitorAlert,@@ -161,14 +154,18 @@ describe("buildMonitorAlertSlackMessage", () => {severity,dataPermalink: undefined,});- const actions = attachments![0].blocks!.find(- (b: any) => b.type === "actions",+ expect(linkText(attachments)).toBe(+ `:arrow_right: *<${mockMonitorAlert.permalink}|View in Langfuse>*`,);- expect(actions.elements).toHaveLength(1);- expect(actions.elements[0].text.text).toBe("View in Langfuse");expect(attachments![0].blocks![1].text.text).not.toContain("scores link is unavailable",);},);});++function linkText(+ attachments: ReturnType<typeof buildMonitorAlertSlackMessage>["attachments"],+): string {+ return attachments![0].blocks!.at(-1).text.text;+}diff --git a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.tsindex 73f235fa29..26a2fb2081 100644--- a/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts+++ b/packages/shared/src/features/monitors/processor/buildMonitorAlertSlackMessage.ts@@ -1,4 +1,5 @@import { buildColoredAttachmentSlackMessage } from "../../../server/services/buildColoredAttachmentSlackMessage";+import { buildSlackLinkSection } from "../../../server/services/buildSlackLinkSection";import { type SlackMessage } from "../../../server/services/SlackService";import { type MonitorAlert, type MonitorSeverity } from "../types";@@ -16,10 +17,19 @@ const severityVisual: Record<MonitorSeverity, { color: string }> = {export function buildMonitorAlertSlackMessage(alert: MonitorAlert,): SlackMessage {+ const secondaryLabel =+ alert.view === "observations" ? "View observations" : "View scores";+ const dataLinkFits =+ !!alert.permalink &&+ !!alert.dataPermalink &&+ buildSlackLinkSection([+ { label: "View in Langfuse", url: alert.permalink },+ { label: secondaryLabel, url: alert.dataPermalink },+ ]).text.text.includes(alert.dataPermalink);const missingScoreLink =alert.view !== "observations" &&alert.permalink &&- !alert.dataPermalink &&+ !dataLinkFits &&(alert.severity === "ALERT" || alert.severity === "WARNING");return buildColoredAttachmentSlackMessage({color: severityVisual[alert.severity].color,@@ -30,7 +40,6 @@ export function buildMonitorAlertSlackMessage(timestamp: alert.timestamp,url: alert.permalink,secondaryUrl: alert.dataPermalink,- secondaryLabel:- alert.view === "observations" ? "View observations" : "View scores",+ secondaryLabel,});}diff --git a/packages/shared/src/features/monitors/processor/processor.ts b/packages/shared/src/features/monitors/processor/processor.tsindex e7cadd728e..0f857b03b1 100644--- a/packages/shared/src/features/monitors/processor/processor.ts+++ b/packages/shared/src/features/monitors/processor/processor.ts@@ -524,7 +524,7 @@ export function buildDataWindowPermalink(showAllEnvironments: "true",});const href = `${base}/project/${projectId}/scores?${query.toString()}`;- // Slack button URLs are limited to 3000 characters. Dropping predicates to+ // Slack section text is limited to 3000 characters. Dropping predicates to// shorten a link would show scores outside the evaluated query.return href.length <= 3000 ? href : undefined;}diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 5a24181239..d0d367e57e 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -180,6 +180,7 @@ export * from "./services/blockEvaluators";export * from "./services/getProjectAdminEmails";export * from "./services/SlackService";export * from "./services/buildColoredAttachmentSlackMessage";+export * from "./services/buildSlackLinkSection";export * from "./tableMappings";export * from "./otel";export * from "./datasets/executeWithDatasetServiceStrategy";diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.tsindex c01359b60b..92832830ac 100644--- a/packages/shared/src/server/services/SlackService.ts+++ b/packages/shared/src/server/services/SlackService.ts@@ -11,8 +11,9 @@ import { WebClient } from "@slack/web-api";import { InstallProvider } from "@slack/oauth";import { logger } from "../logger";import { env } from "../../env";-import { prisma } from "../../db";+import { prisma, type SlackIntegration } from "../../db";import { encrypt, decrypt } from "../../encryption";+import { isSlackActionConfig } from "../../domain/automations";/*** Error thrown by SlackService when a Slack API call fails.@@ -46,10 +47,122 @@ export interface SlackChannel {export interface GetChannelsResult {channels: SlackChannel[];- hasPrivateChannelAccess: boolean;nextCursor?: string;}+/** Same text as Slack's own channel_not_found, so private channels the viewer can't use look non-existent. */+export const SLACK_CHANNEL_NOT_FOUND_MESSAGE =+ 'Channel not found. The channel may not exist or is a private channel the bot has not been invited to. For private channels, invite the app with "/invite @Langfuse" in that channel.';++const SLACK_LOOKUP_TIMEOUT_MS = 5_000;++/**+ * getPrivateChannelViewerSlackUserId returns the installer's Slack user id when+ * the Langfuse user is the installer. Only they may see or use private channels.+ */+export function getPrivateChannelViewerSlackUserId(+ integration: Pick<+ SlackIntegration,+ "installerUserId" | "installerSlackUserId"+ >,+ userId: string,+) {+ return integration.installerUserId === userId+ ? integration.installerSlackUserId+ : null;+}++/**+ * getViewablePrivateSlackChannelIds returns the saved private channels the user+ * may see: only the installer, and only channels they are still a member of.+ * Fails closed (nothing viewable) if Slack can't be reached.+ */+export async function getViewablePrivateSlackChannelIds(params: {+ projectId: string;+ userId: string;+ actions: { config: unknown }[];+}): Promise<Set<string>> {+ const hasPrivateChannel = params.actions.some(+ ({ config }) => isSlackActionConfig(config) && config.isPrivate,+ );+ if (!hasPrivateChannel) return new Set();++ const integration = await prisma.slackIntegration.findUnique({+ where: { projectId: params.projectId },+ select: { installerUserId: true, installerSlackUserId: true },+ });+ const viewerSlackUserId =+ integration &&+ getPrivateChannelViewerSlackUserId(integration, params.userId);+ if (!viewerSlackUserId) return new Set();++ try {+ return await withSlackLookupTimeout(+ (async () => {+ const slackService = SlackService.getInstance();+ const client = await slackService.getWebClientForProject(+ params.projectId,+ );+ const { channels } = await slackService.getPrivateChannels(client, {+ slackUserId: viewerSlackUserId,+ includeArchived: true,+ });+ return new Set(channels.map((channel) => channel.id));+ })(),+ );+ } catch (error) {+ logger.warn("Failed to resolve viewable private Slack channels", {+ error,+ projectId: params.projectId,+ });+ return new Set();+ }+}++/**+ * withSlackLookupTimeout rejects after 5s. The Slack client retries for up to+ * 90s, so access lookups would otherwise hold requests; callers fail closed.+ */+async function withSlackLookupTimeout<T>(lookup: Promise<T>): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error("Slack lookup timed out")),+ SLACK_LOOKUP_TIMEOUT_MS,+ );+ });+ try {+ return await Promise.race([lookup, timeout]);+ } finally {+ clearTimeout(timer);+ }+}++/**+ * maskPrivateSlackChannel hides the name of a saved private channel from users+ * who may not see it. The channel id stays intact so unchanged saves keep working.+ */+export function maskPrivateSlackChannel<T extends { config: unknown }>(+ action: T,+ viewablePrivateChannelIds: Set<string>,+): T {+ const { config } = action;+ if (+ !isSlackActionConfig(config) ||+ !config.isPrivate ||+ viewablePrivateChannelIds.has(config.channelId)+ ) {+ return action;+ }+ return {+ ...action,+ config: {+ ...config,+ channelName: `Private Channel (…${config.channelId.slice(-3)})`,+ },+ };+}+/** SlackMessage is the Block Kit payload sent to Slack. */export interface SlackMessage {blocks: any[];@@ -78,6 +191,8 @@ export interface SlackMessageResponse {// Interface for Slack installation metadataexport interface SlackInstallationMetadata {projectId: string;+ /** Langfuse user who started the install */+ userId?: string;}/**@@ -91,7 +206,8 @@ function isSlackInstallationMetadata(metadata !== null &&"projectId" in metadata &&typeof metadata.projectId === "string" &&- metadata.projectId.length > 0+ metadata.projectId.length > 0 &&+ (!("userId" in metadata) || typeof metadata.userId === "string"));}@@ -163,12 +279,16 @@ export class SlackService {teamName: installation.team?.name!,botToken: encrypt(installation.bot?.token!),botUserId: installation.bot?.userId!,+ installerUserId: metadata.userId ?? null,+ installerSlackUserId: installation.user?.id ?? null,},update: {teamId: installation.team?.id!,teamName: installation.team?.name!,botToken: encrypt(installation.bot?.token!),botUserId: installation.bot?.userId!,+ installerUserId: metadata.userId ?? null,+ installerSlackUserId: installation.user?.id ?? null,},});@@ -381,7 +501,9 @@ export class SlackService {}/**- * Get channels accessible to the bot.+ * Get one page of public channels. Private channels come from getPrivateChannels:+ * the bot token lists every private channel it was invited to, including ones+ * the viewer isn't a member of.*/async getChannels(client: WebClient,@@ -390,7 +512,7 @@ export class SlackService {try {const { channels, nextCursor } = await this.getChannelsPage(client,- "public_channel,private_channel",+ "public_channel",cursor,);@@ -399,42 +521,120 @@ export class SlackService {hasNextPage: Boolean(nextCursor),});- return { channels, hasPrivateChannelAccess: true, nextCursor };- } catch (error: any) {- // we added `groups:read` scope after initial release, so older installations may not have it.- // Detect this case and fall back to fetching only public channels instead of failing completely.- const isMissingGroupsRead =- error?.data?.error === "missing_scope" &&- error?.data?.needed === "groups:read";-- if (isMissingGroupsRead) {- logger.info(- "Bot token lacks groups:read scope, falling back to public channels only",- );+ return { channels, nextCursor };+ } catch (error) {+ logger.error("Failed to fetch channels", { error });+ throw new Error(+ `Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,+ );+ }+ }- try {- const { channels, nextCursor } = await this.getChannelsPage(- client,- "public_channel",- cursor,- );-- return { channels, hasPrivateChannelAccess: false, nextCursor };- } catch (fallbackError) {- logger.error("Failed to fetch public channels fallback", {- error: fallbackError,+ /**+ * Get all private channels the bot is in, or with `slackUserId` only those that+ * user is also a member of. `hasPrivateChannelAccess` is false for installs+ * predating the `groups:read` scope.+ */+ async getPrivateChannels(+ client: WebClient,+ options: { slackUserId?: string; includeArchived?: boolean } = {},+ ) {+ const channels: SlackChannel[] = [];+ let cursor: string | undefined;+ try {+ do {+ const result = await client.users.conversations({+ types: "private_channel",+ exclude_archived: !options.includeArchived,+ limit: env.SLACK_PAGE_SIZE,+ cursor,+ ...(options.slackUserId ? { user: options.slackUserId } : {}),+ });+ for (const channel of result.channels ?? []) {+ channels.push({+ id: channel.id!,+ name: channel.name!,+ isPrivate: true,+ isMember: true,});- throw new Error(- `Failed to fetch channels: ${fallbackError instanceof Error ? fallbackError.message : "Unknown error"}`,- );}+ cursor = result.response_metadata?.next_cursor || undefined;+ } while (cursor);+ } catch (error: any) {+ if (error?.data?.error === "missing_scope") {+ return { channels: [], hasPrivateChannelAccess: false };}-- logger.error("Failed to fetch channels", { error });- throw new Error(- `Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,+ logger.error("Failed to fetch private Slack channels", { error });+ throw new SlackApiError(+ `Failed to fetch private channels: ${error instanceof Error ? error.message : "Unknown error"}`,+ error?.data?.error,);}+ return { channels, hasPrivateChannelAccess: true };+ }++ /**+ * Resolve whether the viewer may use `channel` (id or `#name`): `public` if it+ * is not a private channel the bot is in, `private` if the viewer shares it,+ * `denied` otherwise. Callers must treat `denied` exactly like a non-existent+ * channel so its existence isn't revealed.+ */+ async checkPrivateChannelAccess(params: {+ client: WebClient;+ channel: string;+ viewerSlackUserId: string | null;+ }): Promise<+ | { access: "public" }+ | { access: "private"; channel: SlackChannel }+ | { access: "denied" }+ > {+ const key = params.channel.trim().replace(/^#/, "");+ // Slack channel names are lowercase but name lookups ignore case.+ const name = key.toLowerCase();+ // Archived channels are included so they can't bypass the check.+ const botChannels = await this.getPrivateChannels(params.client, {+ includeArchived: true,+ });++ // Without groups:read, private channels look like public ones; only accept+ // channels Slack confirms are public.+ if (!botChannels.hasPrivateChannelAccess) {+ const info = params.channel.trim().startsWith("#")+ ? await withSlackLookupTimeout(+ this.findPublicChannelByName(params.client, name),+ ).catch(() => null)+ : await this.getChannelInfo(params.client, key);+ return info && !info.isPrivate+ ? { access: "public" }+ : { access: "denied" };+ }++ const privateChannel = botChannels.channels.find(+ (channel) => channel.id === key || channel.name.toLowerCase() === name,+ );+ if (!privateChannel) return { access: "public" };+ if (!params.viewerSlackUserId) return { access: "denied" };++ const viewerChannels = await this.getPrivateChannels(params.client, {+ slackUserId: params.viewerSlackUserId,+ includeArchived: true,+ });+ return viewerChannels.channels.some(+ (channel) => channel.id === privateChannel.id,+ )+ ? { access: "private", channel: privateChannel }+ : { access: "denied" };+ }++ private async findPublicChannelByName(client: WebClient, name: string) {+ let cursor: string | undefined;+ do {+ const page = await this.getChannels(client, cursor);+ const match = page.channels.find((channel) => channel.name === name);+ if (match) return match;+ cursor = page.nextCursor;+ } while (cursor);+ return null;}/**diff --git a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.tsindex c8d92f3318..e1a4cc55bc 100644--- a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts+++ b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.test.ts@@ -23,15 +23,15 @@ describe("buildColoredAttachmentSlackMessage", () => {expect(serialized).toContain(base.timestamp.toISOString());});- it("renders the title as a link and adds a deep-link button when a url is set", () => {+ it("renders the title as a link and adds a deep link when a url is set", () => {const serialized = JSON.stringify(buildColoredAttachmentSlackMessage(base).attachments![0].blocks,);expect(serialized).toContain(`<${base.url}|Something failed>`);- expect(serialized).toContain("View in Langfuse");+ expect(serialized).toContain(`<${base.url}|View in Langfuse>`);});- it("omits the link and button when no url is provided", () => {+ it("omits the deep links when no url is provided", () => {const { url: _url, ...noUrl } = base;const serialized = JSON.stringify(buildColoredAttachmentSlackMessage(noUrl).attachments![0].blocks,@@ -40,39 +40,45 @@ describe("buildColoredAttachmentSlackMessage", () => {expect(serialized).toContain("*Something failed*");});- it("renders a labeled secondary button after the primary when secondaryUrl is set", () => {+ it("renders a labeled secondary link after the primary when secondaryUrl is set", () => {const blocks = buildColoredAttachmentSlackMessage({...base,secondaryUrl: "https://cloud.langfuse.com/y?dateRange=1-2",secondaryLabel: "View traces",}).attachments![0].blocks!;- const actions = blocks.find((b: any) => b.type === "actions");- expect(actions.elements).toHaveLength(2);- expect(actions.elements[0]).toMatchObject({- type: "button",- text: { text: "View in Langfuse" },- url: base.url,- });- expect(actions.elements[1]).toMatchObject({- type: "button",- text: { text: "View traces" },- url: "https://cloud.langfuse.com/y?dateRange=1-2",- });+ const linkText: string = blocks.at(-1).text.text;+ expect(linkText.indexOf(`<${base.url}|View in Langfuse>`)).toBeLessThan(+ linkText.indexOf(+ "<https://cloud.langfuse.com/y?dateRange=1-2|View traces>",+ ),+ );});- it("defaults the secondary button label to 'View data'", () => {+ it("defaults the secondary link label to 'View data'", () => {const blocks = buildColoredAttachmentSlackMessage({...base,secondaryUrl: "https://cloud.langfuse.com/y?dateRange=1-2",}).attachments![0].blocks!;- const actions = blocks.find((b: any) => b.type === "actions");- expect(actions.elements[1].text.text).toBe("View data");+ expect(blocks.at(-1).text.text).toContain(+ "<https://cloud.langfuse.com/y?dateRange=1-2|View data>",+ );+ });++ // Slack rejects the message if a section's text exceeds 3000 characters.+ it("drops a secondary link that would overflow the section", () => {+ const blocks = buildColoredAttachmentSlackMessage({+ ...base,+ secondaryUrl: `https://cloud.langfuse.com/y?q=${"a".repeat(2990)}`,+ }).attachments![0].blocks!;+ const linkText: string = blocks.at(-1).text.text;+ expect(linkText.length).toBeLessThanOrEqual(3000);+ expect(linkText).toContain(`<${base.url}|View in Langfuse>`);+ expect(linkText).not.toContain("View data");});- it("omits the secondary button when secondaryUrl is absent", () => {+ it("omits the secondary link when secondaryUrl is absent", () => {const blocks =buildColoredAttachmentSlackMessage(base).attachments![0].blocks!;- const actions = blocks.find((b: any) => b.type === "actions");- expect(actions.elements).toHaveLength(1);+ expect(blocks.at(-1).text.text).not.toContain("View data");});});diff --git a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.tsindex 6f02d48419..762d6b4244 100644--- a/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts+++ b/packages/shared/src/server/services/buildColoredAttachmentSlackMessage.ts@@ -1,10 +1,11 @@import { slackifyMarkdown } from "slackify-markdown";import { escapeSlackMrkdwn, type SlackMessage } from "./SlackService";+import { buildSlackLinkSection } from "./buildSlackLinkSection";/*** buildColoredAttachmentSlackMessage renders a color-barred Slack Block Kit- * message (title, markdown body, timestamp, optional deep-link button). Shared+ * message (title, markdown body, timestamp, optional deep links). Shared* layout for monitor alerts and project notifications so both look identical;* callers own their severity→color mapping.*/@@ -17,12 +18,12 @@ export function buildColoredAttachmentSlackMessage(args: {/** contextText is an optional extra context element rendered next to the timestamp. */contextText?: string;/**- * secondaryUrl, when set alongside `url`, renders a second action button- * after "View in Langfuse" (e.g. a monitor alert's link to the breaching- * data). Absent by default so project notifications stay single-button.+ * secondaryUrl, when set alongside `url`, renders a second link after+ * "View in Langfuse" (e.g. a monitor alert's link to the breaching data).+ * Absent by default so project notifications stay single-link.*/secondaryUrl?: string;- /** secondaryLabel is the second button's label; defaults to "View data". */+ /** secondaryLabel is the second link's label; defaults to "View data". */secondaryLabel?: string;}): SlackMessage {const { color } = args;@@ -56,33 +57,17 @@ export function buildColoredAttachmentSlackMessage(args: {},...(args.url? [- {- type: "actions",- elements: [- {- type: "button",- text: {- type: "plain_text",- text: "View in Langfuse",- emoji: true,- },- url: args.url,- },- ...(args.secondaryUrl- ? [- {- type: "button",- text: {- type: "plain_text",- text: args.secondaryLabel ?? "View data",- emoji: true,- },- url: args.secondaryUrl,- },- ]- : []),- ],- },+ buildSlackLinkSection([+ { label: "View in Langfuse", url: args.url },+ ...(args.secondaryUrl+ ? [+ {+ label: args.secondaryLabel ?? "View data",+ url: args.secondaryUrl,+ },+ ]+ : []),+ ]),]: []),];diff --git a/packages/shared/src/server/services/buildSlackLinkSection.ts b/packages/shared/src/server/services/buildSlackLinkSection.tsnew file mode 100644index 0000000000..a0d49abc52--- /dev/null+++ b/packages/shared/src/server/services/buildSlackLinkSection.ts@@ -0,0 +1,20 @@+import { escapeSlackMrkdwn } from "./SlackService";++/** Slack rejects the whole message when a section's text exceeds this. */+const SLACK_SECTION_TEXT_MAX_LENGTH = 3000;++/**+ * buildSlackLinkSection renders deep links as an mrkdwn section. Slack sends an+ * interaction payload for URL buttons and shows an error unless the app+ * acknowledges it, so links are plain mrkdwn instead of buttons. Links that+ * would push the text over Slack's limit are dropped so the message still sends.+ */+export function buildSlackLinkSection(links: { label: string; url: string }[]) {+ let text = "";+ for (const { label, url } of links) {+ const link = `:arrow_right: *<${url}|${escapeSlackMrkdwn(label)}>*`;+ const next = text ? `${text} ${link}` : link;+ if (next.length <= SLACK_SECTION_TEXT_MAX_LENGTH) text = next;+ }+ return { type: "section", text: { type: "mrkdwn", text } };+}diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.tsindex 87ada21507..72a6796860 100644--- a/web/src/__tests__/server/automations-trpc.servertest.ts+++ b/web/src/__tests__/server/automations-trpc.servertest.ts@@ -1,8 +1,12 @@import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";+import type * as SharedServer from "@langfuse/shared/src/server";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { type Prisma, prisma } from "@langfuse/shared/src/db";-import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+} from "@langfuse/shared/src/server";import type { Session } from "next-auth";import { v4 } from "uuid";import {@@ -20,6 +24,71 @@ import {} from "@langfuse/shared/encryption";import { TRPCError } from "@trpc/server";+// Fake Slack workspace: the bot is in private channels "G_PRIVATE" and archived+// "G_ARCHIVED". Slack API calls are faked; the access logic is real.+const fakeSlack = vi.hoisted(() => ({+ installerChannelIds: ["G_PRIVATE", "G_ARCHIVED"],+ missingScope: false,+}));+vi.mock("@langfuse/shared/src/server", async () => {+ const actual = await vi.importActual<typeof SharedServer>(+ "@langfuse/shared/src/server",+ );+ const channels = [+ { id: "C123456", name: "general", is_private: false },+ { id: "G_PRIVATE", name: "secret-plans", is_private: true },+ {+ id: "G_ARCHIVED",+ name: "old-secrets",+ is_private: true,+ is_archived: true,+ },+ ];+ const client = {+ users: {+ conversations: async (args: {+ user?: string;+ exclude_archived?: boolean;+ }) => {+ if (fakeSlack.missingScope) {+ throw Object.assign(new Error("missing_scope"), {+ data: { error: "missing_scope" },+ });+ }+ return {+ ok: true,+ channels: channels.filter(+ (channel) =>+ channel.is_private &&+ !(args.exclude_archived && channel.is_archived) &&+ (!args.user ||+ (args.user === "U_INSTALLER" &&+ fakeSlack.installerChannelIds.includes(channel.id))),+ ),+ };+ },+ },+ conversations: {+ info: async ({ channel }: { channel: string }) => {+ const found = channels.find(({ id }) => id === channel);+ if (!found) throw new Error("channel_not_found");+ return { ok: true, channel: found };+ },+ },+ };+ const slackService = {+ getWebClientForProject: async () => client,+ getPrivateChannels: actual.SlackService.prototype.getPrivateChannels,+ checkPrivateChannelAccess:+ actual.SlackService.prototype.checkPrivateChannelAccess,+ getChannelInfo: actual.SlackService.prototype.getChannelInfo,+ };+ // Patched on the real class so calls from inside the shared module see it too.+ actual.SlackService.getInstance = () =>+ slackService as unknown as SharedServer.SlackService;+ return actual;+});+const __orgIds: string[] = [];async function prepare() {@@ -1152,6 +1221,147 @@ describe("automations trpc", () => {});});+ describe("Slack private channels", () => {+ const slackAutomationInput = (projectId: string, channelId: string) => ({+ projectId,+ name: "Slack Automation",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "SLACK" as const,+ actionConfig: {+ type: "SLACK" as const,+ channelId,+ channelName: "secret-plans",+ },+ });++ const prepareWithInstaller = async (installerUserId: string) => {+ const prepared = await prepare();+ await prisma.slackIntegration.create({+ data: {+ projectId: prepared.project.id,+ teamId: "T123456",+ teamName: "Test Team",+ botToken: encrypt("xoxb-test-token"),+ botUserId: "U123456",+ installerUserId,+ installerSlackUserId: "U_INSTALLER",+ },+ });+ const otherUserCaller = appRouter.createCaller({+ ...createInnerTRPCContext({+ session: {+ ...prepared.session,+ user: { ...prepared.session.user!, id: "user-2" },+ },+ headers: {},+ }),+ prisma,+ });+ return { ...prepared, otherUserCaller };+ };++ beforeEach(() => {+ fakeSlack.installerChannelIds = ["G_PRIVATE", "G_ARCHIVED"];+ fakeSlack.missingScope = false;+ });++ it("rejects private channels the user can't use exactly like non-existent channels", async () => {+ const { project, caller } = await prepareWithInstaller("someone-else");+ const errorFor = (channelId: string) =>+ caller.automations+ .createAutomation(slackAutomationInput(project.id, channelId))+ .catch((error: Error) => error.message);++ for (const channelId of ["G_PRIVATE", "G_ARCHIVED", "C_MISSING"]) {+ expect(await errorFor(channelId)).toBe(SLACK_CHANNEL_NOT_FOUND_MESSAGE);+ }+ // Typed names are rejected before any lookup.+ expect(await errorFor("#secret-plans")).toBe(+ await errorFor("#does-not-exist"),+ );+ });++ it("fails closed for private channels on installs without groups:read", async () => {+ const { project, caller } = await prepareWithInstaller("user-1");+ fakeSlack.missingScope = true;++ await expect(+ caller.automations.createAutomation(+ slackAutomationInput(project.id, "G_PRIVATE"),+ ),+ ).rejects.toThrow(SLACK_CHANNEL_NOT_FOUND_MESSAGE);+ const created = await caller.automations.createAutomation(+ slackAutomationInput(project.id, "C123456"),+ );+ expect(created.action.config).toMatchObject({+ channelName: "general",+ isPrivate: false,+ });+ });++ it("masks a saved private channel name for everyone but the installer", async () => {+ const { project, caller, otherUserCaller } =+ await prepareWithInstaller("user-1");++ const created = await caller.automations.createAutomation(+ slackAutomationInput(project.id, "G_PRIVATE"),+ );+ expect(created.action.config).toMatchObject({+ channelId: "G_PRIVATE",+ channelName: "secret-plans",+ isPrivate: true,+ });++ const [otherList, otherSingle] = await Promise.all([+ otherUserCaller.automations.getAutomations({ projectId: project.id }),+ otherUserCaller.automations.getAutomation({+ projectId: project.id,+ automationId: created.automation.id,+ }),+ ]);+ expect(JSON.stringify([otherList, otherSingle])).not.toContain(+ "secret-plans",+ );+ expect(otherSingle.action.config).toMatchObject({+ channelId: "G_PRIVATE",+ channelName: "Private Channel (…ATE)",+ });++ // Saving the masked config unchanged keeps the real channel.+ await otherUserCaller.automations.updateAutomation({+ ...slackAutomationInput(project.id, "G_PRIVATE"),+ automationId: created.automation.id,+ name: "Renamed",+ actionConfig: {+ ...(otherSingle.action.config as { channelId: string }),+ type: "SLACK",+ channelName: "Private Channel (…ATE)",+ },+ });+ const installerView = await caller.automations.getAutomation({+ projectId: project.id,+ automationId: created.automation.id,+ });+ expect(installerView.action.config).toMatchObject({+ channelName: "secret-plans",+ isPrivate: true,+ });++ // The installer loses the name once they leave the channel.+ fakeSlack.installerChannelIds = [];+ const afterLeaving = await caller.automations.getAutomation({+ projectId: project.id,+ automationId: created.automation.id,+ });+ expect(afterLeaving.action.config).toMatchObject({+ channelName: "Private Channel (…ATE)",+ });+ });+ });+describe("automations.updateAutomation", () => {it("should update an existing automation", async () => {const { project, caller } = await prepare();diff --git a/web/src/__tests__/server/slack-integration.servertest.ts b/web/src/__tests__/server/slack-integration.servertest.tsindex 2d7d3da248..cd1b120e25 100644--- a/web/src/__tests__/server/slack-integration.servertest.ts+++ b/web/src/__tests__/server/slack-integration.servertest.ts@@ -1,11 +1,16 @@import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";+import type * as SharedServer from "@langfuse/shared/src/server";import type { Mock } from "vitest";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 {+ createOrgProjectAndApiKey,+ SlackApiError,+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";// Mock SlackService@@ -22,6 +27,55 @@ vi.mock("@langfuse/shared/src/server", async () => {const __orgIds: string[] = [];let mockSlackService: any;+// Bot is in both private channels; the installer's Slack user only in the first.+const INSTALLER_SLACK_USER_ID = "U_INSTALLER";+const installerPrivateChannel = {+ id: "G_SHARED",+ name: "installer-private",+ isPrivate: true,+ isMember: true,+};+const otherPrivateChannel = {+ id: "G_OTHER",+ name: "other-private",+ isPrivate: true,+ isMember: true,+};++const createSlackClient = () => ({+ auth: { test: vi.fn() },+ users: {+ conversations: vi.fn(async ({ user }: { user?: string }) => {+ if (!user)+ return {+ ok: true,+ channels: toSlackApi([installerPrivateChannel, otherPrivateChannel]),+ };+ if (user === INSTALLER_SLACK_USER_ID)+ return { ok: true, channels: toSlackApi([installerPrivateChannel]) };+ return { ok: true, channels: [] };+ }),+ },+});++const toSlackApi = (channels: { id: string; name: string }[]) =>+ channels.map(({ id, name }) => ({ id, name, is_private: true }));++const createIntegration = (+ projectId: string,+ installer: { installerUserId: string; installerSlackUserId: string } | null,+) =>+ prisma.slackIntegration.create({+ data: {+ projectId,+ teamId: "T123456",+ teamName: "Test Team",+ botToken: encrypt("xoxb-test-token"),+ botUserId: "U123456",+ ...installer,+ },+ });+const prepare = async () => {const { project, org } = await createOrgProjectAndApiKey();@@ -77,7 +131,11 @@ describe("Slack Integration", () => {// Import mocked SlackServiceconst { SlackService } = await import("@langfuse/shared/src/server");- // Create mock service instance+ const { SlackService: ActualSlackService } = await vi.importActual<+ typeof SharedServer+ >("@langfuse/shared/src/server");++ // Slack API calls are mocked; private channel access logic runs for real.mockSlackService = {getWebClientForProject: vi.fn(),sendMessage: vi.fn(),@@ -85,12 +143,23 @@ describe("Slack Integration", () => {getChannelInfo: vi.fn(),validateClient: vi.fn(),deleteIntegration: vi.fn(),+ getPrivateChannels: ActualSlackService.prototype.getPrivateChannels,+ checkPrivateChannelAccess:+ ActualSlackService.prototype.checkPrivateChannelAccess,+ findPublicChannelByName:+ ActualSlackService.prototype["findPublicChannelByName"],};// Setup the getInstance mock to return our mock service(SlackService.getInstance as Mock).mockReturnValue(mockSlackService);});+ beforeEach(() => {+ mockSlackService.getWebClientForProject.mockResolvedValue(+ createSlackClient(),+ );+ });+afterAll(async () => {await prisma.organization.deleteMany({where: {@@ -192,17 +261,10 @@ describe("Slack Integration", () => {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({channels: mockChannels,- hasPrivateChannelAccess: true,});const { caller, project } = await prepare();@@ -222,9 +284,10 @@ describe("Slack Integration", () => {projectId: project.id,});+ // Without a recorded installer, the viewer is asked to re-authenticate.expect(result).toMatchObject({channels: mockChannels,- hasPrivateChannelAccess: true,+ hasPrivateChannelAccess: false,teamId: "T123456",teamName: "Test Team",});@@ -234,6 +297,34 @@ describe("Slack Integration", () => {expect(result).not.toHaveProperty("botToken");});+ it("lists private channels only for the installer, limited to ones they are a member of", async () => {+ mockSlackService.getChannels.mockResolvedValue({+ channels: [{ id: "C123456", name: "general", isPrivate: false }],+ });+ const { caller, project } = await prepare();+ const integration = await createIntegration(project.id, {+ installerUserId: "user-1",+ installerSlackUserId: INSTALLER_SLACK_USER_ID,+ });++ const asInstaller = await caller.slack.getChannels({+ projectId: project.id,+ });+ expect(asInstaller.channels.map((channel) => channel.name)).toEqual([+ "general",+ "installer-private",+ ]);++ await prisma.slackIntegration.update({+ where: { id: integration.id },+ data: { installerUserId: "another-user" },+ });+ const asOtherUser = await caller.slack.getChannels({+ projectId: project.id,+ });+ expect(JSON.stringify(asOtherUser)).not.toContain("private");+ });+it("should throw NOT_FOUND for missing integration", async () => {const { caller, project } = await prepare();@@ -270,7 +361,7 @@ describe("Slack Integration", () => {describe("sendTestMessage", () => {it("should send test message successfully", async () => {- const mockClient = { auth: { test: vi.fn() } };+ const mockClient = createSlackClient();mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);mockSlackService.sendMessage.mockResolvedValue({messageTs: "1234567890.123456",@@ -315,7 +406,7 @@ describe("Slack Integration", () => {});it("should resolve channel info for manually-typed channel names", async () => {- const mockClient = { auth: { test: vi.fn() } };+ const mockClient = createSlackClient();mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);mockSlackService.sendMessage.mockResolvedValue({messageTs: "1234567890.123456",@@ -379,8 +470,93 @@ describe("Slack Integration", () => {});});+ it("treats private channels the user can't use exactly like non-existent channels, without posting", async () => {+ const { caller, project } = await prepare();+ const integration = await createIntegration(project.id, {+ installerUserId: "user-1",+ installerSlackUserId: INSTALLER_SLACK_USER_ID,+ });+ mockSlackService.sendMessage.mockReset();+ mockSlackService.sendMessage.mockImplementation(+ async ({ channelId }: { channelId: string }) => {+ if (channelId !== installerPrivateChannel.id)+ throw new SlackApiError("not found", "channel_not_found");+ return { messageTs: "1234567890.123456", channel: channelId };+ },+ );+ const errorFor = (channelId: string) =>+ caller.slack+ .sendTestMessage({ projectId: project.id, channelId })+ .then(+ () => "sent",+ (error: TRPCError) => error.message,+ );++ // The installer may use private channels they are a member of.+ const result = await caller.slack.sendTestMessage({+ projectId: project.id,+ channelId: "#installer-private",+ });+ expect(result.channelInfo).toMatchObject({+ id: installerPrivateChannel.id,+ isPrivate: true,+ });+ expect(await errorFor("#other-private")).toBe(+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+ );++ await prisma.slackIntegration.update({+ where: { id: integration.id },+ data: { installerUserId: "another-user" },+ });+ for (const channelId of [+ "#installer-private",+ " #Installer-Private",+ installerPrivateChannel.id,+ "#does-not-exist",+ ]) {+ expect(await errorFor(channelId)).toBe(+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+ );+ }+ // Only the installer's channel and the non-existent one reached Slack.+ expect(mockSlackService.sendMessage).toHaveBeenCalledTimes(2);+ });++ it("on installs without groups:read, accepts only typed names of public channels", async () => {+ const client = createSlackClient();+ client.users.conversations.mockRejectedValue(+ Object.assign(new Error("missing_scope"), {+ data: { error: "missing_scope" },+ }),+ );+ mockSlackService.getWebClientForProject.mockResolvedValue(client);+ mockSlackService.getChannels.mockResolvedValue({+ channels: [{ id: "C123456", name: "general", isPrivate: false }],+ });+ mockSlackService.sendMessage.mockReset();+ mockSlackService.sendMessage.mockResolvedValue({+ messageTs: "1234567890.123456",+ channel: "C123456",+ });+ const { caller, project } = await prepare();+ await createIntegration(project.id, null);++ await caller.slack.sendTestMessage({+ projectId: project.id,+ channelId: "#General",+ });+ await expect(+ caller.slack.sendTestMessage({+ projectId: project.id,+ channelId: "#installer-private",+ }),+ ).rejects.toThrow(SLACK_CHANNEL_NOT_FOUND_MESSAGE);+ expect(mockSlackService.sendMessage).toHaveBeenCalledTimes(1);+ });+it("should create audit log entry", async () => {- const mockClient = { auth: { test: vi.fn() } };+ const mockClient = createSlackClient();mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);mockSlackService.sendMessage.mockResolvedValue({messageTs: "1234567890.123456",@@ -578,7 +754,6 @@ describe("Slack Integration", () => {channels: [{ id: "C123456", name: "general", isPrivate: false, isMember: true },],- hasPrivateChannelAccess: true,});mockSlackService.sendMessage.mockResolvedValue({messageTs: "1234567890.123456",diff --git a/web/src/features/automations/components/actions/SlackActionForm.tsx b/web/src/features/automations/components/actions/SlackActionForm.tsxindex 43fc892fb6..09d84c9a7c 100644--- a/web/src/features/automations/components/actions/SlackActionForm.tsx+++ b/web/src/features/automations/components/actions/SlackActionForm.tsx@@ -8,7 +8,7 @@ import {FormMessage,} from "@/src/components/ui/form";import { type UseFormReturn } from "react-hook-form";-import { type ActionDomain } from "@langfuse/shared";+import { type ActionDomain, isSlackActionConfig } from "@langfuse/shared";import { api } from "@/src/utils/api";import {SlackConnectionCard,@@ -30,12 +30,23 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({form,disabled,projectId,+ action,}) => {const initialChannelId = form.getValues("slack.channelId") as string;const initialChannelName = form.getValues("slack.channelName") as string;+ // Saved private channels aren't in the list for users who can't see them,+ // so the lock icon has to come from the saved config.+ const initialIsPrivate =+ isSlackActionConfig(action?.config) &&+ action.config.channelId === initialChannelId &&+ action.config.isPrivate;const [selectedChannel, setSelectedChannel] = useState<SlackChannel | null>(initialChannelId && initialChannelName- ? { id: initialChannelId, name: initialChannelName }+ ? {+ id: initialChannelId,+ name: initialChannelName,+ isPrivate: initialIsPrivate,+ }: null,);@@ -101,12 +112,14 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({</div></FormControl><FormDescription>- Select the Slack channel where notifications will be sent. For- private channels, invite the app first with{" "}+ Select the Slack channel where notifications will be sent.+ Private channels appear only for the person who connected+ Slack, and only if both they and the app are members. Invite+ the app with{" "}<code className="bg-muted rounded px-1 py-0.5">/invite @Langfuse- </code>{" "}- in that channel.+ </code>+ .</FormDescription><FormMessage /></FormItem>diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsxindex 36ef409303..3b66bd42a4 100644--- a/web/src/features/automations/components/automationForm.tsx+++ b/web/src/features/automations/components/automationForm.tsx@@ -75,7 +75,9 @@ const promptEventActionDefaults: string[] = ["created", "updated", "deleted"];/** projectNotificationName derives the auto-generated channel name from the destination — the name field is hidden for this source. */const projectNotificationName = (data: FormValues): string => {- if (data.actionType === "SLACK") return `Slack #${data.slack.channelName}`;+ // Automation names are visible to every project member, so they must not+ // carry Slack channel names (private ones are only for channel members).+ if (data.actionType === "SLACK") return "Slack";if (data.actionType === "WEBHOOK") {try {return `Webhook ${new URL(data.webhook.url).hostname}`;diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.tsindex 00ec091a5c..71e3f756ca 100644--- a/web/src/features/automations/server/router.ts+++ b/web/src/features/automations/server/router.ts@@ -20,11 +20,14 @@ import {getAutomations,getAutomationById,getConsecutiveAutomationFailures,+ getViewablePrivateSlackChannelIds,+ maskPrivateSlackChannel,logger,} from "@langfuse/shared/src/server";import { generateWebhookSecret, encrypt } from "@langfuse/shared/encryption";import { processWebhookActionConfig } from "./webhookHelpers";import { processGitHubDispatchActionConfig } from "./githubDispatchHelpers";+import { maskActionForViewer, processSlackActionConfig } from "./slackHelpers";import { updateTriggerEventActions } from "./automationService";import { TRPCError } from "@trpc/server";import { auditLog } from "@/src/features/audit-logs/server";@@ -160,10 +163,24 @@ export const automationsRouter = createTRPCRouter({scope: "automations:read",});- const automations = await getAutomations({+ const allAutomations = await getAutomations({projectId: input.projectId,eventSource: input.eventSource,});+ const viewablePrivateChannelIds = await getViewablePrivateSlackChannelIds(+ {+ projectId: input.projectId,+ userId: ctx.session.user.id,+ actions: allAutomations.map((automation) => automation.action),+ },+ );+ const automations = allAutomations.map((automation) => ({+ ...automation,+ action: maskPrivateSlackChannel(+ automation.action,+ viewablePrivateChannelIds,+ ),+ }));// Project-notification channels are managed from project settings, not// the general Automations UI. When no eventSource is requested (the@@ -206,7 +223,14 @@ export const automationsRouter = createTRPCRouter({});}- return automation;+ return {+ ...automation,+ action: await maskActionForViewer({+ action: automation.action,+ projectId: input.projectId,+ userId: ctx.session.user.id,+ }),+ };}),// Get execution history for an automation@@ -293,18 +317,11 @@ export const automationsRouter = createTRPCRouter({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 },+ finalActionConfig = await processSlackActionConfig({+ actionConfig: input.actionConfig,+ projectId: input.projectId,+ userId: ctx.session.user.id,});-- if (!slackIntegration) {- throw new TRPCError({- code: "NOT_FOUND",- message:- "Slack integration not found. Please connect your Slack workspace first.",- });- }} else if (input.actionType === "GITHUB_DISPATCH") {const githubResult = await processGitHubDispatchActionConfig({actionConfig: input.actionConfig,@@ -367,7 +384,11 @@ export const automationsRouter = createTRPCRouter({logger.info(`Created automation ${trigger.id} for action ${action.id}`);return {- action: convertActionToDomain(action),+ action: await maskActionForViewer({+ action: convertActionToDomain(action),+ projectId: input.projectId,+ userId: ctx.session.user.id,+ }),trigger,automation,webhookSecret: newUnencryptedWebhookSecret, // Return webhook secret at top level for one-time display@@ -406,18 +427,12 @@ export const automationsRouter = createTRPCRouter({});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 },+ finalActionConfig = await processSlackActionConfig({+ actionConfig: input.actionConfig,+ existingActionConfig: existingAutomation.action.config,+ projectId: input.projectId,+ userId: ctx.session.user.id,});-- if (!slackIntegration) {- throw new TRPCError({- code: "NOT_FOUND",- message:- "Slack integration not found. Please connect your Slack workspace first.",- });- }} else if (input.actionType === "GITHUB_DISPATCH") {const githubResult = await processGitHubDispatchActionConfig({actionConfig: input.actionConfig,@@ -495,7 +510,11 @@ export const automationsRouter = createTRPCRouter({});return {- action: convertActionToDomain(action),+ action: await maskActionForViewer({+ action: convertActionToDomain(action),+ projectId: input.projectId,+ userId: ctx.session.user.id,+ }),trigger,automation,};diff --git a/web/src/features/automations/server/slackHelpers.ts b/web/src/features/automations/server/slackHelpers.tsnew file mode 100644index 0000000000..77cdc1ad55--- /dev/null+++ b/web/src/features/automations/server/slackHelpers.ts@@ -0,0 +1,127 @@+import {+ type ActionCreate,+ type ActionDomain,+ type SlackActionConfig,+ isSlackActionConfig,+} from "@langfuse/shared";+import {+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+ SlackService,+ getPrivateChannelViewerSlackUserId,+ getViewablePrivateSlackChannelIds,+ maskPrivateSlackChannel,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { TRPCError } from "@trpc/server";++/**+ * processSlackActionConfig resolves the target channel to an id and records+ * whether it is private. Channels that don't exist and private channels the+ * user may not use fail identically, so saving can't reveal a private channel.+ */+export async function processSlackActionConfig({+ actionConfig,+ existingActionConfig,+ projectId,+ userId,+}: {+ actionConfig: ActionCreate;+ existingActionConfig?: ActionDomain["config"];+ projectId: string;+ userId: string;+}): Promise<SlackActionConfig> {+ if (actionConfig.type !== "SLACK") {+ throw new Error("Action type is not SLACK");+ }++ const integration = await prisma.slackIntegration.findUnique({+ where: { projectId },+ });+ if (!integration) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message:+ "Slack integration not found. Please connect your Slack workspace first.",+ });+ }++ // Keep the stored channel fields so a masked name is never written back.+ if (+ isSlackActionConfig(existingActionConfig) &&+ existingActionConfig.channelId === actionConfig.channelId+ ) {+ return {+ ...actionConfig,+ channelName: existingActionConfig.channelName,+ isPrivate: existingActionConfig.isPrivate,+ };+ }++ // Rejected before any lookup so the response can't differ between private and+ // missing channels; the test message resolves a typed #name to an id.+ if (actionConfig.channelId.startsWith("#")) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Send a test message to this channel before saving so it can be resolved.",+ });+ }++ const slackService = SlackService.getInstance();+ const client = await slackService.getWebClientForProject(projectId);+ const access = await slackService.checkPrivateChannelAccess({+ client,+ channel: actionConfig.channelId,+ viewerSlackUserId: getPrivateChannelViewerSlackUserId(integration, userId),+ });++ if (access.access === "denied") throwChannelNotFound();+ if (access.access === "private") {+ return {+ ...actionConfig,+ channelId: access.channel.id,+ channelName: access.channel.name,+ isPrivate: true,+ };+ }++ const channel = await slackService.getChannelInfo(+ client,+ actionConfig.channelId,+ );+ // A private result here is one the access check didn't vouch for.+ if (!channel || channel.isPrivate) throwChannelNotFound();+ return {+ ...actionConfig,+ channelId: channel.id,+ channelName: channel.name,+ isPrivate: false,+ };+}++/** maskActionForViewer masks a saved private channel name the user may not see. */+export async function maskActionForViewer<T extends { config: unknown }>({+ action,+ projectId,+ userId,+}: {+ action: T;+ projectId: string;+ userId: string;+}) {+ return maskPrivateSlackChannel(+ action,+ await getViewablePrivateSlackChannelIds({+ projectId,+ userId,+ actions: [action],+ }),+ );+}++function throwChannelNotFound(): never {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: SLACK_CHANNEL_NOT_FOUND_MESSAGE,+ });+}diff --git a/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx b/web/src/features/notifications/components/ProjectNotificationChannelsList.tsxindex 5f36a5b4df..ed641dda0b 100644--- a/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx+++ b/web/src/features/notifications/components/ProjectNotificationChannelsList.tsx@@ -8,7 +8,10 @@ import { type AutomationDomain } from "@langfuse/shared";const destinationLabel = (automation: AutomationDomain): string => {if (automation.action.type === "SLACK") {const config = automation.action.config;- return config.type === "SLACK" ? `Slack #${config.channelName}` : "Slack";+ if (config.type !== "SLACK") return "Slack";+ return config.isPrivate+ ? `Slack ${config.channelName}`+ : `Slack #${config.channelName}`;}if (automation.action.type === "WEBHOOK") {const config = automation.action.config;diff --git a/web/src/features/slack/AGENTS.md b/web/src/features/slack/AGENTS.mdnew file mode 100644index 0000000000..3c8597d29d--- /dev/null+++ b/web/src/features/slack/AGENTS.md@@ -0,0 +1,4 @@+# Slack++- Use a link instead of a `LinkButton` for Slack messages as buttons need to follow the Slack user interaction guidelines to stay Slack marketplace compliant: https://docs.slack.dev/interactivity/handling-user-interaction/+- Private channels can't be exposed to anyone who is not in the private channel. E.g. if the app is in channel A but the user who connected the app isn't, then the user shouldn't see channel Adiff --git a/web/src/features/slack/SlackIntegrationPage.tsx b/web/src/features/slack/SlackIntegrationPage.tsxindex 025072be6b..7f7e03fa7b 100644--- a/web/src/features/slack/SlackIntegrationPage.tsx+++ b/web/src/features/slack/SlackIntegrationPage.tsx@@ -7,6 +7,7 @@ import {type SlackChannel,} from "@/src/features/slack/components/ChannelSelector";import { SlackTestMessageButton } from "@/src/features/slack/components/SlackTestMessageButton";+import { PrivateChannelsInfoTooltip } from "@/src/features/slack/components/PrivateChannelsInfoTooltip";import { useSlackIntegration } from "@/src/features/slack/useSlackIntegration";import { useRouter } from "next/router";import { useState, useEffect } from "react";@@ -108,7 +109,10 @@ export default function SlackIntegrationPage() {</CardHeader><CardContent className="space-y-4"><div>- <h4 className="mb-2 text-sm font-bold">Select Test Channel</h4>+ <div className="mb-2 flex items-center gap-1.5">+ <h4 className="text-sm font-bold">Select Test Channel</h4>+ <PrivateChannelsInfoTooltip />+ </div><div className="max-w-md"><ChannelSelectorprojectId={projectId}@@ -188,11 +192,13 @@ export default function SlackIntegrationPage() {{!selectedChannel && (<div className="text-muted-foreground text-sm">Select a channel above to view its details and test message- delivery. For private channels, invite the app first with{" "}+ delivery. Private channels appear only for the person who+ connected Slack, and only if both they and the app are+ members. Invite the app with{" "}<code className="bg-muted rounded px-1 py-0.5">/invite @Langfuse- </code>{" "}- in that channel.+ </code>+ .</div>)}</CardContent>diff --git a/web/src/features/slack/components/ChannelSelector.tsx b/web/src/features/slack/components/ChannelSelector.tsxindex c61090e593..8de8ad322b 100644--- a/web/src/features/slack/components/ChannelSelector.tsx+++ b/web/src/features/slack/components/ChannelSelector.tsx@@ -1,55 +1,71 @@-import React, { useState, useMemo, useCallback, useEffect } from "react";-import { RefreshCw, Search, Hash, Lock, AlertTriangle } from "@langfuse/icons";-import { Button } from "@/src/components/ui/button";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";-import { Alert } from "@/src/components/design-system/Alert/Alert";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "@/src/components/ui/command";-import { useVirtualizer } from "@tanstack/react-virtual";+import React, { useState, useMemo, useEffect } from "react";import { api, reportNonTrpcError } from "@/src/utils/api";import { env } from "@/src/env.mjs";import { type SlackChannel } from "@langfuse/shared/src/server";-import { cn } from "@/src/utils/tailwind";+import {+ ChannelSelectorView,+ type ChannelSelectorViewProps,+} from "@/src/features/slack/components/ChannelSelectorView/ChannelSelectorView";export type { SlackChannel };-/**- * Props for the ChannelSelector component- */-interface ChannelSelectorProps {+type ChannelSelectorProps = {/** Project ID for the Slack integration */projectId: string;- /** Currently selected channel ID */- selectedChannelId?: string;- /** Full channel object for display when the ID isn't in the fetched list (e.g. manual entry) */- selectedChannel?: SlackChannel | null;- /** 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;-}+} & Omit<+ ChannelSelectorViewProps,+ | "channelsData"+ | "isLoading"+ | "hasError"+ | "isRefreshing"+ | "onRefresh"+ | "onReauthenticate"+>;-const ITEM_HEIGHT = 32;const MAX_SLACK_CHANNEL_PAGES = 20;+/**+ * ChannelSelector loads the project's Slack channels and renders them in+ * ChannelSelectorView.+ */+export const ChannelSelector: React.FC<ChannelSelectorProps> = ({+ projectId,+ ...viewProps+}) => {+ const [isRefreshing, setIsRefreshing] = useState(false);+ const { channelsData, isLoadingChannels, error, refetchChannels } =+ useSlackChannels(projectId);++ const handleRefresh = async () => {+ setIsRefreshing(true);+ try {+ await refetchChannels();+ } finally {+ setIsRefreshing(false);+ }+ };++ const handleReauthenticate = () => {+ window.open(+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/public/slack/install?projectId=${projectId}`,+ "slack-reauth",+ "width=600,height=700",+ );+ };++ return (+ <ChannelSelectorView+ {...viewProps}+ channelsData={channelsData}+ isLoading={isLoadingChannels}+ hasError={!!error}+ isRefreshing={isRefreshing}+ onRefresh={handleRefresh}+ onReauthenticate={handleReauthenticate}+ />+ );+};+const useSlackChannels = (projectId: string) => {const {data: channelsPages,@@ -103,328 +119,3 @@ const useSlackChannels = (projectId: string) => {refetchChannels,};};--/**- * 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.- * Items are virtualized with @tanstack/react-virtual to handle large channel lists (~5k).- *- * @param projectId - The project ID for the Slack integration- * @param selectedChannelId - Currently selected channel ID- * @param selectedChannel - Full channel object for display when the ID isn't in the fetched list (e.g. manual entry)- * @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,- selectedChannel: selectedChannelProp,- 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);- const [scrollNode, setScrollNode] = useState<HTMLDivElement | null>(null);- const trimmedSearch = searchValue.trim();- const effectiveName = trimmedSearch.replace(/^#/, "");-- // Get available channels- const { channelsData, isLoadingChannels, error, refetchChannels } =- useSlackChannels(projectId);-- // 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 (effectiveName) {- const searchTerm = effectiveName.toLowerCase();- 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, effectiveName]);-- const virtualizer = useVirtualizer({- count: filteredChannels.length,- getScrollElement: () => scrollNode,- estimateSize: () => ITEM_HEIGHT,- overscan: 20,- });-- // Get selected channel info — fall back to the prop for manual entries- const selectedChannel = useMemo(() => {- if (!selectedChannelId) return null;- const fromList = channelsData?.channels?.find(- (channel) => channel.id === selectedChannelId,- );- return fromList ?? selectedChannelProp ?? null;- }, [selectedChannelId, channelsData?.channels, selectedChannelProp]);-- const selectAndClose = useCallback(- (channel: SlackChannel) => {- onChannelSelect(channel);- setOpen(false);- setSearchValue("");- },- [onChannelSelect],- );-- const handleSelectByName = useCallback(() => {- const name = searchValue.trim().replace(/^#/, "");- if (!name) return;- selectAndClose({- id: `#${name}`,- name,- isPrivate: false,- isMember: false,- });- }, [searchValue, selectAndClose]);-- useEffect(() => {- if (scrollNode) {- scrollNode.scrollTop = 0;- }- }, [effectiveName, scrollNode]);-- // Render channel item- const renderChannelItem = (channel: SlackChannel) => (- <div className="flex w-full items-center gap-2">- {channel.isPrivate ? (- <Lock size="base" color="muted" />- ) : (- <Hash size="base" color="muted" />- )}- <span className="flex-1 truncate" title={channel.name}>- {channel.name}- </span>- </div>- );-- const hasExactMatch = filteredChannels.some(- (channel) => channel.name.toLowerCase() === effectiveName.toLowerCase(),- );- const canUseTypedName = effectiveName.length > 0 && !hasExactMatch;-- return (- <div className="space-y-2">- <div className="flex items-center gap-2">- <Popover- open={open}- onOpenChange={(newOpen) => {- setOpen(newOpen);- if (!newOpen) {- setSearchValue("");- }- }}- >- <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- size="base"- color="default"- __rawClassName="ml-2 opacity-50"- />- </Button>- </PopoverTrigger>- <PopoverContent className="w-full p-0" align="start">- <Command shouldFilter={false}>- <CommandInput- placeholder="Search channels..."- value={searchValue}- onValueChange={setSearchValue}- />- <CommandList ref={setScrollNode}>- {canUseTypedName && (- <CommandGroup className="p-0">- <CommandItem- value={`use-${effectiveName}`}- onSelect={handleSelectByName}- className="cursor-pointer"- >- <Hash size="base" color="muted" />- <span- className="flex-1 truncate"- title={`Use " ${effectiveName} "`}- >- Use "{effectiveName}"- </span>- </CommandItem>- </CommandGroup>- )}- {!isLoadingChannels &&- !canUseTypedName &&- filteredChannels.length === 0 && (- <CommandEmpty>No channels available.</CommandEmpty>- )}- <CommandGroup- className="p-0"- style={{- height: virtualizer.getTotalSize(),- position: "relative",- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const channel = filteredChannels[virtualRow.index];- return (- <CommandItem- key={channel.id}- value={channel.id}- onSelect={() => selectAndClose(channel)}- className="cursor-pointer"- style={{- position: "absolute",- top: virtualRow.start,- left: 0,- width: "100%",- height: ITEM_HEIGHT,- }}- >- {renderChannelItem(channel)}- </CommandItem>- );- })}- </CommandGroup>- {isLoadingChannels && (- <CommandGroup className="p-0">- <CommandItem- value="loading-slack-channels"- disabled- className="text-muted-foreground"- >- <RefreshCw size="base" __rawClassName="animate-spin" />- <span- className="flex-1 truncate"- title="Loading Slack channels. This can take a while for large workspaces."- >- Loading Slack channels. This can take a while for large- workspaces.- </span>- </CommandItem>- </CommandGroup>- )}- </CommandList>- </Command>- </PopoverContent>- </Popover>-- {showRefreshButton && (- <Button- variant="outline"- size="sm"- onClick={handleRefresh}- disabled={disabled || isRefreshing || isLoadingChannels}- >- <RefreshCw- size="base"- color="default"- __rawClassName={cn(- (isRefreshing || isLoadingChannels) && "animate-spin",- )}- />- </Button>- )}- </div>-- {/* Channel stats */}- {channelsData?.channels && !isLoadingChannels ? (- <div className="text-muted-foreground text-xs">- {filteredChannels.length} of {channelsData.channels.length} channels- {memberOnly && " (member only)"}- </div>- ) : null}-- {error && (- <Alert>- <Alert.Description>- Failed to load channels. You can still enter a channel name- manually, or check your Slack connection and try again.- </Alert.Description>- </Alert>- )}-- {/* Private channel scope warning */}- {channelsData && !channelsData.hasPrivateChannelAccess && (- <Alert icon={AlertTriangle}>- <Alert.Description>- Private channels are not visible. To access private channels,{" "}- <button- type="button"- className="font-bold underline"- onClick={() =>- window.open(- `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/public/slack/install?projectId=${projectId}`,- "slack-reauth",- "width=600,height=700",- )- }- >- re-authenticate your Slack integration- </button>{" "}- to grant the required permissions.- </Alert.Description>- </Alert>- )}- </div>- );-};diff --git a/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.stories.tsx b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.stories.tsxnew file mode 100644index 0000000000..8dfbab1564--- /dev/null+++ b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.stories.tsx@@ -0,0 +1,109 @@+import { expect, fn, userEvent, within } from "storybook/test";++import preview from "../../../../../.storybook/preview";+import { ChannelSelectorView } from "./ChannelSelectorView";++const publicChannels = [+ { id: "C01", name: "alerts", isPrivate: false, isMember: true },+ { id: "C02", name: "general", isPrivate: false, isMember: true },+];+const privateChannel = {+ id: "G0123ABC",+ name: "incident-response",+ isPrivate: true,+ isMember: true,+};++const meta = preview.meta({+ component: ChannelSelectorView,+});++export default meta;++/**+ * The person who connected Slack sees the private channels they are a member+ * of, with a lock icon.+ */+export const PrivateChannelSelected = meta.story({+ args: {+ channelsData: {+ channels: [...publicChannels, privateChannel],+ hasPrivateChannelAccess: true,+ },+ isLoading: false,+ hasError: false,+ isRefreshing: false,+ selectedChannelId: privateChannel.id,+ onChannelSelect: fn(),+ onRefresh: fn(),+ onReauthenticate: fn(),+ },+});++/**+ * Anyone else editing an automation that posts to a private channel sees the+ * masked channel name the server returns.+ */+export const MaskedPrivateChannel = meta.story({+ args: {+ channelsData: {+ channels: publicChannels,+ hasPrivateChannelAccess: true,+ },+ isLoading: false,+ hasError: false,+ isRefreshing: false,+ selectedChannelId: privateChannel.id,+ selectedChannel: {+ id: privateChannel.id,+ name: "Private Channel (…ABC)",+ isPrivate: true,+ },+ onChannelSelect: fn(),+ onRefresh: fn(),+ onReauthenticate: fn(),+ },+});++/** Older installs lack the scope to read private channels at all. */+export const MissingPrivateChannelScope = meta.story({+ args: {+ channelsData: {+ channels: publicChannels,+ hasPrivateChannelAccess: false,+ },+ isLoading: false,+ hasError: false,+ isRefreshing: false,+ onChannelSelect: fn(),+ onRefresh: fn(),+ onReauthenticate: fn(),+ },+});++export const ReauthenticatesForPrivateChannels = meta.story({+ name: "(Test) Re-authenticates for private channels",+ args: {+ channelsData: {+ channels: publicChannels,+ hasPrivateChannelAccess: false,+ },+ isLoading: false,+ hasError: false,+ isRefreshing: false,+ onChannelSelect: fn(),+ onRefresh: fn(),+ onReauthenticate: fn(),+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ canvas.getByRole("button", {+ name: "re-authenticate your Slack integration",+ }),+ );++ await expect(args.onReauthenticate).toHaveBeenCalledOnce();+ },+});diff --git a/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsx b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsxnew file mode 100644index 0000000000..c831017fc4--- /dev/null+++ b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsx@@ -0,0 +1,325 @@+import React, { useState, useMemo, useCallback, useEffect } from "react";+import { RefreshCw, Search, Hash, Lock, AlertTriangle } from "@langfuse/icons";+import { Button } from "@/src/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { Alert } from "@/src/components/design-system/Alert/Alert";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/src/components/ui/command";+import { useVirtualizer } from "@tanstack/react-virtual";+import { type SlackChannel } from "@langfuse/shared/src/server";+const ITEM_HEIGHT = 32;++export interface ChannelSelectorViewProps {+ /** Loaded channels and private channel flags; null until the first page loads */+ channelsData: {+ channels: SlackChannel[];+ /** False when the bot token lacks the scope to read private channels */+ hasPrivateChannelAccess: boolean;+ } | null;+ isLoading: boolean;+ hasError: boolean;+ isRefreshing: boolean;+ /** Currently selected channel ID */+ selectedChannelId?: string;+ /** Full channel object for display when the ID isn't in the fetched list (e.g. manual entry) */+ selectedChannel?: SlackChannel | null;+ /** Callback when a channel is selected */+ onChannelSelect: (channel: SlackChannel) => void;+ onRefresh: () => void;+ /** Reconnects Slack to grant missing scopes */+ onReauthenticate: () => 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 command palette style dropdown for picking a Slack channel, with search,+ * public/private indicators, typed-name entry and private channel notices.+ * Items are virtualized with @tanstack/react-virtual to handle large channel lists (~5k).+ */+export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({+ channelsData,+ isLoading,+ hasError,+ isRefreshing,+ selectedChannelId,+ selectedChannel: selectedChannelProp,+ onChannelSelect,+ onRefresh,+ onReauthenticate,+ disabled = false,+ placeholder = "Select a channel",+ memberOnly = false,+ filterChannels,+ showRefreshButton = true,+}) => {+ const [open, setOpen] = useState(false);+ const [searchValue, setSearchValue] = useState("");+ const [scrollNode, setScrollNode] = useState<HTMLDivElement | null>(null);+ const trimmedSearch = searchValue.trim();+ const effectiveName = trimmedSearch.replace(/^#/, "");++ // 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 (effectiveName) {+ const searchTerm = effectiveName.toLowerCase();+ 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, effectiveName]);++ const virtualizer = useVirtualizer({+ count: filteredChannels.length,+ getScrollElement: () => scrollNode,+ estimateSize: () => ITEM_HEIGHT,+ overscan: 20,+ });++ // Get selected channel info — fall back to the prop for manual entries+ const selectedChannel = useMemo(() => {+ if (!selectedChannelId) return null;+ const fromList = channelsData?.channels?.find(+ (channel) => channel.id === selectedChannelId,+ );+ return fromList ?? selectedChannelProp ?? null;+ }, [selectedChannelId, channelsData?.channels, selectedChannelProp]);++ const selectAndClose = useCallback(+ (channel: SlackChannel) => {+ onChannelSelect(channel);+ setOpen(false);+ setSearchValue("");+ },+ [onChannelSelect],+ );++ const handleSelectByName = useCallback(() => {+ const name = searchValue.trim().replace(/^#/, "");+ if (!name) return;+ selectAndClose({+ id: `#${name}`,+ name,+ isPrivate: false,+ isMember: false,+ });+ }, [searchValue, selectAndClose]);++ const handleOpenChange = (newOpen: boolean) => {+ setOpen(newOpen);+ if (!newOpen) {+ setSearchValue("");+ }+ };++ useEffect(() => {+ if (scrollNode) {+ scrollNode.scrollTop = 0;+ }+ }, [effectiveName, scrollNode]);++ const hasExactMatch = filteredChannels.some(+ (channel) => channel.name.toLowerCase() === effectiveName.toLowerCase(),+ );+ const canUseTypedName = effectiveName.length > 0 && !hasExactMatch;++ return (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ role="combobox"+ aria-expanded={open}+ className="w-full justify-between"+ disabled={disabled}+ >+ {selectedChannel ? (+ <ChannelLabel channel={selectedChannel} />+ ) : (+ <span className="text-muted-foreground">{placeholder}</span>+ )}+ <Search+ size="base"+ color="default"+ __rawClassName="ml-2 opacity-50"+ />+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-full p-0" align="start">+ <Command shouldFilter={false}>+ <CommandInput+ placeholder="Search channels..."+ value={searchValue}+ onValueChange={setSearchValue}+ />+ <CommandList ref={setScrollNode}>+ {canUseTypedName && (+ <CommandGroup className="p-0">+ <CommandItem+ value={`use-${effectiveName}`}+ onSelect={handleSelectByName}+ className="cursor-pointer"+ >+ <Hash size="base" color="muted" />+ <span+ className="flex-1 truncate"+ title={`Use " ${effectiveName} "`}+ >+ Use "{effectiveName}"+ </span>+ </CommandItem>+ </CommandGroup>+ )}+ {!isLoading &&+ !canUseTypedName &&+ filteredChannels.length === 0 && (+ <CommandEmpty>No channels available.</CommandEmpty>+ )}+ <CommandGroup+ className="p-0"+ style={{+ height: virtualizer.getTotalSize(),+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const channel = filteredChannels[virtualRow.index];+ return (+ <CommandItem+ key={channel.id}+ value={channel.id}+ onSelect={() => selectAndClose(channel)}+ className="cursor-pointer"+ style={{+ position: "absolute",+ top: virtualRow.start,+ left: 0,+ width: "100%",+ height: ITEM_HEIGHT,+ }}+ >+ <ChannelLabel channel={channel} />+ </CommandItem>+ );+ })}+ </CommandGroup>+ {isLoading && (+ <CommandGroup className="p-0">+ <CommandItem+ value="loading-slack-channels"+ disabled+ className="text-muted-foreground"+ >+ <RefreshCw size="base" __rawClassName="animate-spin" />+ <span+ className="flex-1 truncate"+ title="Loading Slack channels. This can take a while for large workspaces."+ >+ Loading Slack channels. This can take a while for large+ workspaces.+ </span>+ </CommandItem>+ </CommandGroup>+ )}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>++ {showRefreshButton && (+ <IconButton+ icon={RefreshCw}+ label="Refresh channels"+ variant="outline"+ onClick={onRefresh}+ disabled={disabled || isRefreshing || isLoading}+ />+ )}+ </div>++ {hasError && (+ <Alert>+ <Alert.Description>+ Failed to load channels. You can still enter a channel name+ manually, or check your Slack connection and try again.+ </Alert.Description>+ </Alert>+ )}++ {/* Private channel scope warning */}+ {channelsData && !channelsData.hasPrivateChannelAccess && (+ <Alert icon={AlertTriangle} variant="warning" size="sm">+ <Alert.Title>Private channels are not visible</Alert.Title>+ <Alert.Description>+ To access private channels,{" "}+ <button+ type="button"+ className="font-bold underline"+ onClick={onReauthenticate}+ >+ re-authenticate your Slack integration+ </button>{" "}+ to grant the required permissions.+ </Alert.Description>+ </Alert>+ )}+ </div>+ );+};++const ChannelLabel = ({ channel }: { channel: SlackChannel }) => (+ <div className="flex w-full items-center gap-2">+ {channel.isPrivate ? (+ <Lock size="base" color="muted" />+ ) : (+ <Hash size="base" color="muted" />+ )}+ <span className="flex-1 truncate" title={channel.name}>+ {channel.name}+ </span>+ </div>+);diff --git a/web/src/features/slack/components/PrivateChannelsInfoTooltip.tsx b/web/src/features/slack/components/PrivateChannelsInfoTooltip.tsxnew file mode 100644index 0000000000..e06f684e05--- /dev/null+++ b/web/src/features/slack/components/PrivateChannelsInfoTooltip.tsx@@ -0,0 +1,17 @@+import { Info } from "@langfuse/icons";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";++export const PrivateChannelsInfoTooltip = () => (+ <Tooltip label="Private channels are only listed for the person who connected Slack to this project, and only those they are a member of. Reconnect Slack to list your own private channels.">+ {({ getTriggerProps }) => (+ <IconButton+ {...getTriggerProps()}+ icon={Info}+ label="About private channels"+ size="sm"+ variant="ghost"+ />+ )}+ </Tooltip>+);diff --git a/web/src/features/slack/components/SlackConnectionCard.tsx b/web/src/features/slack/components/SlackConnectionCard.tsxindex 1a2516afc6..9bf256f243 100644--- a/web/src/features/slack/components/SlackConnectionCard.tsx+++ b/web/src/features/slack/components/SlackConnectionCard.tsx@@ -1,7 +1,7 @@import React from "react";-import { CheckCircle, AlertCircle } from "@langfuse/icons";+import { CheckCircle, AlertCircle, Unlink } from "@langfuse/icons";import { Badge } from "@/src/components/ui/badge";-import { Button } from "@/src/components/ui/button";+import { Button } from "@/src/components/design-system/Button/Button";import {Card,CardContent,@@ -12,7 +12,7 @@ import {import { Alert } from "@/src/components/design-system/Alert/Alert";import { api } from "@/src/utils/api";import { SlackConnectButton } from "@/src/features/slack/components/SlackConnectButton";-import { SlackDisconnectButton } from "@/src/features/slack/components/SlackDisconnectButton";+import { SlackDisconnectDialogController } from "@/src/features/slack/components/SlackDisconnectDialogController";/*** Props for the SlackConnectionCard component@@ -197,23 +197,32 @@ export const SlackConnectionCard: React.FC<SlackConnectionCardProps> = ({{/* Management Actions */}<div className="flex gap-2 pt-2">- <SlackDisconnectButton+ <SlackDisconnectDialogControllerprojectId={projectId}- disabled={disabled}onSuccess={() => handleConnectionChange(false)}onError={(error: Error) => {console.error("Slack disconnection error:", error);}}- />+ >+ {({ isPending, openDialog }) => (+ <Button+ text="Disconnect"+ icon={Unlink}+ variant="destructive"+ size="sm"+ onClick={openDialog}+ disabled={disabled || isPending}+ />+ )}+ </SlackDisconnectDialogController><Button- variant="outline"+ text="Refresh Status"+ variant="secondary"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.tsxdeleted file mode 100644index c519c915ce..0000000000--- a/web/src/features/slack/components/SlackDisconnectButton.tsx+++ /dev/null@@ -1,235 +0,0 @@-/* eslint-disable @repo/no-abstracted-overlay-trigger */-import React, { useState } from "react";-import { Unlink, AlertTriangle } from "@langfuse/icons";-import { Button } from "@/src/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/src/components/ui/dialog";-import { showSuccessToast, showErrorToast } from "@/src/features/notifications";-import { api, reportTrpcErrorWithoutToast } from "@/src/utils/api";-import { Spinner } from "@/src/components/design-system/Spinner/Spinner";-import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";--/**- * 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({- operation: "slack.disconnect",- 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,- classifyTrpcToastError(error, "slack.disconnect"),- );-- onError?.(new Error(errorMessage));- },- });-- // Handle disconnect action- const handleDisconnect = async () => {- if (isDisconnecting) return;-- setIsDisconnecting(true);-- try {- await disconnectMutation.mutateAsync({ projectId });- } catch (error) {- // The mutation's local onError owns the UX; this owns classification + capture.- reportTrpcErrorWithoutToast(error, "slack");- }- };-- // Handle button click- const handleClick = () => {- if (showConfirmation) {- setIsDialogOpen(true);- } else {- handleDisconnect();- }- };-- const buttonContent = (- <>- {isDisconnecting ? (- <div className={showText ? "mr-2" : ""}>- <Spinner size="sm" />- </div>- ) : (- <Unlink size="base" __rawClassName={showText ? "mr-2" : ""} />- )}- {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 size="lg" color="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="bg-muted space-y-2 rounded-md p-3">- <p className="text-sm font-bold">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-muted-foreground text-sm">- You can reconnect at any time, but you'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 ? (- <>- <div className="mr-2">- <Spinner size="sm" />- </div>- Disconnecting...- </>- ) : (- <>- <Unlink size="base" __rawClassName="mr-2" />- 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/SlackDisconnectDialog/SlackDisconnectDialog.stories.tsx b/web/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog.stories.tsxnew file mode 100644index 0000000000..3a87710134--- /dev/null+++ b/web/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog.stories.tsx@@ -0,0 +1,35 @@+import { fn } from "storybook/test";++import preview from "../../../../../.storybook/preview";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { SlackDisconnectDialog } from "./SlackDisconnectDialog";++const meta = preview.meta({+ component: SlackDisconnectDialog,+ decorators: [+ (Story) => (+ <DialogController+ initialState={() => true}+ renderDialog={() => <Story />}+ >+ {() => null}+ </DialogController>+ ),+ ],+});++export default meta;++export const Default = meta.story({+ args: {+ isPending: false,+ onConfirm: fn(),+ },+});++export const Loading = meta.story({+ args: {+ isPending: true,+ onConfirm: fn(),+ },+});diff --git a/web/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog.tsx b/web/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog.tsxnew file mode 100644index 0000000000..c6278eb033--- /dev/null+++ b/web/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog.tsx@@ -0,0 +1,42 @@+import { Unlink } from "@langfuse/icons";+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";++export interface SlackDisconnectDialogProps {+ isPending: boolean;+ onConfirm: () => void;+}++export function SlackDisconnectDialog({+ isPending,+ onConfirm,+}: SlackDisconnectDialogProps) {+ return (+ <Dialog+ size="sm"+ title="Disconnect Slack?"+ actions={[+ {+ label: "Disconnect",+ icon: Unlink,+ variant: "destructive",+ loading: isPending,+ onClick: onConfirm,+ },+ ]}+ >+ <Dialog.Body>+ <p>This disconnects your Slack workspace from this project and:</p>+ <ul className="list-disc space-y-1 pl-5">+ <li>Removes the bot from your Slack workspace</li>+ <li>Disables all existing Slack automations</li>+ <li>Stops all future Slack notifications</li>+ <li>Deletes stored workspace credentials</li>+ </ul>+ <p className="text-muted-foreground">+ You can reconnect at any time, but you'll need to reconfigure+ your automations.+ </p>+ </Dialog.Body>+ </Dialog>+ );+}diff --git a/web/src/features/slack/components/SlackDisconnectDialogController.tsx b/web/src/features/slack/components/SlackDisconnectDialogController.tsxnew file mode 100644index 0000000000..737ae1ef17--- /dev/null+++ b/web/src/features/slack/components/SlackDisconnectDialogController.tsx@@ -0,0 +1,88 @@+import React from "react";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { showSuccessToast, showErrorToast } from "@/src/features/notifications";+import { api, reportTrpcErrorWithoutToast } from "@/src/utils/api";+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";+import { SlackDisconnectDialog } from "@/src/features/slack/components/SlackDisconnectDialog/SlackDisconnectDialog";++interface SlackDisconnectDialogControllerProps {+ /** Project ID for the Slack integration */+ projectId: string;+ /** Callback when disconnection is successful */+ onSuccess?: () => void;+ /** Callback when disconnection fails */+ onError?: (error: Error) => void;+ children: (control: {+ isPending: boolean;+ openDialog: () => void;+ }) => React.ReactNode;+}++/**+ * SlackDisconnectDialogController asks for confirmation, then disconnects the+ * project's Slack integration. The caller renders the trigger.+ */+export const SlackDisconnectDialogController = ({+ projectId,+ onSuccess,+ onError,+ children,+}: SlackDisconnectDialogControllerProps) => {+ const disconnectMutation = api.slack.disconnect.useMutation({+ onSuccess: () => {+ showSuccessToast({+ operation: "slack.disconnect",+ title: "Slack Disconnected",+ description: "Successfully disconnected from your Slack workspace.",+ });++ onSuccess?.();+ },+ onError: (error) => {+ const errorMessage = error.message || "Failed to disconnect from Slack";++ showErrorToast(+ "Disconnection Failed",+ errorMessage,+ classifyTrpcToastError(error, "slack.disconnect"),+ );++ onError?.(new Error(errorMessage));+ },+ });++ const handleDisconnect = async (closeDialog: () => void) => {+ if (disconnectMutation.isPending) return;++ try {+ await disconnectMutation.mutateAsync({ projectId });+ closeDialog();+ } catch (error) {+ // The mutation's local onError owns the UX; this owns classification + capture.+ reportTrpcErrorWithoutToast(error, "slack");+ }+ };++ return (+ <DialogController+ renderDialog={({ closeDialog }) => {+ const handleConfirm = () => handleDisconnect(closeDialog);+ return (+ <SlackDisconnectDialog+ isPending={disconnectMutation.isPending}+ onConfirm={handleConfirm}+ />+ );+ }}+ >+ {({ openDialog }) => {+ // Called without arguments so a click event is never stored as dialog state.+ const handleOpenDialog = () => openDialog();+ return children({+ isPending: disconnectMutation.isPending,+ openDialog: handleOpenDialog,+ });+ }}+ </DialogController>+ );+};diff --git a/web/src/features/slack/server/oauth-handlers.ts b/web/src/features/slack/server/oauth-handlers.tsindex 4572b43e2d..1160c71712 100644--- a/web/src/features/slack/server/oauth-handlers.ts+++ b/web/src/features/slack/server/oauth-handlers.ts@@ -39,6 +39,7 @@ export async function handleInstallPath(req: NextApiRequest,res: NextApiResponse,projectId: string,+ userId: string,) {try {// Use InstallProvider's handleInstallPath method to render the installation page@@ -54,7 +55,7 @@ export async function handleInstallPath(const installOptions = {scopes: [...SLACK_BOT_SCOPES],- metadata: JSON.stringify({ projectId: projectId }),+ metadata: JSON.stringify({ projectId, userId }),redirectUri: redirectUri.toString(),};diff --git a/web/src/features/slack/server/router.ts b/web/src/features/slack/server/router.tsindex b856b705b7..55eba78a9b 100644--- a/web/src/features/slack/server/router.ts+++ b/web/src/features/slack/server/router.ts@@ -6,6 +6,9 @@ import { z } from "zod";import {SlackService,SlackApiError,+ SLACK_CHANNEL_NOT_FOUND_MESSAGE,+ buildSlackLinkSection,+ getPrivateChannelViewerSlackUserId,logger,} from "@langfuse/shared/src/server";import { throwIfNoProjectAccess } from "@/src/features/rbac";@@ -116,8 +119,31 @@ export const slackRouter = createTRPCRouter({const client = await slackService.getWebClientForProject(input.projectId,);- const { channels, hasPrivateChannelAccess, nextCursor } =- await slackService.getChannels(client, input.cursor);+ const viewerSlackUserId = getPrivateChannelViewerSlackUserId(+ integration,+ ctx.session.user.id,+ );+ const [publicPage, privateChannels] = await Promise.all([+ slackService.getChannels(client, input.cursor),+ // Private channels are not paginated; add them to the first page only+ !input.cursor && viewerSlackUserId+ ? slackService+ .getPrivateChannels(client, { slackUserId: viewerSlackUserId })+ // A failed private lookup must not hide the public channels.+ .catch((error) => {+ logger.warn("Failed to fetch private Slack channels", {+ error,+ projectId: input.projectId,+ });+ return null;+ })+ : null,+ ]);+ const channels = [+ ...publicPage.channels,+ ...(privateChannels?.channels ?? []),+ ];+ const nextCursor = publicPage.nextCursor;if (!input.cursor) {await auditLog({@@ -135,7 +161,12 @@ export const slackRouter = createTRPCRouter({return {channels,- hasPrivateChannelAccess,+ // Installs without a recorded installer can't list private channels+ // until someone re-authenticates.+ hasPrivateChannelAccess:+ privateChannels?.hasPrivateChannelAccess ??+ (Boolean(input.cursor) ||+ Boolean(integration.installerSlackUserId)),nextCursor,teamId: integration.teamId,teamName: integration.teamName,@@ -241,6 +272,25 @@ export const slackRouter = createTRPCRouter({const client = await SlackService.getInstance().getWebClientForProject(input.projectId,);++ // Checked before posting so a private channel the viewer can't use+ // fails exactly like a non-existent one.+ const privateChannelAccess =+ await SlackService.getInstance().checkPrivateChannelAccess({+ client,+ channel: input.channelId,+ viewerSlackUserId: getPrivateChannelViewerSlackUserId(+ integration,+ ctx.session.user.id,+ ),+ });+ if (privateChannelAccess.access === "denied") {+ throw new SlackApiError(+ "Private channel is not accessible to this user",+ "channel_not_found",+ );+ }+const projectUrl = new URL(`project/${input.projectId}`,getProductBaseUrl(),@@ -283,26 +333,17 @@ export const slackRouter = createTRPCRouter({},],},- {- type: "actions",- elements: [- {- type: "button",- text: {- type: "plain_text",- text: "Open Langfuse",- emoji: true,- },- url: projectUrl.toString(),- style: "primary",- },- ],- },+ buildSlackLinkSection([+ { label: "Open Langfuse", url: projectUrl.toString() },+ ]),];const result = await SlackService.getInstance().sendMessage({client,- channelId: input.channelId,+ channelId:+ privateChannelAccess.access === "private"+ ? privateChannelAccess.channel.id+ : input.channelId,blocks: testBlocks,text: "Test message from Langfuse",});@@ -317,7 +358,9 @@ export const slackRouter = createTRPCRouter({isPrivate?: boolean;} = { id: result.channel };- if (input.channelId.startsWith("#")) {+ if (privateChannelAccess.access === "private") {+ channelInfo = privateChannelAccess.channel;+ } else if (input.channelId.startsWith("#")) {const resolved = await SlackService.getInstance().getChannelInfo(client,result.channel,@@ -370,7 +413,7 @@ export const slackRouter = createTRPCRouter({const userMessage = (() => {switch (slackError) {case "channel_not_found":- return 'Channel not found. The channel may not exist or is a private channel the bot has not been invited to. For private channels, invite the app with "/invite @Langfuse" in that channel.';+ return SLACK_CHANNEL_NOT_FOUND_MESSAGE;case "not_in_channel":return "The bot is not a member of this channel. Please invite the bot to the channel first.";case "is_archived":diff --git a/web/src/pages/api/public/slack/install/index.ts b/web/src/pages/api/public/slack/install/index.tsindex 5c4f2d0889..874bcba2f1 100644--- a/web/src/pages/api/public/slack/install/index.ts+++ b/web/src/pages/api/public/slack/install/index.ts@@ -24,7 +24,7 @@ export default async function handler(// Verify user is authenticatedconst session = await getServerAuthSession({ req, res });- if (!session) {+ if (!session?.user) {logger.warn("Unauthenticated Slack install attempt", { projectId });return res.status(401).json({ error: "Authentication required" });}@@ -56,7 +56,7 @@ export default async function handler(// - Generating the OAuth URL with proper state// - Setting session cookies for state validation// - Rendering the installation page- return await handleInstallPath(req, res, projectId);+ return await handleInstallPath(req, res, projectId, session.user.id);} catch (error) {logger.error("Install handler failed", { error });return res.status(500).json({ message: "Internal server error" });diff --git a/worker/src/__tests__/slack-message-builder.test.ts b/worker/src/__tests__/slack-message-builder.test.tsindex d1bab837d2..229c3a38dc 100644--- a/worker/src/__tests__/slack-message-builder.test.ts+++ b/worker/src/__tests__/slack-message-builder.test.ts@@ -43,7 +43,7 @@ describe("SlackMessageBuilder", () => {const blocks =SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);- expect(blocks).toHaveLength(5); // header, main, details, commit, actions+ expect(blocks).toHaveLength(5); // header, main, details, commit, link// Check header blockexpect(blocks[0]).toMatchObject({@@ -100,23 +100,14 @@ describe("SlackMessageBuilder", () => {},});- // Check action buttonsexpect(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",- },- ],+ type: "section",+ text: {+ type: "mrkdwn",+ text: expect.stringMatching(+ /<[^|]*\/project\/project-456\/prompts\/test-prompt\?version=2\|View Prompt>/,+ ),+ },});});@@ -244,7 +235,7 @@ describe("SlackMessageBuilder", () => {it("should generate correct URLs for different environments", () => {const blocks =SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);- expect(blocks[4].elements[0].url).toContain(+ expect(blocks[4].text.text).toContain("http://localhost:3000/project/project-456/prompts/test-prompt?version=2",);});@@ -255,8 +246,8 @@ describe("SlackMessageBuilder", () => {const blocks =SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);- expect(blocks[4].elements[0].url).toBe(- "https://example.com/langfuse/project/project-456/prompts/test-prompt?version=2",+ expect(blocks[4].text.text).toContain(+ "<https://example.com/langfuse/project/project-456/prompts/test-prompt?version=2|",);});@@ -267,8 +258,8 @@ describe("SlackMessageBuilder", () => {const blocks =SlackMessageBuilder.buildPromptVersionMessage(mockPromptPayload);- expect(blocks[4].elements[0].url).toBe(- "https://example.com/langfuse/project/project-456/prompts/test-prompt?version=2",+ expect(blocks[4].text.text).toContain(+ "<https://example.com/langfuse/project/project-456/prompts/test-prompt?version=2|",);});});diff --git a/worker/src/features/slack/slackMessageBuilder.ts b/worker/src/features/slack/slackMessageBuilder.tsindex a534170738..8388d7deff 100644--- a/worker/src/features/slack/slackMessageBuilder.ts+++ b/worker/src/features/slack/slackMessageBuilder.ts@@ -1,5 +1,6 @@import {logger,+ buildSlackLinkSection,escapeSlackMrkdwn,type WebhookInput,type SlackMessage,@@ -108,25 +109,8 @@ export class SlackMessageBuilder {},]: []),- // Action buttons...(promptUrl- ? [- {- type: "actions",- elements: [- {- type: "button",- text: {- type: "plain_text",- text: "View Prompt",- emoji: true,- },- url: promptUrl,- style: "primary",- },- ],- },- ]+ ? [buildSlackLinkSection([{ label: "View Prompt", url: promptUrl }])]: []),];