🪢 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): paginate channel loading (#14583)
Tobias Wochinger0be915a5d5f8
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex fd33b4035a..48693e58ef 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -409,14 +409,6 @@ const EnvSchema = z.object({SLACK_CLIENT_ID: z.string().optional(),SLACK_CLIENT_SECRET: z.string().optional(),SLACK_STATE_SECRET: z.string().optional(),- SLACK_FETCH_LIMIT: z.coerce- .number()- .positive()- .optional()- .default(5_000)- .describe(- "How many records should be fetched from Slack, before we give up",- ),SLACK_PAGE_SIZE: z.coerce.number().positive()diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.tsindex d1d0cdde54..c01359b60b 100644--- a/packages/shared/src/server/services/SlackService.ts+++ b/packages/shared/src/server/services/SlackService.ts@@ -47,6 +47,7 @@ export interface SlackChannel {export interface GetChannelsResult {channels: SlackChannel[];hasPrivateChannelAccess: boolean;+ nextCursor?: string;}/** SlackMessage is the Block Kit payload sent to Slack. */@@ -339,15 +340,14 @@ export class SlackService {}/**- * Recursively fetch all channels accessible to the bot- * Uses cursor-based pagination defined by Slack API https://api.slack.com/apis/pagination+ * Fetch one page of channels accessible to the bot.+ * Uses cursor-based pagination defined by Slack API https://api.slack.com/apis/pagination.*/- private async getChannelsRecursive(+ private async getChannelsPage(client: WebClient,channelTypes = "public_channel,private_channel",cursor?: string,- fetchedRecords = 0,- ): Promise<SlackChannel[]> {+ ): Promise<Omit<GetChannelsResult, "hasPrivateChannelAccess">> {try {const result = await client.conversations.list({exclude_archived: true,@@ -370,28 +370,12 @@ export class SlackService {);const nextCursor = result.response_metadata?.next_cursor;- if (- nextCursor &&- fetchedRecords + channels.length < env.SLACK_FETCH_LIMIT- ) {- try {- const nextPageChannels = await this.getChannelsRecursive(- client,- channelTypes,- nextCursor,- fetchedRecords + channels.length,- );- return channels.concat(nextPageChannels);- } catch (error) {- logger.error(- `Failed to retrieve next page of channels, returning only already fetched`,- error,- );- }- }- return channels;+ return {+ channels,+ nextCursor: nextCursor || undefined,+ };} catch (error) {- logger.error("Failed to fetch channels recursively", { error, cursor });+ logger.error("Failed to fetch Slack channels page", { error, cursor });throw error;}}@@ -399,18 +383,23 @@ export class SlackService {/*** Get channels accessible to the bot.*/- async getChannels(client: WebClient): Promise<GetChannelsResult> {+ async getChannels(+ client: WebClient,+ cursor?: string,+ ): Promise<GetChannelsResult> {try {- const channels = await this.getChannelsRecursive(+ const { channels, nextCursor } = await this.getChannelsPage(client,"public_channel,private_channel",+ cursor,);logger.debug("Retrieved channels from Slack", {channelCount: channels.length,+ hasNextPage: Boolean(nextCursor),});- return { channels, hasPrivateChannelAccess: true };+ 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.@@ -424,12 +413,13 @@ export class SlackService {);try {- const channels = await this.getChannelsRecursive(+ const { channels, nextCursor } = await this.getChannelsPage(client,"public_channel",+ cursor,);- return { channels, hasPrivateChannelAccess: false };+ return { channels, hasPrivateChannelAccess: false, nextCursor };} catch (fallbackError) {logger.error("Failed to fetch public channels fallback", {error: fallbackError,diff --git a/web/src/features/slack/components/ChannelSelector.tsx b/web/src/features/slack/components/ChannelSelector.tsxindex c9062e6f45..7c2fac84f6 100644--- a/web/src/features/slack/components/ChannelSelector.tsx+++ b/web/src/features/slack/components/ChannelSelector.tsx@@ -7,7 +7,6 @@ import {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,CommandEmpty,@@ -47,6 +46,61 @@ interface ChannelSelectorProps {}const ITEM_HEIGHT = 32;+const MAX_SLACK_CHANNEL_PAGES = 20;++const useSlackChannels = (projectId: string) => {+ const {+ data: channelsPages,+ isLoading,+ isFetching,+ isFetchingNextPage,+ hasNextPage,+ fetchNextPage,+ error,+ refetch: refetchChannels,+ } = api.slack.getChannels.useInfiniteQuery(+ { projectId },+ {+ enabled: !!projectId,+ getNextPageParam: (lastPage, allPages) =>+ allPages.length >= MAX_SLACK_CHANNEL_PAGES+ ? undefined+ : lastPage.nextCursor,+ staleTime: 5 * 60 * 1000,+ },+ );++ const channelsData = useMemo(() => {+ const pages = channelsPages?.pages ?? [];+ if (pages.length === 0) return null;++ return {+ channels: pages.flatMap((page) => page.channels),+ hasPrivateChannelAccess: pages.every(+ (page) => page.hasPrivateChannelAccess,+ ),+ };+ }, [channelsPages?.pages]);++ const isLoadingChannels =+ isLoading || isFetchingNextPage || (isFetching && !channelsData);++ // useInfiniteQuery stores page state, but next pages are only loaded when requested.+ useEffect(() => {+ if (error || !hasNextPage || isFetchingNextPage) return;++ fetchNextPage().catch((error) => {+ console.error("Failed to load next Slack channels page", error);+ });+ }, [error, fetchNextPage, hasNextPage, isFetchingNextPage]);++ return {+ channelsData,+ isLoadingChannels,+ error,+ refetchChannels,+ };+};/*** A dropdown component for selecting Slack channels with search and filtering capabilities.@@ -92,19 +146,8 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({const effectiveName = trimmedSearch.replace(/^#/, "");// Get available channels- const {- data: channelsData,- isLoading,- error,- refetch: refetchChannels,- } = api.slack.getChannels.useQuery(- { projectId },- {- enabled: !!projectId,- // Keep data fresh- staleTime: 5 * 60 * 1000, // 5 minutes- },- );+ const { channelsData, isLoadingChannels, error, refetchChannels } =+ useSlackChannels(projectId);// Handle refreshconst handleRefresh = async () => {@@ -203,52 +246,6 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({</div>);- // Handle loading state- if (isLoading) {- return (- <div className="space-y-2">- <div className="flex items-center gap-2">- <Select disabled>- <SelectTrigger>- <SelectValue placeholder="Loading channels..." />- </SelectTrigger>- </Select>- {showRefreshButton && (- <Button variant="outline" size="sm" disabled>- <RefreshCw className="h-4 w-4" />- </Button>- )}- </div>- </div>- );- }-- // Handle error state- if (error) {- return (- <div className="space-y-2">- <div className="flex items-center gap-2">- <Select disabled>- <SelectTrigger>- <SelectValue placeholder="Error loading channels" />- </SelectTrigger>- </Select>- {showRefreshButton && (- <Button variant="outline" size="sm" onClick={handleRefresh}>- <RefreshCw className="h-4 w-4" />- </Button>- )}- </div>- <Alert>- <AlertDescription>- Failed to load channels. Please check your Slack connection and try- again.- </AlertDescription>- </Alert>- </div>- );- }-const hasExactMatch = filteredChannels.some((channel) => channel.name.toLowerCase() === effectiveName.toLowerCase(),);@@ -304,9 +301,11 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({</CommandItem></CommandGroup>)}- {!canUseTypedName && filteredChannels.length === 0 && (- <CommandEmpty>No channels available.</CommandEmpty>- )}+ {!isLoadingChannels &&+ !canUseTypedName &&+ filteredChannels.length === 0 && (+ <CommandEmpty>No channels available.</CommandEmpty>+ )}<CommandGroupclassName="p-0"style={{@@ -335,6 +334,21 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({);})}</CommandGroup>+ {isLoadingChannels && (+ <CommandGroup className="p-0">+ <CommandItem+ value="loading-slack-channels"+ disabled+ className="text-muted-foreground"+ >+ <RefreshCw className="h-4 w-4 animate-spin" />+ <span className="flex-1 truncate">+ Loading Slack channels. This can take a while for large+ workspaces.+ </span>+ </CommandItem>+ </CommandGroup>+ )}</CommandList></Command></PopoverContent>@@ -345,21 +359,30 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({variant="outline"size="sm"onClick={handleRefresh}- disabled={disabled || isRefreshing}+ disabled={disabled || isRefreshing || isLoadingChannels}><RefreshCw- className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`}+ className={`h-4 w-4 ${isRefreshing || isLoadingChannels ? "animate-spin" : ""}`}/></Button>)}</div>{/* Channel stats */}- {channelsData?.channels && (+ {channelsData?.channels && !isLoadingChannels ? (<div className="text-muted-foreground text-xs">{filteredChannels.length} of {channelsData.channels.length} channels{memberOnly && " (member only)"}</div>+ ) : null}++ {error && (+ <Alert>+ <AlertDescription>+ Failed to load channels. You can still enter a channel name+ manually, or check your Slack connection and try again.+ </AlertDescription>+ </Alert>)}{/* Private channel scope warning */}diff --git a/web/src/features/slack/server/router.ts b/web/src/features/slack/server/router.tsindex 83cd660156..ecf2c1ffc0 100644--- a/web/src/features/slack/server/router.ts+++ b/web/src/features/slack/server/router.ts@@ -88,7 +88,7 @@ export const slackRouter = createTRPCRouter({* Get channels for a project's Slack integration*/getChannels: protectedProjectProcedure- .input(z.object({ projectId: z.string() }))+ .input(z.object({ projectId: z.string(), cursor: z.string().optional() })).query(async ({ ctx, input }) => {throwIfNoProjectAccess({session: ctx.session,@@ -112,20 +112,27 @@ export const slackRouter = createTRPCRouter({const client = await slackService.getWebClientForProject(input.projectId,);- const { channels, hasPrivateChannelAccess } =- await slackService.getChannels(client);-- await auditLog({- session: ctx.session,- resourceType: "slackIntegration",- resourceId: integration.id,- action: "read",- after: { action: "channels_fetched", channelCount: channels.length },- });+ const { channels, hasPrivateChannelAccess, nextCursor } =+ await slackService.getChannels(client, input.cursor);++ if (!input.cursor) {+ await auditLog({+ session: ctx.session,+ resourceType: "slackIntegration",+ resourceId: integration.id,+ action: "read",+ after: {+ action: "channels_fetched",+ channelCount: channels.length,+ hasNextPage: Boolean(nextCursor),+ },+ });+ }return {channels,hasPrivateChannelAccess,+ nextCursor,teamId: integration.teamId,teamName: integration.teamName,};