Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

AI support chats to slack threads

Pedro Ladeirae67cd7711e50
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 033f320ab9..ba9e1f185e 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -115,6 +115,9 @@ DUB_SLACK_HOOK_LINKS=
# Slack Dub Support integration
DUB_SLACK_ASSISTANT_BOT_TOKEN=
+# Slack channel ID that mirrors AI support chat conversations
+DUB_SLACK_SUPPORT_CHAT_CHANNEL_ID=
+
# Used for background jobs
# Get your ngrok URL here: https://ngrok.com/
NEXT_PUBLIC_NGROK_URL=
diff --git a/apps/web/app/api/ai/support-chat/route.ts b/apps/web/app/api/ai/support-chat/route.ts
index 21c7f531a5..539e9634d8 100644
--- a/apps/web/app/api/ai/support-chat/route.ts
+++ b/apps/web/app/api/ai/support-chat/route.ts
@@ -9,6 +9,7 @@ import { getProgramPerformanceTool } from "@/lib/ai/get-program-performance";
import { getWorkspaceDetailsTool } from "@/lib/ai/get-workspace-details";
import { requestSupportTicketTool } from "@/lib/ai/request-support-ticket";
import { withSession } from "@/lib/auth";
+import { getSlackClient } from "@/lib/slack/client";
import { ratelimit } from "@/lib/upstash/ratelimit";
import { anthropic } from "@ai-sdk/anthropic";
import { convertToModelMessages, stepCountIs, streamText, UIMessage } from "ai";
@@ -44,6 +45,14 @@ export const POST = withSession(async ({ req, session }) => {
}
const ticketDetails: string | undefined = body.ticketDetails?.slice(0, 4982);
+ if (
+ body.slackThreadTs !== undefined &&
+ (typeof body.slackThreadTs !== "string" || body.slackThreadTs.length > 64)
+ ) {
+ return new Response("Invalid slackThreadTs", { status: 400 });
+ }
+ const incomingSlackThreadTs: string | undefined = body.slackThreadTs;
+
const { success } = await ratelimit(5, "30 s").limit(
`support-chat:${session.user.id}`,
);
@@ -51,6 +60,37 @@ export const POST = withSession(async ({ req, session }) => {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
+ const slackChannel = process.env.DUB_SLACK_SUPPORT_CHAT_CHANNEL_ID;
+ let slackThreadTs = incomingSlackThreadTs;
+
+ if (slackChannel) {
+ const latestUserText =
+ messages[messages.length - 1].parts
+ ?.filter((p): p is { type: "text"; text: string } => p.type === "text")
+ .map((p) => p.text)
+ .join("\n\n") ?? "";
+ const userLabel = session.user.name || session.user.email || "Unknown user";
+
+ if (!slackThreadTs) {
+ slackThreadTs = await postSupportChatMessage({
+ channel: slackChannel,
+ text: [
+ `:speech_balloon: *New AI Support Chat*`,
+ ...getAccountContextLines(globalContext),
+ `${userLabel} (${session.user.email})`,
+ "",
+ `${userLabel}: ${latestUserText}`,
+ ].join("\n"),
+ });
+ } else {
+ await postSupportChatMessage({
+ channel: slackChannel,
+ threadTs: slackThreadTs,
+ text: `*${userLabel}:* ${latestUserText}`,
+ });
+ }
+ }
+
const result = streamText({
model: anthropic("claude-sonnet-4-6"),
system: buildSystemPrompt(globalContext),
@@ -73,7 +113,60 @@ export const POST = withSession(async ({ req, session }) => {
ticketDetails,
}),
},
+ onFinish: async ({ text }) => {
+ if (slackChannel && slackThreadTs && text) {
+ await postSupportChatMessage({
+ channel: slackChannel,
+ threadTs: slackThreadTs,
+ text: `*Dub AI:* ${text}`,
+ });
+ }
+ },
});
- return result.toUIMessageStreamResponse();
+ return result.toUIMessageStreamResponse({
+ messageMetadata: ({ part }) => {
+ if (part.type === "start" && slackThreadTs) {
+ return { slackThreadTs };
+ }
+ },
+ });
});
+
+const postSupportChatMessage = async ({
+ channel,
+ threadTs,
+ text,
+}: {
+ channel: string;
+ threadTs?: string;
+ text: string;
+}): Promise<string | undefined> => {
+ try {
+ const slack = getSlackClient();
+ const res = await slack.chat.postMessage({
+ channel,
+ thread_ts: threadTs,
+ text: text.slice(0, 3000),
+ unfurl_links: false,
+ });
+ return (res.ts as string | undefined) ?? threadTs;
+ } catch (e) {
+ console.error("[Slack] Failed to post support chat message", e);
+ return threadTs;
+ }
+};
+
+const getAccountContextLines = (globalContext?: GlobalChatContext) => {
+ if (globalContext?.selectedWorkspace) {
+ const { name, slug } = globalContext.selectedWorkspace;
+ return [`:briefcase: *Workspace* - ${name} (${slug})`];
+ }
+
+ if (globalContext?.selectedProgram) {
+ const { name, slug } = globalContext.selectedProgram;
+ return [`:handshake: *Partners* - ${name} (${slug})`];
+ }
+
+ return [globalContext?.chatLocation ?? "Unknown context"];
+};
diff --git a/apps/web/ui/support/chat-interface.tsx b/apps/web/ui/support/chat-interface.tsx
index 644e00debb..0aed6c19f0 100644
--- a/apps/web/ui/support/chat-interface.tsx
+++ b/apps/web/ui/support/chat-interface.tsx
@@ -141,6 +141,16 @@ export function ChatInterface({
}
};
+ const getSlackThreadTs = () => {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const meta = (messages[i] as any).metadata as
+ | { slackThreadTs?: string }
+ | undefined;
+ if (meta?.slackThreadTs) return meta.slackThreadTs;
+ }
+ return undefined;
+ };
+
const handleSend = (text?: string) => {
const messageText = text ?? input;
if (!messageText.trim() || status === "streaming" || !canChat) return;
@@ -154,6 +164,7 @@ export function ChatInterface({
effectiveAccountType === "partner" ? "partners" : "app",
accountType: effectiveAccountType,
},
+ slackThreadTs: getSlackThreadTs(),
},
},
);
@@ -175,6 +186,7 @@ export function ChatInterface({
effectiveAccountType === "partner" ? "partners" : "app",
accountType: effectiveAccountType,
},
+ slackThreadTs: getSlackThreadTs(),
...(attachmentIds.length ? { attachmentIds } : {}),
...(details ? { ticketDetails: details } : {}),
},