Skip to content

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

fix: make Slack integration more robust (#13004)

Tobias Wochinger25d99aa37148
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 5a98e3f3a1..12c0f5a247 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -290,6 +290,14 @@ const EnvSchema = z.object({
.describe(
"How many records should be fetched from Slack, before we give up",
),
+ SLACK_PAGE_SIZE: z.coerce
+ .number()
+ .positive()
+ .int()
+ .max(1000)
+ .optional()
+ .default(1000) // Use high default to minimize number of API calls and hence avoid rate limits
+ .describe("Number of channels to fetch per Slack API page"),
HTTPS_PROXY: z.string().optional(),
LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT: z.coerce
diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.ts
index 2b8165e93c..ae6c9c7814 100644
--- a/packages/shared/src/server/services/SlackService.ts
+++ b/packages/shared/src/server/services/SlackService.ts
@@ -14,12 +14,39 @@ import { env } from "../../env";
import { prisma } from "../../db";
import { encrypt, decrypt } from "../../encryption";
+/**
+ * Error thrown by SlackService when a Slack API call fails.
+ * Preserves the Slack error code so callers can provide user-friendly messages.
+ */
+export class SlackApiError extends Error {
+ constructor(
+ message: string,
+ public readonly slackErrorCode?: string,
+ ) {
+ super(message);
+ this.name = "SlackApiError";
+ }
+}
+
+/** OAuth scopes requested when installing the Slack app. */
+export const SLACK_BOT_SCOPES = [
+ "channels:read", // read public channels
+ "groups:read", // read private channels that the bot is a member of
+ "chat:write", // send messages to channels the bot is a member of
+ "chat:write.public", // send messages to public channels that the bot is not a member of
+] as const;
+
// Types for Slack integration
export interface SlackChannel {
id: string;
name: string;
- isPrivate: boolean;
- isMember: boolean;
+ isPrivate?: boolean;
+ isMember?: boolean;
+}
+
+export interface GetChannelsResult {
+ channels: SlackChannel[];
+ hasPrivateChannelAccess: boolean;
}
export interface SlackMessageParams {
@@ -96,7 +123,7 @@ export class SlackService {
clientSecret: env.SLACK_CLIENT_SECRET!,
stateSecret: env.SLACK_STATE_SECRET!,
installUrlOptions: {
- scopes: ["channels:read", "chat:write", "chat:write.public"],
+ scopes: SLACK_BOT_SCOPES as unknown as string[],
},
installationStore: {
storeInstallation: async (installation) => {
@@ -280,7 +307,9 @@ export class SlackService {
throw new Error("No bot token found for project");
}
- const client = new WebClient(auth.botToken);
+ const client = new WebClient(auth.botToken, {
+ retryConfig: { retries: 3, maxRetryTime: 90_000 },
+ });
logger.debug("Created WebClient for project", { projectId });
return client;
@@ -301,14 +330,15 @@ export class SlackService {
*/
private async getChannelsRecursive(
client: WebClient,
+ channelTypes: string = "public_channel,private_channel",
cursor?: string,
fetchedRecords: number = 0,
): Promise<SlackChannel[]> {
try {
const result = await client.conversations.list({
exclude_archived: true,
- types: "public_channel",
- limit: 200,
+ types: channelTypes,
+ limit: env.SLACK_PAGE_SIZE,
cursor: cursor,
});
@@ -333,10 +363,11 @@ export class SlackService {
try {
const nextPageChannels = await this.getChannelsRecursive(
client,
+ channelTypes,
nextCursor,
fetchedRecords + channels.length,
);
- return [...channels, ...nextPageChannels];
+ return channels.concat(nextPageChannels);
} catch (error) {
logger.error(
`Failed to retrieve next page of channels, returning only already fetched`,
@@ -347,25 +378,54 @@ export class SlackService {
return channels;
} catch (error) {
logger.error("Failed to fetch channels recursively", { error, cursor });
- throw new Error(
- `Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,
- );
+ throw error;
}
}
/**
- * Get channels accessible to the bot
+ * Get channels accessible to the bot.
*/
- async getChannels(client: WebClient): Promise<SlackChannel[]> {
+ async getChannels(client: WebClient): Promise<GetChannelsResult> {
try {
- const channels = await this.getChannelsRecursive(client);
+ const channels = await this.getChannelsRecursive(
+ client,
+ "public_channel,private_channel",
+ );
logger.debug("Retrieved channels from Slack", {
channelCount: channels.length,
});
- return channels;
- } catch (error) {
+ return { channels, hasPrivateChannelAccess: true };
+ } 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",
+ );
+
+ try {
+ const channels = await this.getChannelsRecursive(
+ client,
+ "public_channel",
+ );
+
+ return { channels, hasPrivateChannelAccess: false };
+ } catch (fallbackError) {
+ logger.error("Failed to fetch public channels fallback", {
+ error: fallbackError,
+ });
+ throw new Error(
+ `Failed to fetch channels: ${fallbackError instanceof Error ? fallbackError.message : "Unknown error"}`,
+ );
+ }
+ }
+
logger.error("Failed to fetch channels", { error });
throw new Error(
`Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,
@@ -373,6 +433,28 @@ export class SlackService {
}
}
+ /**
+ * Get channel info by ID via conversations.info.
+ */
+ async getChannelInfo(
+ client: WebClient,
+ channelId: string,
+ ): Promise<SlackChannel | null> {
+ try {
+ const result = await client.conversations.info({ channel: channelId });
+ if (!result.ok || !result.channel) return null;
+ return {
+ id: result.channel.id!,
+ name: result.channel.name!,
+ isPrivate: result.channel.is_private || false,
+ isMember: result.channel.is_member || false,
+ };
+ } catch (error) {
+ logger.warn("Failed to fetch channel info", { error, channelId });
+ return null;
+ }
+ }
+
/**
* Send a message to a Slack channel
*/
@@ -401,13 +483,16 @@ export class SlackService {
});
return response;
- } catch (error) {
+ } catch (error: any) {
logger.error("Failed to send message", {
error,
channelId: params.channelId,
});
- throw new Error(
+
+ const slackErrorCode = error?.data?.error as string | undefined;
+ throw new SlackApiError(
`Failed to send message: ${error instanceof Error ? error.message : "Unknown error"}`,
+ slackErrorCode,
);
}
}
diff --git a/web/src/__tests__/server/slack-integration.servertest.ts b/web/src/__tests__/server/slack-integration.servertest.ts
index 8ae3aa1518..c6c78c9b6c 100644
--- a/web/src/__tests__/server/slack-integration.servertest.ts
+++ b/web/src/__tests__/server/slack-integration.servertest.ts
@@ -79,6 +79,7 @@ describe("Slack Integration", () => {
getWebClientForProject: jest.fn(),
sendMessage: jest.fn(),
getChannels: jest.fn(),
+ getChannelInfo: jest.fn(),
validateClient: jest.fn(),
deleteIntegration: jest.fn(),
};
@@ -196,7 +197,10 @@ describe("Slack Integration", () => {
},
];
- mockSlackService.getChannels.mockResolvedValue(mockChannels);
+ mockSlackService.getChannels.mockResolvedValue({
+ channels: mockChannels,
+ hasPrivateChannelAccess: true,
+ });
const { caller, project } = await prepare();
@@ -217,6 +221,7 @@ describe("Slack Integration", () => {
expect(result).toMatchObject({
channels: mockChannels,
+ hasPrivateChannelAccess: true,
teamId: "T123456",
teamName: "Test Team",
});
@@ -306,6 +311,71 @@ describe("Slack Integration", () => {
expect(JSON.stringify(result)).not.toContain("xoxb-test-token");
});
+ it("should resolve channel info for manually-typed channel names", async () => {
+ const mockClient = { auth: { test: jest.fn() } };
+ mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);
+ mockSlackService.sendMessage.mockResolvedValue({
+ messageTs: "1234567890.123456",
+ channel: "C999888",
+ });
+ mockSlackService.getChannelInfo.mockResolvedValue({
+ id: "C999888",
+ name: "general",
+ isPrivate: false,
+ });
+
+ const { caller, project } = await prepare();
+
+ await prisma.slackIntegration.create({
+ data: {
+ projectId: project.id,
+ teamId: "T123456",
+ teamName: "Test Team",
+ botToken: encrypt("xoxb-test-token"),
+ botUserId: "U123456",
+ },
+ });
+
+ const result = await caller.slack.sendTestMessage({
+ projectId: project.id,
+ channelId: "#general",
+ channelName: "general",
+ });
+
+ expect(result).toMatchObject({
+ success: true,
+ channel: "C999888",
+ channelInfo: {
+ id: "C999888",
+ name: "general",
+ isPrivate: false,
+ },
+ });
+
+ expect(mockSlackService.getChannelInfo).toHaveBeenCalledWith(
+ mockClient,
+ "C999888",
+ );
+
+ // Verify audit log records the resolved channel ID, not the #-prefixed input
+ const auditLogEntry = await prisma.auditLog.findFirst({
+ where: {
+ projectId: project.id,
+ resourceType: "slackIntegration",
+ action: "create",
+ },
+ orderBy: { createdAt: "desc" },
+ });
+
+ expect(auditLogEntry).toBeDefined();
+ const afterData = auditLogEntry?.after
+ ? JSON.parse(auditLogEntry.after)
+ : null;
+ expect(afterData).toMatchObject({
+ channelId: "C999888",
+ });
+ });
+
it("should create audit log entry", async () => {
const mockClient = { auth: { test: jest.fn() } };
mockSlackService.getWebClientForProject.mockResolvedValue(mockClient);
@@ -501,9 +571,12 @@ describe("Slack Integration", () => {
it("should NEVER expose raw bot tokens in any API response", async () => {
mockSlackService.validateClient.mockResolvedValue(true);
- mockSlackService.getChannels.mockResolvedValue([
- { id: "C123456", name: "general", isPrivate: false, isMember: true },
- ]);
+ mockSlackService.getChannels.mockResolvedValue({
+ channels: [
+ { id: "C123456", name: "general", isPrivate: false, isMember: true },
+ ],
+ hasPrivateChannelAccess: true,
+ });
mockSlackService.sendMessage.mockResolvedValue({
messageTs: "1234567890.123456",
channel: "C123456",
diff --git a/web/src/features/automations/components/actions/SlackActionForm.tsx b/web/src/features/automations/components/actions/SlackActionForm.tsx
index 3d931e70df..eb84635dce 100644
--- a/web/src/features/automations/components/actions/SlackActionForm.tsx
+++ b/web/src/features/automations/components/actions/SlackActionForm.tsx
@@ -31,8 +31,12 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({
disabled,
projectId,
}) => {
+ const initialChannelId = form.getValues("slack.channelId") as string;
+ const initialChannelName = form.getValues("slack.channelName") as string;
const [selectedChannel, setSelectedChannel] = useState<SlackChannel | null>(
- null,
+ initialChannelId && initialChannelName
+ ? { id: initialChannelId, name: initialChannelName }
+ : null,
);
// Get Slack integration status
@@ -88,6 +92,7 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({
<ChannelSelector
projectId={projectId}
selectedChannelId={field.value}
+ selectedChannel={selectedChannel}
onChannelSelect={handleChannelSelect}
disabled={disabled}
placeholder="Select a channel"
@@ -96,7 +101,12 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({
</div>
</FormControl>
<FormDescription>
- Select the Slack channel where notifications will be sent.
+ Select the Slack channel where notifications will be sent. For
+ private channels, invite the app first with{" "}
+ <code className="bg-muted rounded px-1 py-0.5">
+ /invite @Langfuse
+ </code>{" "}
+ in that channel.
</FormDescription>
<FormMessage />
</FormItem>
@@ -120,6 +130,23 @@ export const SlackActionForm: React.FC<SlackActionFormProps> = ({
disabled={disabled}
size="sm"
buttonText="Test Channel"
+ onSuccess={(channelInfo) => {
+ form.setValue("slack.channelId", channelInfo.id);
+ form.setValue(
+ "slack.channelName",
+ channelInfo.name ?? selectedChannel?.name ?? "",
+ );
+ setSelectedChannel((prev) =>
+ prev
+ ? {
+ ...prev,
+ id: channelInfo.id,
+ name: channelInfo.name ?? prev.name,
+ isPrivate: channelInfo.isPrivate ?? prev.isPrivate,
+ }
+ : prev,
+ );
+ }}
/>
<p className="text-muted-foreground text-sm">
Test this channel to verify the bot can send messages.
diff --git a/web/src/features/slack/app_manifest.json b/web/src/features/slack/app_manifest.json
index 655185090a..7dec817136 100644
--- a/web/src/features/slack/app_manifest.json
+++ b/web/src/features/slack/app_manifest.json
@@ -20,7 +20,7 @@
"https://staging.langfuse.com/api/public/slack/oauth"
],
"scopes": {
- "bot": ["channels:read", "chat:write", "chat:write.public"]
+ "bot": ["channels:read", "groups:read", "chat:write", "chat:write.public"]
}
},
"settings": {
diff --git a/web/src/features/slack/components/ChannelSelector.tsx b/web/src/features/slack/components/ChannelSelector.tsx
index 811bddb42c..c9062e6f45 100644
--- a/web/src/features/slack/components/ChannelSelector.tsx
+++ b/web/src/features/slack/components/ChannelSelector.tsx
@@ -1,7 +1,12 @@
-import React, { useState, useMemo } from "react";
-import { RefreshCw, Search, Hash, Lock } from "lucide-react";
+import React, { useState, useMemo, useCallback, useEffect } from "react";
+import { RefreshCw, Search, Hash, Lock, AlertTriangle } from "lucide-react";
import { Button } from "@/src/components/ui/button";
-
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
import { Select, SelectTrigger, SelectValue } from "@/src/components/ui/select";
import {
Command,
@@ -11,23 +16,11 @@ import {
CommandItem,
CommandList,
} from "@/src/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { useVirtualizer } from "@tanstack/react-virtual";
import { api } from "@/src/utils/api";
+import { type SlackChannel } from "@langfuse/shared/src/server";
-/**
- * Represents a Slack channel
- */
-export interface SlackChannel {
- id: string;
- name: string;
- isPrivate: boolean;
- isMember: boolean;
-}
+export type { SlackChannel };
/**
* Props for the ChannelSelector component
@@ -37,6 +30,8 @@ interface ChannelSelectorProps {
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 */
@@ -51,6 +46,8 @@ interface ChannelSelectorProps {
showRefreshButton?: boolean;
}
+const ITEM_HEIGHT = 32;
+
/**
* A dropdown component for selecting Slack channels with search and filtering capabilities.
*
@@ -64,9 +61,11 @@ interface ChannelSelectorProps {
*
* 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
@@ -77,6 +76,7 @@ interface ChannelSelectorProps {
export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
projectId,
selectedChannelId,
+ selectedChannel: selectedChannelProp,
onChannelSelect,
disabled = false,
placeholder = "Select a channel",
@@ -87,6 +87,9 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
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 {
@@ -130,36 +133,63 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
}
// Apply search filter
- if (searchValue.trim()) {
- const searchTerm = searchValue.toLowerCase().trim();
+ 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) => {
+ return [...channels].sort((a, b) => {
if (a.isPrivate !== b.isPrivate) {
return a.isPrivate ? 1 : -1;
}
return a.name.localeCompare(b.name);
});
- }, [channelsData?.channels, memberOnly, filterChannels, searchValue]);
+ }, [channelsData?.channels, memberOnly, filterChannels, effectiveName]);
- // Get selected channel info
+ 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 || !channelsData?.channels) return null;
- return channelsData.channels.find(
+ if (!selectedChannelId) return null;
+ const fromList = channelsData?.channels?.find(
(channel) => channel.id === selectedChannelId,
);
- }, [selectedChannelId, channelsData?.channels]);
+ return fromList ?? selectedChannelProp ?? null;
+ }, [selectedChannelId, channelsData?.channels, selectedChannelProp]);
- // Handle channel selection
- const handleChannelSelect = (channel: SlackChannel) => {
- onChannelSelect(channel);
- setOpen(false);
- setSearchValue("");
- };
+ 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) => (
@@ -219,10 +249,23 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
);
}
+ 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={setOpen}>
+ <Popover
+ open={open}
+ onOpenChange={(newOpen) => {
+ setOpen(newOpen);
+ if (!newOpen) {
+ setSearchValue("");
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -246,23 +289,51 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
value={searchValue}
onValueChange={setSearchValue}
/>
- <CommandList>
- <CommandEmpty>
- {searchValue
- ? "No channels match your search."
- : "No channels available."}
- </CommandEmpty>
- <CommandGroup>
- {filteredChannels.map((channel) => (
+ <CommandList ref={setScrollNode}>
+ {canUseTypedName && (
+ <CommandGroup className="p-0">
<CommandItem
- key={channel.id}
- value={channel.id}
- onSelect={() => handleChannelSelect(channel)}
+ value={`use-${effectiveName}`}
+ onSelect={handleSelectByName}
className="cursor-pointer"
>
- {renderChannelItem(channel)}
+ <Hash className="text-muted-foreground h-4 w-4" />
+ <span className="flex-1 truncate">
+ Use &quot;{effectiveName}&quot;
+ </span>
</CommandItem>
- ))}
+ </CommandGroup>
+ )}
+ {!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>
</CommandList>
</Command>
@@ -290,6 +361,30 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
{memberOnly && " (member only)"}
</div>
)}
+
+ {/* Private channel scope warning */}
+ {channelsData && !channelsData.hasPrivateChannelAccess && (
+ <Alert>
+ <AlertTriangle className="h-4 w-4" />
+ <AlertDescription>
+ Private channels are not visible. To access private channels,{" "}
+ <button
+ type="button"
+ className="font-medium underline"
+ onClick={() =>
+ window.open(
+ `/api/public/slack/install?projectId=${projectId}`,
+ "slack-reauth",
+ "width=600,height=700",
+ )
+ }
+ >
+ re-authenticate your Slack integration
+ </button>{" "}
+ to grant the required permissions.
+ </AlertDescription>
+ </Alert>
+ )}
</div>
);
};
diff --git a/web/src/features/slack/components/SlackTestMessageButton.tsx b/web/src/features/slack/components/SlackTestMessageButton.tsx
index 42dcb82997..8630906a4b 100644
--- a/web/src/features/slack/components/SlackTestMessageButton.tsx
+++ b/web/src/features/slack/components/SlackTestMessageButton.tsx
@@ -22,8 +22,12 @@ interface SlackTestMessageButtonProps {
size?: ButtonProps["size"];
/** Custom button text */
buttonText?: string;
- /** Callback when test message is sent successfully */
- onSuccess?: () => void;
+ /** Callback when test message is sent successfully, receives the resolved channel info */
+ onSuccess?: (channelInfo: {
+ id: string;
+ name?: string;
+ isPrivate?: boolean;
+ }) => void;
/** Callback when test message fails */
onError?: (error: Error) => void;
/** Whether to show the button text */
@@ -52,12 +56,12 @@ export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
}) => {
// Test message mutation
const testMessageMutation = api.slack.sendTestMessage.useMutation({
- onSuccess: () => {
+ onSuccess: (data) => {
showSuccessToast({
title: "Test Message Sent",
description: "Test message sent successfully to the selected channel.",
});
- onSuccess?.();
+ onSuccess?.(data.channelInfo);
},
onError: (error) => {
showErrorToast("Failed to Send Test Message", error.message);
@@ -73,7 +77,7 @@ export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
await testMessageMutation.mutateAsync({
projectId,
channelId: selectedChannel.id,
- channelName: selectedChannel.name,
+ channelName: selectedChannel.name ?? undefined,
});
} catch {
// Error handling is done in the mutation
diff --git a/web/src/features/slack/server/oauth-handlers.ts b/web/src/features/slack/server/oauth-handlers.ts
index a392d475c4..bbe51b87ae 100644
--- a/web/src/features/slack/server/oauth-handlers.ts
+++ b/web/src/features/slack/server/oauth-handlers.ts
@@ -1,6 +1,7 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import {
SlackService,
+ SLACK_BOT_SCOPES,
parseSlackInstallationMetadata,
} from "@langfuse/shared/src/server";
import { logger } from "@langfuse/shared/src/server";
@@ -30,7 +31,7 @@ export async function handleInstallPath(
// 2. Set session cookies for state validation
// 3. Render the installation page with "Add to Slack" button
const installOptions = {
- scopes: ["channels:read", "chat:write", "chat:write.public"],
+ scopes: [...SLACK_BOT_SCOPES],
metadata: JSON.stringify({ projectId: projectId }),
redirectUri: `${env.NEXTAUTH_URL}/api/public/slack/oauth`,
};
diff --git a/web/src/features/slack/server/router.ts b/web/src/features/slack/server/router.ts
index 530a6bc97d..83cd660156 100644
--- a/web/src/features/slack/server/router.ts
+++ b/web/src/features/slack/server/router.ts
@@ -3,7 +3,7 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { z } from "zod";
-import { SlackService } from "@langfuse/shared/src/server";
+import { SlackService, SlackApiError } from "@langfuse/shared/src/server";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { logger } from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
@@ -112,7 +112,8 @@ export const slackRouter = createTRPCRouter({
const client = await slackService.getWebClientForProject(
input.projectId,
);
- const channels = await slackService.getChannels(client);
+ const { channels, hasPrivateChannelAccess } =
+ await slackService.getChannels(client);
await auditLog({
session: ctx.session,
@@ -124,6 +125,7 @@ export const slackRouter = createTRPCRouter({
return {
channels,
+ hasPrivateChannelAccess,
teamId: integration.teamId,
teamName: integration.teamName,
};
@@ -201,8 +203,9 @@ export const slackRouter = createTRPCRouter({
.input(
z.object({
projectId: z.string(),
+ // Slack resolves both channel IDs (C1234) and names (#general)
channelId: z.string(),
- channelName: z.string(),
+ channelName: z.string().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
@@ -253,7 +256,7 @@ export const slackRouter = createTRPCRouter({
},
{
type: "mrkdwn",
- text: `*Channel:*\n#${input.channelName}`,
+ text: `*Channel:*\n#${input.channelName ?? input.channelId.replace(/^#/, "")}`,
},
{
type: "mrkdwn",
@@ -289,6 +292,30 @@ export const slackRouter = createTRPCRouter({
text: "Test message from Langfuse",
});
+ // For manually-typed channel names (id starts with #), resolve
+ // channel metadata via conversations.info so the UI can show
+ // accurate type/ID info. Skip for channels already selected from
+ // the list since we already have their metadata.
+ let channelInfo: {
+ id: string;
+ name?: string;
+ isPrivate?: boolean;
+ } = { id: result.channel };
+
+ if (input.channelId.startsWith("#")) {
+ const resolved = await SlackService.getInstance().getChannelInfo(
+ client,
+ result.channel,
+ );
+ if (resolved) {
+ channelInfo = {
+ id: resolved.id,
+ name: resolved.name,
+ isPrivate: resolved.isPrivate,
+ };
+ }
+ }
+
await auditLog({
session: ctx.session,
resourceType: "slackIntegration",
@@ -296,7 +323,7 @@ export const slackRouter = createTRPCRouter({
action: "create",
after: {
action: "test_message_sent",
- channelId: input.channelId,
+ channelId: result.channel,
channelName: input.channelName,
messageTs: result.messageTs,
},
@@ -304,7 +331,7 @@ export const slackRouter = createTRPCRouter({
logger.info("Test message sent successfully", {
projectId: input.projectId,
- channelId: input.channelId,
+ channelId: result.channel,
channelName: input.channelName,
messageTs: result.messageTs,
});
@@ -313,6 +340,7 @@ export const slackRouter = createTRPCRouter({
success: true,
messageTs: result.messageTs,
channel: result.channel,
+ channelInfo,
};
} catch (error) {
logger.error("Failed to send test message", {
@@ -321,10 +349,28 @@ export const slackRouter = createTRPCRouter({
channelId: input.channelId,
});
+ const slackError =
+ error instanceof SlackApiError ? error.slackErrorCode : undefined;
+
+ 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.';
+ 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":
+ return "This channel has been archived and cannot receive messages.";
+ case "invalid_auth":
+ case "token_revoked":
+ return "Slack authentication failed. Please reconnect your Slack workspace.";
+ default:
+ return "Failed to send test message. Please check your Slack connection and channel permissions.";
+ }
+ })();
+
throw new TRPCError({
code: "BAD_REQUEST",
- message:
- "Failed to send test message. Please check your Slack connection and channel permissions.",
+ message: userMessage,
});
}
}),
diff --git a/web/src/pages/project/[projectId]/settings/integrations/slack.tsx b/web/src/pages/project/[projectId]/settings/integrations/slack.tsx
index 6345756a64..591a83cee8 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/slack.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/slack.tsx
@@ -86,6 +86,9 @@ export default function SlackIntegrationSettings() {
scope: "automations:CUD",
});
+ // Channel was typed by name rather than selected from the list
+ const isManualEntry = selectedChannel?.id.startsWith("#") ?? false;
+
return (
<ContainerPage
headerProps={{
@@ -121,6 +124,7 @@ export default function SlackIntegrationSettings() {
<ChannelSelector
projectId={projectId}
selectedChannelId={selectedChannel?.id}
+ selectedChannel={selectedChannel}
onChannelSelect={setSelectedChannel}
placeholder="Choose a channel to test"
showRefreshButton={true}
@@ -143,15 +147,27 @@ export default function SlackIntegrationSettings() {
</div>
<div>
<p className="text-sm font-medium">Channel Type</p>
- <Badge variant="outline" className="text-xs">
- {selectedChannel.isPrivate ? "Private" : "Public"}
- </Badge>
+ {isManualEntry ? (
+ <span className="text-muted-foreground text-xs">
+ Available after sending a test message
+ </span>
+ ) : (
+ <Badge variant="outline" className="text-xs">
+ {selectedChannel.isPrivate ? "Private" : "Public"}
+ </Badge>
+ )}
</div>
<div>
<p className="text-sm font-medium">Channel ID</p>
- <p className="text-muted-foreground font-mono text-sm">
- {selectedChannel.id}
- </p>
+ {isManualEntry ? (
+ <span className="text-muted-foreground text-xs">
+ Available after sending a test message
+ </span>
+ ) : (
+ <p className="text-muted-foreground font-mono text-sm">
+ {selectedChannel.id}
+ </p>
+ )}
</div>
</div>
</div>
@@ -162,6 +178,19 @@ export default function SlackIntegrationSettings() {
selectedChannel={selectedChannel}
hasAccess={hasAccess}
disabled={false}
+ onSuccess={(channelInfo) => {
+ setSelectedChannel((prev) =>
+ prev
+ ? {
+ ...prev,
+ id: channelInfo.id,
+ name: channelInfo.name ?? prev.name,
+ isPrivate:
+ channelInfo.isPrivate ?? prev.isPrivate,
+ }
+ : prev,
+ );
+ }}
/>
</div>
</div>
@@ -170,7 +199,11 @@ export default function SlackIntegrationSettings() {
{!selectedChannel && (
<div className="text-muted-foreground text-sm">
Select a channel above to view its details and test message
- delivery.
+ delivery. For private channels, invite the app first with{" "}
+ <code className="bg-muted rounded px-1 py-0.5">
+ /invite @Langfuse
+ </code>{" "}
+ in that channel.
</div>
)}
</CardContent>