-
Notifications
You must be signed in to change notification settings - Fork 899
feat(api): Slack integration with AI agent #1027
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
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
215df83
WIP
saddlepaddle 963a4a2
WIP - untested could be jank
saddlepaddle 9d4be79
WIP - untested could be jank
saddlepaddle 9502566
feat(slack): add Slack integration UI pages and clean up hardcoded URLs
saddlepaddle 564e60e
WIP - untested could be jank
saddlepaddle ae43f0e
refactor(slack): co-locate Slack API code per project conventions
saddlepaddle af5f313
refactor(slack): clean up dead code, comments, dev bypasses, and hard…
saddlepaddle 574d322
Merge remote-tracking branch 'origin/main' into satya-patel/slack-int…
saddlepaddle 9dcde4a
fix(docs): handle ReactNode type for fumadocs page tree node names
saddlepaddle 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
116 changes: 116 additions & 0 deletions
116
apps/api/src/app/api/integrations/slack/callback/route.ts
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,116 @@ | ||
| import { WebClient } from "@slack/web-api"; | ||
| import { db } from "@superset/db/client"; | ||
| import type { SlackConfig } from "@superset/db/schema"; | ||
| import { integrationConnections, members } from "@superset/db/schema"; | ||
| import { and, eq } from "drizzle-orm"; | ||
|
|
||
| import { env } from "@/env"; | ||
| import { verifySignedState } from "@/lib/oauth-state"; | ||
|
|
||
| export async function GET(request: Request) { | ||
| const url = new URL(request.url); | ||
| const code = url.searchParams.get("code"); | ||
| const state = url.searchParams.get("state"); | ||
| const error = url.searchParams.get("error"); | ||
|
|
||
| if (error) { | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=oauth_denied`, | ||
| ); | ||
| } | ||
|
|
||
| if (!code || !state) { | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=missing_params`, | ||
| ); | ||
| } | ||
|
|
||
| const stateData = verifySignedState(state); | ||
| if (!stateData) { | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=invalid_state`, | ||
| ); | ||
| } | ||
|
|
||
| const { organizationId, userId } = stateData; | ||
|
|
||
| // Re-verify membership at callback time (state was signed earlier) | ||
| const membership = await db.query.members.findFirst({ | ||
| where: and( | ||
| eq(members.organizationId, organizationId), | ||
| eq(members.userId, userId), | ||
| ), | ||
| }); | ||
|
|
||
| if (!membership) { | ||
| console.error("[slack/callback] Membership verification failed:", { | ||
| organizationId, | ||
| userId, | ||
| }); | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=unauthorized`, | ||
| ); | ||
| } | ||
|
|
||
| const redirectUri = `${env.NEXT_PUBLIC_API_URL}/api/integrations/slack/callback`; | ||
| const client = new WebClient(); | ||
|
|
||
| try { | ||
| const tokenData = await client.oauth.v2.access({ | ||
| client_id: env.SLACK_CLIENT_ID, | ||
| client_secret: env.SLACK_CLIENT_SECRET, | ||
| redirect_uri: redirectUri, | ||
| code, | ||
| }); | ||
|
|
||
| if (!tokenData.ok || !tokenData.access_token || !tokenData.team) { | ||
| console.error("[slack/callback] Slack API error:", tokenData.error); | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=slack_api_error`, | ||
| ); | ||
| } | ||
|
|
||
| const config: SlackConfig = { | ||
| provider: "slack", | ||
| }; | ||
|
|
||
| await db | ||
| .insert(integrationConnections) | ||
| .values({ | ||
| organizationId, | ||
| connectedByUserId: userId, | ||
| provider: "slack", | ||
| accessToken: tokenData.access_token, | ||
| externalOrgId: tokenData.team.id, | ||
| externalOrgName: tokenData.team.name, | ||
| config, | ||
| }) | ||
| .onConflictDoUpdate({ | ||
| target: [ | ||
| integrationConnections.organizationId, | ||
| integrationConnections.provider, | ||
| ], | ||
| set: { | ||
| accessToken: tokenData.access_token, | ||
| externalOrgId: tokenData.team.id, | ||
| externalOrgName: tokenData.team.name, | ||
| connectedByUserId: userId, | ||
| config, | ||
| updatedAt: new Date(), | ||
| }, | ||
| }); | ||
|
|
||
| console.log("[slack/callback] Connected workspace:", { | ||
| organizationId, | ||
| teamId: tokenData.team.id, | ||
| teamName: tokenData.team.name, | ||
| }); | ||
|
|
||
| return Response.redirect(`${env.NEXT_PUBLIC_WEB_URL}/integrations/slack`); | ||
| } catch (error) { | ||
| console.error("[slack/callback] Token exchange failed:", error); | ||
| return Response.redirect( | ||
| `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=token_exchange_failed`, | ||
| ); | ||
| } | ||
| } | ||
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,73 @@ | ||
| import { auth } from "@superset/auth/server"; | ||
| import { db } from "@superset/db/client"; | ||
| import { members } from "@superset/db/schema"; | ||
| import { and, eq } from "drizzle-orm"; | ||
|
|
||
| import { env } from "@/env"; | ||
| import { createSignedState } from "@/lib/oauth-state"; | ||
|
|
||
| const SLACK_SCOPES = [ | ||
| "app_mentions:read", | ||
| "chat:write", | ||
| "reactions:write", | ||
| "channels:history", | ||
| "groups:history", | ||
| "im:history", | ||
| "im:read", | ||
| "im:write", | ||
| "mpim:history", | ||
| "users:read", | ||
| "assistant:write", | ||
| "links:read", | ||
| "links:write", | ||
| ].join(","); | ||
|
|
||
| export async function GET(request: Request) { | ||
| const url = new URL(request.url); | ||
| const organizationId = url.searchParams.get("organizationId"); | ||
| if (!organizationId) { | ||
| return Response.json( | ||
| { error: "Missing organizationId parameter" }, | ||
| { status: 400 }, | ||
| ); | ||
| } | ||
|
|
||
| const session = await auth.api.getSession({ | ||
| headers: request.headers, | ||
| }); | ||
|
|
||
| if (!session?.user) { | ||
| return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
| } | ||
|
|
||
| const userId = session.user.id; | ||
|
|
||
| const membership = await db.query.members.findFirst({ | ||
| where: and( | ||
| eq(members.organizationId, organizationId), | ||
| eq(members.userId, userId), | ||
| ), | ||
| }); | ||
|
|
||
| if (!membership) { | ||
| return Response.json( | ||
| { error: "User is not a member of this organization" }, | ||
| { status: 403 }, | ||
| ); | ||
| } | ||
|
|
||
| const state = createSignedState({ | ||
| organizationId, | ||
| userId, | ||
| }); | ||
|
|
||
| const redirectUri = `${env.NEXT_PUBLIC_API_URL}/api/integrations/slack/callback`; | ||
|
|
||
| const slackAuthUrl = new URL("https://slack.com/oauth/v2/authorize"); | ||
| slackAuthUrl.searchParams.set("client_id", env.SLACK_CLIENT_ID); | ||
| slackAuthUrl.searchParams.set("redirect_uri", redirectUri); | ||
| slackAuthUrl.searchParams.set("scope", SLACK_SCOPES); | ||
| slackAuthUrl.searchParams.set("state", state); | ||
|
|
||
| return Response.redirect(slackAuthUrl.toString()); | ||
| } |
1 change: 1 addition & 0 deletions
1
apps/api/src/app/api/integrations/slack/events/process-assistant-message/index.ts
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 @@ | ||
| export { processAssistantMessage } from "./process-assistant-message"; |
97 changes: 97 additions & 0 deletions
97
.../app/api/integrations/slack/events/process-assistant-message/process-assistant-message.ts
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,97 @@ | ||
| import type { GenericMessageEvent } from "@slack/types"; | ||
| import { db } from "@superset/db/client"; | ||
| import { integrationConnections } from "@superset/db/schema"; | ||
| import { and, eq } from "drizzle-orm"; | ||
| import { runSlackAgent } from "../utils/run-agent"; | ||
| import { formatActionsAsText } from "../utils/slack-blocks"; | ||
| import { createSlackClient } from "../utils/slack-client"; | ||
|
|
||
| interface ProcessAssistantMessageParams { | ||
| event: GenericMessageEvent; | ||
| teamId: string; | ||
| eventId: string; | ||
| } | ||
|
|
||
| export async function processAssistantMessage({ | ||
| event, | ||
| teamId, | ||
| eventId, | ||
| }: ProcessAssistantMessageParams): Promise<void> { | ||
| console.log("[slack/process-assistant-message] Processing message:", { | ||
| eventId, | ||
| teamId, | ||
| channel: event.channel, | ||
| user: event.user, | ||
| }); | ||
|
|
||
| const connection = await db.query.integrationConnections.findFirst({ | ||
| where: and( | ||
| eq(integrationConnections.provider, "slack"), | ||
| eq(integrationConnections.externalOrgId, teamId), | ||
| ), | ||
| }); | ||
|
|
||
| if (!connection) { | ||
| console.error( | ||
| "[slack/process-assistant-message] No connection found for team:", | ||
| teamId, | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| const slack = createSlackClient(connection.accessToken); | ||
|
|
||
| const threadTs = event.thread_ts ?? event.ts; | ||
|
|
||
| try { | ||
| await slack.assistant.threads.setStatus({ | ||
| channel_id: event.channel, | ||
| thread_ts: threadTs, | ||
| status: "Thinking...", | ||
| }); | ||
| } catch (err) { | ||
| console.warn( | ||
| "[slack/process-assistant-message] Failed to set status:", | ||
| err, | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| const result = await runSlackAgent({ | ||
| prompt: event.text ?? "", | ||
| channelId: event.channel, | ||
| threadTs, | ||
| organizationId: connection.organizationId, | ||
| slackToken: connection.accessToken, | ||
| slackTeamId: teamId, | ||
| }); | ||
|
|
||
| // Format actions as text with URLs (enables Slack unfurling) | ||
| const hasActions = result.actions.length > 0; | ||
| const responseText = hasActions | ||
| ? formatActionsAsText(result.actions) | ||
| : result.text; | ||
|
|
||
| await slack.chat.postMessage({ | ||
| channel: event.channel, | ||
| thread_ts: threadTs, | ||
| text: responseText, | ||
| }); | ||
| } catch (err) { | ||
| console.error("[slack/process-assistant-message] Agent error:", err); | ||
|
|
||
| await slack.chat.postMessage({ | ||
| channel: event.channel, | ||
| thread_ts: threadTs, | ||
| text: `Sorry, something went wrong: ${err instanceof Error ? err.message : "Unknown error"}`, | ||
| }); | ||
| } finally { | ||
| try { | ||
| await slack.assistant.threads.setStatus({ | ||
| channel_id: event.channel, | ||
| thread_ts: threadTs, | ||
| status: "", | ||
| }); | ||
| } catch {} | ||
| } | ||
| } |
1 change: 1 addition & 0 deletions
1
apps/api/src/app/api/integrations/slack/events/process-entity-details/index.ts
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 @@ | ||
| export { processEntityDetails } from "./process-entity-details"; |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: superset-sh/superset
Length of output: 4751
Add Zod parsing for OAuth callback query params.
Guidelines call for Zod validation at API boundaries; validate
codeandstateas non-empty before use.🔧 Suggested fix
import { integrationConnections, members } from "@superset/db/schema"; import { and, eq } from "drizzle-orm"; +import { z } from "zod"; @@ interface SlackOAuthResponse { @@ } +const callbackParamsSchema = z.object({ + code: z.string().min(1), + state: z.string().min(1), +}); + export async function GET(request: Request) { const url = new URL(request.url); - const code = url.searchParams.get("code"); - const state = url.searchParams.get("state"); const error = url.searchParams.get("error"); + const parsedParams = callbackParamsSchema.safeParse({ + code: url.searchParams.get("code"), + state: url.searchParams.get("state"), + }); + if (!parsedParams.success) { + return Response.redirect( + `${env.NEXT_PUBLIC_WEB_URL}/integrations/slack?error=missing_params`, + ); + } + const { code, state } = parsedParams.data;As per coding guidelines: Validate at boundaries using Zod schemas for tRPC inputs and API route bodies.
📝 Committable suggestion
🤖 Prompt for AI Agents