-
Notifications
You must be signed in to change notification settings - Fork 3.8k
feat(slack): added slack oauth for sim bot & maintained old custom bot, fixed markdown rendering #445
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat(slack): added slack oauth for sim bot & maintained old custom bot, fixed markdown rendering #445
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4293470
fix formatting of contributors chart
waleedlatif1 d81fc39
added slack oauth, removed hardcoded localhosts and use NEXT_PUBLIC_A…
waleedlatif1 8a06a36
remove conditional rendering of subblocks for tools in an agent blcok
waleedlatif1 43ca17e
updated tests
waleedlatif1 cbb59ba
added permission to read private channels that bot was invited to
waleedlatif1 e422f93
acknowledge PR comments, added additional typing & fallbacks
waleedlatif1 db82ca6
fixed build error
waleedlatif1 5c40fef
remove fallback logic for password fields
waleedlatif1 7f27de1
reverted changes to middleware
waleedlatif1 f16c4ae
cleanup
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import { NextResponse } from 'next/server' | ||
| import { getSession } from '@/lib/auth' | ||
| import { createLogger } from '@/lib/logs/console-logger' | ||
| import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| const logger = createLogger('SlackChannelsAPI') | ||
|
|
||
| interface SlackChannel { | ||
| id: string | ||
| name: string | ||
| is_private: boolean | ||
| is_archived: boolean | ||
| is_member: boolean | ||
| } | ||
|
|
||
| export async function POST(request: Request) { | ||
| try { | ||
| const session = await getSession() | ||
| const body = await request.json() | ||
| const { credential, workflowId } = body | ||
|
|
||
| if (!credential) { | ||
| logger.error('Missing credential in request') | ||
| return NextResponse.json({ error: 'Credential is required' }, { status: 400 }) | ||
| } | ||
|
|
||
| let accessToken: string | ||
| let isBotToken = false | ||
|
|
||
| if (credential.startsWith('xoxb-')) { | ||
| accessToken = credential | ||
| isBotToken = true | ||
| logger.info('Using direct bot token for Slack API') | ||
| } else { | ||
| const userId = session?.user?.id || '' | ||
| if (!userId) { | ||
| logger.error('No user ID found in session') | ||
| return NextResponse.json({ error: 'Authentication required' }, { status: 401 }) | ||
| } | ||
|
|
||
| const resolvedToken = await refreshAccessTokenIfNeeded(credential, userId, workflowId) | ||
| if (!resolvedToken) { | ||
| logger.error('Failed to get access token', { credentialId: credential, userId }) | ||
| return NextResponse.json( | ||
| { | ||
| error: 'Could not retrieve access token', | ||
| authRequired: true, | ||
| }, | ||
| { status: 401 } | ||
| ) | ||
| } | ||
| accessToken = resolvedToken | ||
| logger.info('Using OAuth token for Slack API') | ||
| } | ||
|
|
||
| let data | ||
| try { | ||
| data = await fetchSlackChannels(accessToken, true) | ||
| logger.info('Successfully fetched channels including private channels') | ||
| } catch (error) { | ||
| if (isBotToken) { | ||
| logger.warn( | ||
| 'Failed to fetch private channels with bot token, falling back to public channels only:', | ||
| (error as Error).message | ||
| ) | ||
| try { | ||
| data = await fetchSlackChannels(accessToken, false) | ||
| logger.info('Successfully fetched public channels only') | ||
| } catch (fallbackError) { | ||
| logger.error('Failed to fetch channels even with public-only fallback:', fallbackError) | ||
| return NextResponse.json( | ||
| { error: `Slack API error: ${(fallbackError as Error).message}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| } else { | ||
| logger.error('Slack API error with OAuth token:', error) | ||
| return NextResponse.json( | ||
| { error: `Slack API error: ${(error as Error).message}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // Filter to channels the bot can access and format the response | ||
| const channels = (data.channels || []) | ||
| .filter((channel: SlackChannel) => { | ||
| const canAccess = !channel.is_archived && (channel.is_member || !channel.is_private) | ||
|
|
||
| if (!canAccess) { | ||
| logger.debug( | ||
| `Filtering out channel: ${channel.name} (archived: ${channel.is_archived}, private: ${channel.is_private}, member: ${channel.is_member})` | ||
| ) | ||
| } | ||
|
|
||
| return canAccess | ||
| }) | ||
| .map((channel: SlackChannel) => ({ | ||
| id: channel.id, | ||
| name: channel.name, | ||
| isPrivate: channel.is_private, | ||
| })) | ||
|
|
||
| logger.info(`Successfully fetched ${channels.length} Slack channels`, { | ||
| total: data.channels?.length || 0, | ||
| private: channels.filter((c: { isPrivate: boolean }) => c.isPrivate).length, | ||
| public: channels.filter((c: { isPrivate: boolean }) => !c.isPrivate).length, | ||
| tokenType: isBotToken ? 'bot_token' : 'oauth', | ||
| }) | ||
| return NextResponse.json({ channels }) | ||
| } catch (error) { | ||
| logger.error('Error processing Slack channels request:', error) | ||
| return NextResponse.json( | ||
| { error: 'Failed to retrieve Slack channels', details: (error as Error).message }, | ||
| { status: 500 } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| ) | ||
| } | ||
| } | ||
|
|
||
| async function fetchSlackChannels(accessToken: string, includePrivate = true) { | ||
| const url = new URL('https://slack.com/api/conversations.list') | ||
|
|
||
| if (includePrivate) { | ||
| url.searchParams.append('types', 'public_channel,private_channel') | ||
| } else { | ||
| url.searchParams.append('types', 'public_channel') | ||
| } | ||
|
|
||
| url.searchParams.append('exclude_archived', 'true') | ||
| url.searchParams.append('limit', '200') | ||
|
|
||
| const response = await fetch(url.toString(), { | ||
| method: 'GET', | ||
| headers: { | ||
| Authorization: `Bearer ${accessToken}`, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`Slack API error: ${response.status} ${response.statusText}`) | ||
| } | ||
|
|
||
| const data = await response.json() | ||
|
|
||
| if (!data.ok) { | ||
| throw new Error(data.error || 'Failed to fetch channels') | ||
| } | ||
|
|
||
| return data | ||
| } | ||
104 changes: 104 additions & 0 deletions
104
...orkflow-block/components/sub-block/components/channel-selector/channel-selector-input.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| 'use client' | ||
|
|
||
| import { useEffect, useState } from 'react' | ||
| import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' | ||
| import type { SubBlockConfig } from '@/blocks/types' | ||
| import { useSubBlockStore } from '@/stores/workflows/subblock/store' | ||
| import { type SlackChannelInfo, SlackChannelSelector } from './components/slack-channel-selector' | ||
|
|
||
| interface ChannelSelectorInputProps { | ||
| blockId: string | ||
| subBlock: SubBlockConfig | ||
| disabled?: boolean | ||
| onChannelSelect?: (channelId: string) => void | ||
| credential?: string // Optional credential override | ||
| } | ||
|
|
||
| export function ChannelSelectorInput({ | ||
| blockId, | ||
| subBlock, | ||
| disabled = false, | ||
| onChannelSelect, | ||
| credential: providedCredential, | ||
| }: ChannelSelectorInputProps) { | ||
| const { getValue, setValue } = useSubBlockStore() | ||
| const [selectedChannelId, setSelectedChannelId] = useState<string>('') | ||
| const [_channelInfo, setChannelInfo] = useState<SlackChannelInfo | null>(null) | ||
|
|
||
| // Get provider-specific values | ||
| const provider = subBlock.provider || 'slack' | ||
| const isSlack = provider === 'slack' | ||
|
|
||
| // Get the credential for the provider - use provided credential or fall back to store | ||
| const authMethod = getValue(blockId, 'authMethod') as string | ||
| const botToken = getValue(blockId, 'botToken') as string | ||
|
|
||
| let credential: string | ||
| if (providedCredential) { | ||
| credential = providedCredential | ||
| } else if (authMethod === 'bot_token' && botToken) { | ||
| credential = botToken | ||
| } else { | ||
| credential = (getValue(blockId, 'credential') as string) || '' | ||
| } | ||
|
|
||
| // Get the current value from the store | ||
| useEffect(() => { | ||
| const value = getValue(blockId, subBlock.id) | ||
| if (value && typeof value === 'string') { | ||
| setSelectedChannelId(value) | ||
| } | ||
| }, [blockId, subBlock.id, getValue]) | ||
|
|
||
| // Handle channel selection | ||
| const handleChannelChange = (channelId: string, info?: SlackChannelInfo) => { | ||
| setSelectedChannelId(channelId) | ||
| setChannelInfo(info || null) | ||
| setValue(blockId, subBlock.id, channelId) | ||
| onChannelSelect?.(channelId) | ||
| } | ||
|
|
||
| // Render Slack channel selector | ||
| if (isSlack) { | ||
| return ( | ||
| <TooltipProvider> | ||
| <Tooltip> | ||
| <TooltipTrigger asChild> | ||
| <div className='w-full'> | ||
| <SlackChannelSelector | ||
| value={selectedChannelId} | ||
| onChange={(channelId: string, channelInfo?: SlackChannelInfo) => { | ||
| handleChannelChange(channelId, channelInfo) | ||
| }} | ||
| credential={credential} | ||
| label={subBlock.placeholder || 'Select Slack channel'} | ||
| disabled={disabled || !credential} | ||
| /> | ||
| </div> | ||
| </TooltipTrigger> | ||
| {!credential && ( | ||
| <TooltipContent side='top'> | ||
| <p>Please select a Slack account or enter a bot token first</p> | ||
| </TooltipContent> | ||
| )} | ||
| </Tooltip> | ||
| </TooltipProvider> | ||
| ) | ||
| } | ||
|
|
||
| // Default fallback for unsupported providers | ||
| return ( | ||
| <TooltipProvider> | ||
| <Tooltip> | ||
| <TooltipTrigger asChild> | ||
| <div className='w-full rounded border border-dashed p-4 text-center text-muted-foreground text-sm'> | ||
| Channel selector not supported for provider: {provider} | ||
| </div> | ||
| </TooltipTrigger> | ||
| <TooltipContent side='top'> | ||
| <p>This channel selector is not yet implemented for {provider}</p> | ||
| </TooltipContent> | ||
| </Tooltip> | ||
| </TooltipProvider> | ||
| ) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.