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.

Embeddable support chat (#3517)

Pedro Ladeira889daa55f815
diff --git a/apps/web/.env.example b/apps/web/.env.example
index b71c704e86..a87a0d2bd3 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -142,6 +142,11 @@ NEXT_PUBLIC_IS_DUB=
# For cron jobs
CRON_SECRET=
+# For support docs embedding sync
+EMBEDDING_SYNC_SECRET=
+UPSTASH_VECTOR_REST_URL=
+UPSTASH_VECTOR_REST_TOKEN=
+
# Slack integration
SLACK_CLIENT_ID=
SLACK_CLIENT_SECRET=
diff --git a/apps/web/app/api/ai/support-chat/route.ts b/apps/web/app/api/ai/support-chat/route.ts
new file mode 100644
index 0000000000..9f83697c63
--- /dev/null
+++ b/apps/web/app/api/ai/support-chat/route.ts
@@ -0,0 +1,48 @@
+import {
+ buildSystemPrompt,
+ GlobalChatContext,
+} from "@/lib/ai/build-system-prompt";
+import { createSupportTicketTool } from "@/lib/ai/create-support-ticket";
+import { findRelevantDocsTool } from "@/lib/ai/find-relevant-docs";
+import { getProgramPerformanceTool } from "@/lib/ai/get-program-performance";
+import { getWorkspaceDetailsTool } from "@/lib/ai/get-workspace-details";
+import { withSession } from "@/lib/auth";
+import { ratelimit } from "@/lib/upstash/ratelimit";
+import { anthropic } from "@ai-sdk/anthropic";
+import { convertToModelMessages, stepCountIs, streamText, UIMessage } from "ai";
+
+export const POST = withSession(async ({ req, session }) => {
+ const { messages, globalContext } = (await req.json()) as {
+ messages: UIMessage[];
+ globalContext?: GlobalChatContext;
+ };
+
+ const { success } = await ratelimit(5, "30 s").limit(
+ `support-chat:${session.user.id}`,
+ );
+ if (!success) {
+ return new Response("Don't DDoS me pls πŸ₯Ί", { status: 429 });
+ }
+
+ const result = streamText({
+ model: anthropic("claude-sonnet-4-20250514"),
+ system: buildSystemPrompt(globalContext),
+ messages: await convertToModelMessages(messages),
+ stopWhen: stepCountIs(5),
+ tools: {
+ findRelevantDocs: findRelevantDocsTool,
+ getProgramPerformance: getProgramPerformanceTool,
+ getWorkspaceDetails: getWorkspaceDetailsTool,
+ createSupportTicket: createSupportTicketTool({
+ context: globalContext?.chatLocation ?? "docs",
+ session,
+ messages: messages.map((msg) => ({
+ role: msg.role,
+ parts: "parts" in msg ? msg.parts : [],
+ })),
+ }),
+ },
+ });
+
+ return result.toUIMessageStreamResponse();
+});
diff --git a/apps/web/app/api/ai/sync-embeddings/route.ts b/apps/web/app/api/ai/sync-embeddings/route.ts
new file mode 100644
index 0000000000..6a922c78f1
--- /dev/null
+++ b/apps/web/app/api/ai/sync-embeddings/route.ts
@@ -0,0 +1,59 @@
+import { upsertDocsEmbeddings } from "@/lib/ai/upsert-docs-embedding";
+
+// POST /api/ai/sync-embeddings
+// Triggers re-embedding of a single docs/help article.
+// Called by the docs GitHub Action when a .mdx file changes.
+//
+// Auth: Authorization: Bearer <EMBEDDING_SYNC_SECRET>
+// Body: { url: string }
+export const POST = async (req: Request) => {
+ const authHeader = req.headers.get("Authorization");
+ const secret = process.env.EMBEDDING_SYNC_SECRET;
+
+ if (!secret || authHeader !== `Bearer ${secret}`) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ let url: string;
+ try {
+ ({ url } = await req.json());
+ } catch {
+ return new Response("Invalid JSON body", { status: 400 });
+ }
+
+ if (!url || typeof url !== "string") {
+ return new Response("Missing or invalid `url` field", { status: 400 });
+ }
+
+ let parsedUrl: URL;
+ try {
+ parsedUrl = new URL(url);
+ } catch {
+ return new Response("Invalid URL", { status: 400 });
+ }
+
+ const allowedHostnames = ["dub.co", "www.dub.co"];
+ const allowedPathPrefixes = ["/docs/", "/help/"];
+ if (
+ parsedUrl.protocol !== "https:" ||
+ !allowedHostnames.includes(parsedUrl.hostname) ||
+ !allowedPathPrefixes.some((p) => parsedUrl.pathname.startsWith(p))
+ ) {
+ return new Response("URL must be a dub.co/docs or dub.co/help URL", {
+ status: 400,
+ });
+ }
+
+ const normalizedUrl = parsedUrl.toString();
+
+ try {
+ const result = await upsertDocsEmbeddings(normalizedUrl);
+ return Response.json({ success: true, url: normalizedUrl, ...result });
+ } catch (err) {
+ console.error("Failed to seed URL:", normalizedUrl, err);
+ return Response.json(
+ { success: false, url: normalizedUrl, error: "Failed to seed embedding" },
+ { status: 500 },
+ );
+ }
+};
diff --git a/apps/web/app/api/supported-countries/route.ts b/apps/web/app/api/supported-countries/route.ts
index a9fd0f0173..423465c578 100644
--- a/apps/web/app/api/supported-countries/route.ts
+++ b/apps/web/app/api/supported-countries/route.ts
@@ -1,26 +1,10 @@
-import {
- CONNECT_SUPPORTED_COUNTRIES,
- COUNTRIES,
- PAYPAL_SUPPORTED_COUNTRIES,
- STABLECOIN_SUPPORTED_COUNTRIES,
-} from "@dub/utils";
+import { PAYOUT_SUPPORTED_COUNTRIES } from "@/lib/constants/payouts-supported-countries";
import { NextResponse } from "next/server";
export const dynamic = "force-static";
export async function GET() {
- const supported = [
- ...new Set([
- ...STABLECOIN_SUPPORTED_COUNTRIES,
- ...CONNECT_SUPPORTED_COUNTRIES,
- ...PAYPAL_SUPPORTED_COUNTRIES,
- ]),
- ];
- const sorted = supported
- .sort((a, b) => COUNTRIES[a].localeCompare(COUNTRIES[b]))
- .map((code) => ({ code, name: COUNTRIES[code] }));
-
- return NextResponse.json(sorted, {
+ return NextResponse.json(PAYOUT_SUPPORTED_COUNTRIES, {
headers: {
"Access-Control-Allow-Origin": "*",
// cache indefinitely till next deployment
diff --git a/apps/web/app/app.dub.co/embed/support-chat/dynamic-height-messenger.tsx b/apps/web/app/app.dub.co/embed/support-chat/dynamic-height-messenger.tsx
new file mode 100644
index 0000000000..89630f8740
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/support-chat/dynamic-height-messenger.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useEffect } from "react";
+
+export function SupportChatDynamicHeightMessenger() {
+ useEffect(() => {
+ document.body.style.overflow = "hidden";
+ const update = () => {
+ const height = document.body.scrollHeight;
+ window.parent.postMessage(
+ {
+ originator: "Dub",
+ event: "PAGE_HEIGHT",
+ data: { height },
+ },
+ "*",
+ );
+ };
+ update();
+
+ const resizeObserver = new ResizeObserver(update);
+ resizeObserver.observe(document.body);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, []);
+
+ return null;
+}
diff --git a/apps/web/app/app.dub.co/embed/support-chat/layout.tsx b/apps/web/app/app.dub.co/embed/support-chat/layout.tsx
new file mode 100644
index 0000000000..21bf6e3f89
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/support-chat/layout.tsx
@@ -0,0 +1,14 @@
+export default function SupportChatEmbedLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <>
+ <style precedence="high">{`
+ html, body { background: transparent !important; }
+ `}</style>
+ {children}
+ </>
+ );
+}
diff --git a/apps/web/app/app.dub.co/embed/support-chat/page.tsx b/apps/web/app/app.dub.co/embed/support-chat/page.tsx
new file mode 100644
index 0000000000..656d3ca8cd
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/support-chat/page.tsx
@@ -0,0 +1,28 @@
+import { SupportChatBubble } from "@/ui/support/chat-bubble";
+import { EmbeddedSupportChat } from "@/ui/support/embedded-chat";
+import { SupportChatContext, SupportChatVariant } from "@/ui/support/types";
+import { SupportChatDynamicHeightMessenger } from "./dynamic-height-messenger";
+
+export default async function SupportChatEmbedPage(props: {
+ searchParams: Promise<{
+ variant?: SupportChatVariant;
+ context?: SupportChatContext;
+ }>;
+}) {
+ const { variant, context } = await props.searchParams;
+
+ if (variant === "embedded") {
+ return (
+ <div className="min-h-[500px] bg-white p-4">
+ <EmbeddedSupportChat context={context} />
+ <SupportChatDynamicHeightMessenger />
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-screen bg-transparent">
+ <SupportChatBubble context={context} />
+ </div>
+ );
+}
diff --git a/apps/web/lib/ai/build-system-prompt.ts b/apps/web/lib/ai/build-system-prompt.ts
new file mode 100644
index 0000000000..15f5b88be4
--- /dev/null
+++ b/apps/web/lib/ai/build-system-prompt.ts
@@ -0,0 +1,70 @@
+import { SupportChatContext } from "@/ui/support/types";
+import { Program, Project } from "@dub/prisma/client";
+
+export type GlobalChatContext = {
+ chatLocation?: SupportChatContext;
+ accountType?: "workspace" | "partner";
+ selectedWorkspace?: Pick<Project, "id" | "name" | "slug">;
+ selectedProgram?: Pick<Program, "id" | "name" | "slug">;
+};
+
+const CONTEXT_SYSTEM_PROMPTS: Record<SupportChatContext, string> = {
+ app: `You are a helpful Dub support assistant helping users manage their Dub workspaces and links.
+ Focus on: link shortening, custom domains, analytics, click tracking, API usage, workspace management, billing, and integrations.
+ When a user has a billing issue, account access problem, or a bug that can't be resolved through documentation, use the createSupportTicket tool.`,
+
+ partners: `You are a helpful Dub Partners support assistant helping affiliate partners with their programs.
+ Focus on: payouts, referral tracking, commission structure, partner links, bank account setup, payout countries, program enrollment, and affiliate performance.
+ When a user has a payout dispute, tax compliance issue, or a problem that can't be resolved through documentation, use the createSupportTicket tool.
+ Always try to provide the program's support email for program-specific issues.`,
+
+ docs: `You are a helpful Dub developer support assistant helping developers integrate Dub into their applications.
+ Focus on: SDK installation and usage, webhooks, conversion tracking, rate limits, API authentication, link creation, analytics API, and integration guides.
+ When a user has a complex integration issue that can't be resolved through documentation, use the createSupportTicket tool.`,
+};
+
+const BASE_SYSTEM_PROMPT = `
+ You are powered by Dub's documentation and help articles. Always ground your answers in the retrieved content.
+ Respond in concise, clear markdown. Strictly avoid using headings (h1, h2, h3, h4, h5, h6) in your responses.
+ If you find a relevant article, include a link to it in your response.
+ If you cannot find relevant information in the docs, acknowledge it and offer to create a support ticket.
+ Never make up information β€” if unsure, say so and offer to escalate.
+ `.trim();
+
+function buildAccountSpecificPrompt(context: GlobalChatContext): string[] {
+ if (!context.accountType) return [];
+
+ const prompts = [
+ `The user is asking about their ${context.accountType} account.`,
+ ];
+
+ if (context.accountType === "workspace" && context.selectedWorkspace) {
+ prompts.push(
+ `They are specifically asking about workspace: ${JSON.stringify(context.selectedWorkspace)}`,
+ );
+ } else if (context.accountType === "partner" && context.selectedProgram) {
+ prompts.push(
+ `They are specifically asking about program: ${JSON.stringify(context.selectedProgram)}`,
+ );
+ }
+
+ return prompts;
+}
+
+export function buildSystemPrompt(globalContext?: GlobalChatContext): string {
+ const accountSpecificPrompts = buildAccountSpecificPrompt(
+ globalContext || {},
+ );
+
+ const systemPrompt = [
+ globalContext?.chatLocation
+ ? CONTEXT_SYSTEM_PROMPTS[globalContext?.chatLocation]
+ : "",
+ BASE_SYSTEM_PROMPT,
+ ...accountSpecificPrompts,
+ ].join("\n\n");
+
+ console.log(systemPrompt);
+
+ return systemPrompt;
+}
diff --git a/apps/web/lib/ai/create-support-ticket.ts b/apps/web/lib/ai/create-support-ticket.ts
new file mode 100644
index 0000000000..3643e46ba2
--- /dev/null
+++ b/apps/web/lib/ai/create-support-ticket.ts
@@ -0,0 +1,89 @@
+import { createPlainThread } from "@/lib/plain/create-plain-thread";
+import { SupportChatContext } from "@/ui/support/types";
+import { ComponentDividerSpacingSize } from "@team-plain/typescript-sdk";
+import { tool } from "ai";
+import { z } from "zod";
+import { Session } from "../auth/utils";
+
+const createSupportTicketInputSchema = z.object({
+ summary: z
+ .string()
+ .describe(
+ "A concise summary of the user's issue based on the conversation.",
+ ),
+ category: z
+ .enum(["billing", "account", "bug", "feature", "other"])
+ .describe("The category of the support request."),
+});
+
+export type CreateSupportTicketOptions = {
+ context: SupportChatContext;
+ session: Session;
+ messages: Array<{
+ role: string;
+ parts: Array<{ type: string; text?: string }>;
+ }>;
+};
+
+export function createSupportTicketTool(options: CreateSupportTicketOptions) {
+ const { context, session, messages } = options;
+
+ return tool({
+ description:
+ "Creates a support ticket in Plain when the AI cannot resolve the user's issue. Use this when the user explicitly asks to speak with a human, when the issue involves billing disputes, account access problems, or confirmed bugs.",
+ inputSchema: createSupportTicketInputSchema,
+ execute: async ({ summary, category }) => {
+ const chatHistory = messages
+ .map((msg) => {
+ const text = msg.parts
+ .filter((p) => p.type === "text")
+ .map((p) => (p as { type: "text"; text: string }).text)
+ .join("");
+ return `${msg.role === "user" ? "User" : "Dub Support"}: ${text}`;
+ })
+ .join("\n\n");
+
+ try {
+ await createPlainThread({
+ user: {
+ id: session.user.id,
+ name: session.user.name ?? "",
+ email: session.user.email,
+ },
+ title: `[${context.toUpperCase()}] ${summary.slice(0, 80)}`,
+ priority: 2,
+ components: [
+ {
+ componentText: {
+ text: `**Category:** ${category}\n\n**Summary:** ${summary}`,
+ },
+ },
+ {
+ componentDivider: {
+ dividerSpacingSize: ComponentDividerSpacingSize.L,
+ },
+ },
+ {
+ componentText: {
+ text: chatHistory.slice(0, 5000),
+ },
+ },
+ ],
+ });
+
+ return {
+ success: true,
+ message:
+ "Support ticket created successfully. Our team will reach out to you shortly.",
+ };
+ } catch (err) {
+ console.error("Failed to create support ticket:", err);
+ return {
+ success: false,
+ message:
+ "Failed to create support ticket. Please try again or email [email protected].",
+ };
+ }
+ },
+ });
+}
diff --git a/apps/web/lib/ai/find-relevant-docs.ts b/apps/web/lib/ai/find-relevant-docs.ts
new file mode 100644
index 0000000000..a5ad6e0514
--- /dev/null
+++ b/apps/web/lib/ai/find-relevant-docs.ts
@@ -0,0 +1,28 @@
+import { tool } from "ai";
+import { z } from "zod";
+import { vectorIndex } from "../upstash/vector";
+
+export const findRelevantDocsTool = tool({
+ description: "Finds the most relevant docs / help article for a given query.",
+ inputSchema: z.object({
+ query: z.string().describe("The query to search for."),
+ accountType: z
+ .enum(["workspace", "partner"])
+ .describe("The type of account the user is asking about."),
+ }),
+ execute: async ({ query }) => {
+ const result = await vectorIndex.query({
+ data: query,
+ topK: 4,
+ includeMetadata: true,
+ });
+
+ // Return array of metadata for each chunk
+ // e.g. [{ id, score, metadata: { resourceId, content }}, ... ]
+ return result.map(({ id, score, metadata }) => ({
+ id,
+ score,
+ metadata,
+ }));
+ },
+});
diff --git a/apps/web/lib/ai/get-program-performance.ts b/apps/web/lib/ai/get-program-performance.ts
new file mode 100644
index 0000000000..ebaee1a4b3
--- /dev/null
+++ b/apps/web/lib/ai/get-program-performance.ts
@@ -0,0 +1,136 @@
+import { prisma } from "@dub/prisma";
+import { CommissionStatus, PayoutStatus } from "@dub/prisma/client";
+import { tool } from "ai";
+import { z } from "zod";
+import { getSession } from "../auth/utils";
+
+const programPerformanceSchema = z.object({
+ program: z.object({
+ name: z.string().describe("The name of the program."),
+ supportEmail: z
+ .string()
+ .describe(
+ "The support email of the program. Useful for letting the user know how to contact the program's support team.",
+ ),
+ minPayoutAmount: z
+ .number()
+ .describe(
+ "The minimum payout amount for the program in USD cents. If the partner's earnings are less than this amount, it will not be eligible for payout.",
+ ),
+ }),
+ commissions: z.array(
+ z.object({
+ status: z
+ .enum(CommissionStatus)
+ .describe("The status of the commission."),
+ earningsInCents: z.number().describe("Total earnings in USD cents"),
+ }),
+ ),
+ payouts: z.array(
+ z.object({
+ amount: z.number().describe("The amount of the payout in USD cents."),
+ status: z.enum(PayoutStatus).describe("The status of the payout."),
+ stripePayoutTraceId: z
+ .string()
+ .nullish()
+ .describe(
+ "The payout trace ID. Useful for tracking delayed payouts – if the partner asks about a delayed payout, provide them with the trace ID for them to track the status of the payout with their bank.",
+ ),
+ createdAt: z.date().describe("The date and time the payout was created."),
+ periodStart: z.date().describe("The start date of the payout period."),
+ periodEnd: z.date().describe("The end date of the payout period."),
+ }),
+ ),
+ holdingPeriodDays: z
+ .number()
+ .describe(
+ "The number of days that commissions are held in 'pending' status until they are eligible for payout.",
+ ),
+});
+
+export const getProgramPerformanceTool = tool({
+ description:
+ "Retrives the partner's performance for a given program (commissions, payouts, etc.) along with the program's details.",
+ inputSchema: z.object({
+ programId: z.string().describe("The unique ID of the program."),
+ }),
+ outputSchema: programPerformanceSchema,
+ execute: async ({ programId }) => {
+ const session = await getSession();
+ if (!session?.user.id) {
+ return {
+ error: "Unauthorized. Please log in to continue.",
+ };
+ }
+ const programEnrollment = await prisma.programEnrollment.findFirst({
+ where: {
+ programId,
+ partner: {
+ users: {
+ some: {
+ userId: session.user.id,
+ },
+ },
+ },
+ },
+ include: {
+ program: {
+ include: {
+ groups: {
+ where: {
+ slug: "default",
+ },
+ },
+ },
+ },
+ partnerGroup: true,
+ },
+ });
+ if (!programEnrollment) {
+ return {
+ error: "Partner not enrolled in program",
+ };
+ }
+ const [commissions, payouts] = await Promise.all([
+ prisma.commission.groupBy({
+ by: ["status"],
+ where: {
+ earnings: {
+ gt: 0,
+ },
+ programId: programEnrollment.programId,
+ partnerId: programEnrollment.partnerId,
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+ prisma.payout.findMany({
+ where: {
+ programId: programEnrollment.programId,
+ partnerId: programEnrollment.partnerId,
+ },
+ take: 100, // limit to latest 100 payouts
+ orderBy: {
+ createdAt: "desc",
+ },
+ }),
+ ]);
+
+ const data = programPerformanceSchema.parse({
+ program: programEnrollment.program,
+ holdingPeriodDays:
+ programEnrollment.partnerGroup?.holdingPeriodDays ??
+ programEnrollment.program.groups[0]?.holdingPeriodDays ??
+ 0,
+ commissions: commissions.map((commission) => ({
+ status: commission.status,
+ earningsInCents: commission._sum.earnings,
+ })),
+ payouts,
+ });
+
+ console.log(data);
+ return data;
+ },
+});
diff --git a/apps/web/lib/ai/get-workspace-details.ts b/apps/web/lib/ai/get-workspace-details.ts
new file mode 100644
index 0000000000..159b83e72a
--- /dev/null
+++ b/apps/web/lib/ai/get-workspace-details.ts
@@ -0,0 +1,73 @@
+import { prisma } from "@dub/prisma";
+import { tool } from "ai";
+import { z } from "zod";
+import { getSession } from "../auth/utils";
+
+const workspaceDetailsSchema = z.object({
+ name: z.string().describe("The name of the workspace."),
+ slug: z.string().describe("The slug of the workspace."),
+ logo: z.string().describe("The logo of the workspace."),
+ plan: z
+ .enum(["free", "pro", "business", "advanced", "enterprise"])
+ .describe("The plan of the workspace."),
+ billingCycleStart: z
+ .number()
+ .describe("The day of the month when the billing cycle starts."),
+ paymentFailedAt: z
+ .date()
+ .nullable()
+ .describe("The date and time the payment failed at."),
+ usage: z
+ .number()
+ .describe(
+ "The tracked events usage that the workspace has used for the current billing cycle.",
+ ),
+ usageLimit: z
+ .number()
+ .describe(
+ "The total tracked events that the workspace has for the current billing cycle.",
+ ),
+ linksUsage: z
+ .number()
+ .describe(
+ "The amount of links that the workspace has created for the current billing cycle.",
+ ),
+ linksLimit: z
+ .number()
+ .describe(
+ "The total amount of links that the workspace can create for the current billing cycle.",
+ ),
+});
+
+export const getWorkspaceDetailsTool = tool({
+ description:
+ "Retrives the details of a given user's workspace (plan, usage, etc.).",
+ inputSchema: z.object({
+ workspaceId: z.string().describe("The unique ID of the workspace."),
+ }),
+ outputSchema: workspaceDetailsSchema,
+ execute: async ({ workspaceId }) => {
+ const session = await getSession();
+ if (!session?.user.id) {
+ return {
+ error: "Unauthorized. Please log in to continue.",
+ };
+ }
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ users: {
+ some: {
+ userId: session.user.id,
+ },
+ },
+ },
+ });
+ if (!workspace) {
+ return {
+ error: "Workspace not found",
+ };
+ }
+ return workspaceDetailsSchema.parse(workspace);
+ },
+});
diff --git a/apps/web/lib/ai/upsert-docs-embedding.ts b/apps/web/lib/ai/upsert-docs-embedding.ts
new file mode 100644
index 0000000000..6f4ccab656
--- /dev/null
+++ b/apps/web/lib/ai/upsert-docs-embedding.ts
@@ -0,0 +1,224 @@
+import { vectorIndex } from "../../lib/upstash/vector";
+import { PAYOUT_SUPPORTED_COUNTRIES } from "../constants/payouts-supported-countries";
+/**
+ * Clean raw MDX fetched from Mintlify's .md endpoint.
+ * Strips frontmatter, imports, images, JSX components.
+ * Replaces <PayoutSupportedCountries /> with the actual country list.
+ */
+export async function cleanMdx(raw: string): Promise<string> {
+ let content = raw;
+
+ content = content.replace(/^---[\s\S]*?---\s*/m, "");
+ content = content.replace(/^import\s+.*from\s+['"][^'"]*['"]\s*;?\s*$/gm, "");
+ content = content.replace(/!\[.*?\]\(.*?\)/g, "");
+
+ content = content.replace(
+ /<PayoutSupportedCountries\s*\/>/g,
+ PAYOUT_SUPPORTED_COUNTRIES.map((c) => `- ${c.name} (${c.code})`).join("\n"),
+ );
+
+ content = content.replace(/<[A-Z][A-Za-z]*\s*\/>/g, "");
+
+ const blockComponents = [
+ "CardGroup",
+ "Card",
+ "Tabs",
+ "Tab",
+ "Note",
+ "Tip",
+ "Warning",
+ "Info",
+ "Check",
+ "Steps",
+ "Step",
+ "Frame",
+ "Accordion",
+ "AccordionGroup",
+ "ResponseField",
+ "ParamField",
+ "Expandable",
+ "Update",
+ ];
+ for (const tag of blockComponents) {
+ content = content.replace(new RegExp(`<${tag}(?:\\s[^>]*)?>`, "g"), "");
+ content = content.replace(new RegExp(`</${tag}>`, "g"), "");
+ }
+
+ content = content.replace(/^\s*\w+=\{.*?\}\s*$/gm, "");
+ content = content.replace(/\{\/\*[\s\S]*?\*\/\}/g, "");
+ content = content.replace(/\{`[^`]*`\}/g, "");
+ content = content.replace(/<video[\s\S]*?<\/video>/g, "");
+ content = content.replace(/<img[^>]*>/g, "");
+ content = content.replace(/\n{3,}/g, "\n\n");
+
+ return content.trim();
+}
+
+type ArticleChunk = {
+ id: string;
+ content: string;
+ url: string;
+ heading: string;
+ type: "docs" | "help";
+};
+
+/**
+ * Split cleaned markdown into chunks at H2/H3 heading boundaries.
+ * Each chunk carries the section URL + heading as metadata.
+ */
+export function chunkByHeadings(content: string, url: string): ArticleChunk[] {
+ const lines = content.split("\n");
+ const chunks: ArticleChunk[] = [];
+ let currentHeading = "Introduction";
+ let currentLines: string[] = [];
+ const seenSlugs = new Map<string, number>();
+
+ const type: "docs" | "help" = url.includes("/help/") ? "help" : "docs";
+
+ const flush = () => {
+ const text = currentLines.join("\n").trim();
+ if (text.length < 50) {
+ currentLines = [];
+ return;
+ }
+
+ const baseSlug = currentHeading
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+
+ const count = (seenSlugs.get(baseSlug) ?? 0) + 1;
+ seenSlugs.set(baseSlug, count);
+ const slug = count === 1 ? baseSlug : `${baseSlug}-${count}`;
+
+ const id = `${url}#${slug}`;
+ chunks.push({
+ id,
+ content: `## ${currentHeading}\n\n${text}`,
+ url: `${url}#${slug}`,
+ heading: currentHeading,
+ type,
+ });
+ currentLines = [];
+ };
+
+ for (const line of lines) {
+ const h2Match = line.match(/^## (.+)$/);
+ const h3Match = line.match(/^### (.+)$/);
+
+ if (h2Match || h3Match) {
+ flush();
+ currentHeading = (h2Match || h3Match)![1].trim();
+ } else {
+ currentLines.push(line);
+ }
+ }
+
+ flush();
+
+ if (chunks.length === 0 && content.length > 50) {
+ const baseSlug = url.split("/").pop() || "article";
+ const count = (seenSlugs.get(baseSlug) ?? 0) + 1;
+ seenSlugs.set(baseSlug, count);
+ const slug = count === 1 ? baseSlug : `${baseSlug}-${count}`;
+ chunks.push({
+ id: `${url}#${slug}`,
+ content,
+ url: `${url}#${slug}`,
+ heading: "Overview",
+ type,
+ });
+ }
+
+ return chunks;
+}
+
+/**
+ * Maps every allowed hostname to its canonical HTTPS origin.
+ * The outgoing request origin is always picked from this map β€” never
+ * constructed directly from user-supplied input β€” to prevent SSRF.
+ * This is also the source of truth for the hostname allowlist.
+ */
+const HOSTNAME_TO_ORIGIN: Record<string, string> = {
+ "dub.co": "https://dub.co",
+ "www.dub.co": "https://www.dub.co",
+};
+const ALLOWED_HOSTNAMES = Object.keys(HOSTNAME_TO_ORIGIN);
+const ALLOWED_PATH_PREFIXES = ["/docs", "/help"];
+
+/**
+ * Sanitize pathname: keep only alphanumeric, hyphens, underscores, slashes,
+ * and dots, then collapse any remaining ".." sequences to prevent path
+ * traversal even if the caller skips the pre-validation step.
+ */
+function sanitizePathname(pathname: string): string {
+ return pathname.replace(/[^a-zA-Z0-9\-_/.]/g, "").replace(/\.\.+/g, "");
+}
+
+/**
+ * Fetch, clean, chunk, and upsert a single article URL into Upstash Vector.
+ * Uses heading-level chunks directly β€” no sentence-level fragmentation.
+ * Validates URL to restrict fetches to dub.co docs/help (SSRF guard).
+ */
+export async function upsertDocsEmbeddings(
+ url: string,
+): Promise<{ chunks: number; skipped?: boolean }> {
+ let parsedUrl: URL;
+ try {
+ parsedUrl = new URL(url);
+ } catch {
+ console.warn(`Skipping (invalid URL): ${url}`);
+ return { chunks: 0, skipped: true };
+ }
+
+ if (
+ parsedUrl.protocol !== "https:" ||
+ !ALLOWED_HOSTNAMES.includes(parsedUrl.hostname) ||
+ (!ALLOWED_HOSTNAMES.includes(parsedUrl.pathname) &&
+ !ALLOWED_PATH_PREFIXES.some((p) => parsedUrl.pathname.startsWith(p))) ||
+ parsedUrl.pathname.includes("..")
+ ) {
+ console.warn(`Skipping (disallowed URL): ${url}`);
+ return { chunks: 0, skipped: true };
+ }
+
+ const origin = HOSTNAME_TO_ORIGIN[parsedUrl.hostname] ?? "https://dub.co";
+ const sanitizedPath = sanitizePathname(parsedUrl.pathname);
+ const pathnameWithMd = sanitizedPath.endsWith(".md")
+ ? sanitizedPath
+ : `${sanitizedPath}.md`;
+ const normalizedUrl = `${origin}${sanitizedPath}`;
+ const mdUrl = `${origin}${pathnameWithMd}`;
+
+ const res = await fetch(mdUrl);
+ if (!res.ok) {
+ console.warn(`Skipping (${res.status}): ${normalizedUrl}`);
+ return { chunks: 0, skipped: true };
+ }
+
+ const raw = await res.text();
+ const cleaned = await cleanMdx(raw);
+ const chunks = chunkByHeadings(cleaned, normalizedUrl);
+
+ // Upstash Vector has a 48KB metadata size limit per vector.
+ const MAX_METADATA_CONTENT = 4000;
+
+ await Promise.all(
+ chunks.map(async (chunk) => {
+ await vectorIndex.upsert([
+ {
+ id: chunk.id,
+ data: chunk.content,
+ metadata: {
+ url: chunk.url,
+ heading: chunk.heading,
+ type: chunk.type,
+ content: chunk.content.slice(0, MAX_METADATA_CONTENT),
+ },
+ },
+ ]);
+ }),
+ );
+
+ return { chunks: chunks.length };
+}
diff --git a/apps/web/lib/constants/payouts-supported-countries.ts b/apps/web/lib/constants/payouts-supported-countries.ts
new file mode 100644
index 0000000000..f6cd0d3567
--- /dev/null
+++ b/apps/web/lib/constants/payouts-supported-countries.ts
@@ -0,0 +1,16 @@
+import {
+ CONNECT_SUPPORTED_COUNTRIES,
+ COUNTRIES,
+ PAYPAL_SUPPORTED_COUNTRIES,
+ STABLECOIN_SUPPORTED_COUNTRIES,
+} from "@dub/utils";
+
+export const PAYOUT_SUPPORTED_COUNTRIES = [
+ ...new Set([
+ ...STABLECOIN_SUPPORTED_COUNTRIES,
+ ...CONNECT_SUPPORTED_COUNTRIES,
+ ...PAYPAL_SUPPORTED_COUNTRIES,
+ ]),
+]
+ .sort((a, b) => COUNTRIES[a].localeCompare(COUNTRIES[b]))
+ .map((code) => ({ code, name: COUNTRIES[code] }));
diff --git a/apps/web/lib/middleware/embed.ts b/apps/web/lib/middleware/embed.ts
index 965ece1aa2..4997522b6c 100644
--- a/apps/web/lib/middleware/embed.ts
+++ b/apps/web/lib/middleware/embed.ts
@@ -2,7 +2,11 @@ import { NextRequest, NextResponse } from "next/server";
import { parse } from "./utils/parse";
export function EmbedMiddleware(req: NextRequest) {
- const { searchParamsObj, fullPath } = parse(req);
+ const { path, searchParamsObj, fullPath } = parse(req);
+
+ if (path.startsWith("/embed/support-chat")) {
+ return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url));
+ }
if (searchParamsObj.token) {
return NextResponse.rewrite(new URL(`/app.dub.co${fullPath}`, req.url));
diff --git a/apps/web/lib/upstash/vector.ts b/apps/web/lib/upstash/vector.ts
new file mode 100644
index 0000000000..8a3ebec27c
--- /dev/null
+++ b/apps/web/lib/upstash/vector.ts
@@ -0,0 +1,6 @@
+import { Index } from "@upstash/vector";
+
+export const vectorIndex = new Index({
+ url: process.env.UPSTASH_VECTOR_REST_URL!,
+ token: process.env.UPSTASH_VECTOR_REST_TOKEN!,
+});
diff --git a/apps/web/package.json b/apps/web/package.json
index d58ec50027..458fd64da4 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -56,6 +56,7 @@
"@upstash/qstash": "^2.8.2",
"@upstash/ratelimit": "^2.0.6",
"@upstash/redis": "^1.35.3",
+ "@upstash/vector": "^1.2.2",
"@upstash/workflow": "^0.2.19",
"@vercel/edge-config": "^0.4.1",
"@vercel/functions": "^1.4.2",
@@ -123,6 +124,7 @@
"sanitize-html": "^2.17.0",
"shiki": "^1.14.1",
"sonner": "^1.4.41",
+ "streamdown": "^2.3.0",
"stripe": "^18.2.0",
"svix": "^1.76.1",
"swr": "^2.1.5",
diff --git a/apps/web/scripts/seed-support-embeddings.ts b/apps/web/scripts/seed-support-embeddings.ts
new file mode 100644
index 0000000000..bca52a2ae3
--- /dev/null
+++ b/apps/web/scripts/seed-support-embeddings.ts
@@ -0,0 +1,104 @@
+/**
+ * Seed script for support embeddings.
+ *
+ *
+ * Usage:
+ * pnpm tsx scripts/seed-support-embeddings.ts # seed all articles
+ * pnpm tsx scripts/seed-support-embeddings.ts --url <url> # re-seed a single article
+ */
+
+import "dotenv-flow/config";
+import { upsertDocsEmbeddings } from "../lib/ai/upsert-docs-embedding";
+
+/**
+ * Fetch all article URLs from dub.co/llms.txt.
+ */
+export async function fetchArticleUrls(): Promise<string[]> {
+ const res = await fetch("https://dub.co/docs/llms.txt");
+ if (!res.ok) throw new Error(`Failed to fetch llms.txt: ${res.status}`);
+
+ const text = await res.text();
+ const urls: string[] = [];
+
+ for (const line of text.split("\n")) {
+ const trimmed = line.trim();
+ const linkMatch = trimmed.match(
+ /\(?(https?:\/\/dub\.co\/(?:docs|help)[^\s)]*)\)?/,
+ );
+ const candidate = linkMatch ? linkMatch[1] : trimmed;
+
+ if (candidate.startsWith("http")) {
+ try {
+ const parsed = new URL(candidate);
+ const origin = "https://dub.co";
+ const pathname = parsed.pathname.endsWith(".md")
+ ? parsed.pathname.slice(0, -3)
+ : parsed.pathname;
+ const normalizedUrl = `${origin}${pathname}`;
+ urls.push(normalizedUrl);
+ } catch {
+ // Invalid URL, skip
+ }
+ }
+ }
+
+ return [...new Set(urls)];
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const urlFlagIdx = args.indexOf("--url");
+
+ if (urlFlagIdx !== -1) {
+ const url = args[urlFlagIdx + 1];
+ if (!url) {
+ console.error(
+ "Error: --url requires a value (e.g. --url https://dub.co/docs/...)",
+ );
+ process.exit(1);
+ }
+ console.log(`Seeding single article: ${url}`);
+ const result = await upsertDocsEmbeddings(url);
+ console.log(
+ ` β†’ ${result.chunks} chunks${result.skipped ? " (skipped)" : ""}`,
+ );
+ console.log("Done.");
+ return;
+ }
+
+ console.log("Fetching article list from llms.txt...");
+ const urls = await fetchArticleUrls();
+ console.log(`Found ${urls.length} articles to embed.\n`);
+
+ let success = 0;
+ let skipped = 0;
+ let failed = 0;
+
+ for (const url of urls) {
+ try {
+ process.stdout.write(`Processing: ${url} ... `);
+ const result = await upsertDocsEmbeddings(url);
+ if (result.skipped) {
+ process.stdout.write(`skipped\n`);
+ skipped++;
+ } else {
+ process.stdout.write(`${result.chunks} chunks\n`);
+ success++;
+ }
+ } catch (err) {
+ process.stdout.write(`ERROR: ${err}\n`);
+ failed++;
+ }
+
+ await new Promise((r) => setTimeout(r, 200));
+ }
+
+ console.log(
+ `\nDone. Success: ${success}, Skipped: ${skipped}, Failed: ${failed}`,
+ );
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/apps/web/ui/support/chat-bubble.tsx b/apps/web/ui/support/chat-bubble.tsx
new file mode 100644
index 0000000000..ce9a5d9fec
--- /dev/null
+++ b/apps/web/ui/support/chat-bubble.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { MsgsFill, Xmark } from "@dub/ui/icons";
+import { AnimatePresence, motion } from "motion/react";
+import { useEffect, useRef, useState } from "react";
+import { ChatInterface } from "./chat-interface";
+import { SupportChatContext } from "./types";
+
+export function SupportChatBubble({
+ context,
+}: {
+ context?: SupportChatContext;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const panelRef = useRef<HTMLDivElement>(null);
+
+ const handleClose = () => {
+ setIsOpen(false);
+ };
+
+ useEffect(() => {
+ if (window.parent === window) return;
+ window.parent.postMessage({ type: "dub-support-chat", isOpen }, "*");
+ }, [isOpen]);
+
+ const handleOpen = () => {
+ setIsOpen(true);
+ };
+
+ return (
+ <div className="pointer-events-none fixed bottom-0 right-0 z-50 flex flex-col items-end p-3 sm:p-6">
+ <AnimatePresence>
+ {isOpen && (
+ <motion.div
+ ref={panelRef}
+ initial={{ opacity: 0, y: 16, scale: 0.97 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 16, scale: 0.97 }}
+ transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
+ className="pointer-events-auto mb-4 flex h-[660px] max-h-[calc(100vh-6rem)] w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-2xl bg-white shadow-2xl shadow-neutral-900/15 sm:w-[560px]"
+ >
+ <div className="flex shrink-0 items-center justify-between bg-neutral-900 px-4 py-3">
+ <div className="flex items-center gap-2.5">
+ <img
+ src="https://assets.dub.co/misc/dub-avatar.svg"
+ alt="Dub Support"
+ className="size-7 rounded-full"
+ draggable={false}
+ />
+ <p className="text-sm font-semibold leading-none text-white">
+ Dub Support
+ </p>
+ </div>
+
+ <button
+ type="button"
+ onClick={handleClose}
+ className="flex size-7 items-center justify-center rounded-lg text-neutral-400 transition-colors hover:bg-white/10 hover:text-white"
+ aria-label="Close chat"
+ >
+ <Xmark className="size-3.5" />
+ </button>
+ </div>
+
+ <ChatInterface
+ context={context}
+ className="flex-1 overflow-hidden"
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ <button
+ type="button"
+ onClick={isOpen ? handleClose : handleOpen}
+ className="pointer-events-auto relative flex size-14 items-center justify-center rounded-full bg-neutral-900 shadow-lg shadow-neutral-900/30 transition-all duration-200 hover:scale-105 hover:shadow-xl hover:shadow-neutral-900/30 active:scale-95"
+ aria-label={isOpen ? "Close support chat" : "Open support chat"}
+ >
+ <AnimatePresence mode="wait">
+ {isOpen ? (
+ <motion.div
+ key="close"
+ initial={{ opacity: 0, rotate: -90 }}
+ animate={{ opacity: 1, rotate: 0 }}
+ exit={{ opacity: 0, rotate: 90 }}
+ transition={{ duration: 0.15 }}
+ >
+ <Xmark className="size-5 text-white" />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="chat"
+ initial={{ opacity: 0, scale: 0.8 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.8 }}
+ transition={{ duration: 0.15 }}
+ >
+ <MsgsFill className="size-5 text-white" />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </button>
+ </div>
+ );
+}
diff --git a/apps/web/ui/support/chat-interface.tsx b/apps/web/ui/support/chat-interface.tsx
new file mode 100644
index 0000000000..3f6fa26d7b
--- /dev/null
+++ b/apps/web/ui/support/chat-interface.tsx
@@ -0,0 +1,527 @@
+"use client";
+
+import { GlobalChatContext } from "@/lib/ai/build-system-prompt";
+import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
+import { useChat } from "@ai-sdk/react";
+import { OfficeBuilding, PaperPlane, Users2 } from "@dub/ui/icons";
+import { cn, fetcher, OG_AVATAR_URL } from "@dub/utils";
+import { DefaultChatTransport } from "ai";
+import { useSession } from "next-auth/react";
+import { useEffect, useRef, useState } from "react";
+import TextareaAutosize from "react-textarea-autosize";
+import { toast } from "sonner";
+import { Streamdown } from "streamdown";
+import "streamdown/styles.css";
+import useSWR from "swr";
+import { SupportMessage } from "./message";
+import { ProgramCombobox } from "./program-combobox";
+import { StarterQuestions } from "./starter-questions";
+import { SupportChatContext } from "./types";
+import { WorkspaceCombobox, WorkspaceSummary } from "./workspace-combobox";
+
+type AccountType = "workspace" | "partner";
+
+export function ChatInterface({
+ context,
+ className,
+ embedded,
+}: {
+ context?: SupportChatContext;
+ className?: string;
+ embedded?: boolean;
+}) {
+ const { data: session, status: sessionStatus } = useSession();
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const [input, setInput] = useState("");
+ const [ticketSubmitted, setTicketSubmitted] = useState(false);
+ const [selection, setSelection] = useState<GlobalChatContext>({});
+
+ const preselectedAccountType: AccountType | undefined =
+ context === "app"
+ ? "workspace"
+ : context === "partners"
+ ? "partner"
+ : undefined;
+
+ const effectiveAccountType = selection.accountType ?? preselectedAccountType;
+
+ const { data: workspaces } = useSWR<WorkspaceSummary[]>(
+ effectiveAccountType === "workspace" ? "/api/workspaces" : null,
+ fetcher,
+ );
+
+ const { programEnrollments, isLoading: isLoadingPrograms } =
+ useProgramEnrollments();
+ const hasPartnerProfile = !!session?.user?.["defaultPartnerId"];
+
+ const isDocsContext = context === "docs" || context === undefined;
+ const requiresWorkspace =
+ context === "app" ||
+ (isDocsContext && effectiveAccountType === "workspace");
+ const requiresPartner =
+ context === "partners" ||
+ (isDocsContext && effectiveAccountType === "partner");
+
+ let canChat: boolean;
+ if (requiresWorkspace) canChat = !!selection.selectedWorkspace;
+ else if (requiresPartner) canChat = !!selection.selectedProgram;
+ else canChat = !isDocsContext;
+
+ const { messages, sendMessage, status, setMessages } = useChat({
+ transport: new DefaultChatTransport({
+ api: "/api/ai/support-chat",
+ }),
+ onError: (err) => {
+ toast.error(err.message || "Something went wrong. Please try again.");
+ },
+ });
+
+ useEffect(() => {
+ if (embedded) return;
+
+ const container = scrollContainerRef.current;
+ if (!container) return;
+
+ container.scrollTo({ top: container.scrollHeight, behavior: "smooth" });
+ }, [messages, status, embedded]);
+
+ const handleSend = (text?: string) => {
+ const messageText = text ?? input;
+ if (!messageText.trim() || status === "streaming" || !canChat) return;
+ sendMessage(
+ { text: messageText },
+ {
+ body: {
+ globalContext: {
+ ...selection,
+ chatLocation: context,
+ accountType: effectiveAccountType,
+ },
+ },
+ },
+ );
+ setInput("");
+ };
+
+ const handleEscalate = () => {
+ sendMessage({
+ text: "I'd like to speak with a human support agent and create a support ticket.",
+ });
+ setTicketSubmitted(true);
+ };
+
+ const handleAccountTypeChange = (type: AccountType) => {
+ setSelection({ accountType: type });
+ setMessages([]);
+ };
+
+ const requiresAuth = true;
+ const isLoadingSession = requiresAuth && sessionStatus === "loading";
+ const isUnauthenticated = requiresAuth && sessionStatus === "unauthenticated";
+
+ const userAvatar =
+ session?.user?.image || `${OG_AVATAR_URL}${session?.user?.email}`;
+ const showStarterQuestions = canChat && messages.length === 0;
+ const canEscalate =
+ canChat && messages.length >= 2 && status === "ready" && !ticketSubmitted;
+
+ const ticketCreated = messages.some(
+ (m) =>
+ m.role === "assistant" &&
+ m.parts?.some(
+ (p) =>
+ p.type === "tool-invocation" &&
+ (p as any).toolName === "createSupportTicket" &&
+ (p as any).state === "result" &&
+ (p as any).result?.success === true,
+ ),
+ );
+
+ if (isLoadingSession) {
+ return (
+ <div
+ className={cn(
+ "flex h-full flex-col items-center justify-center gap-3 p-6",
+ className,
+ )}
+ >
+ <div className="size-8 animate-pulse rounded-full bg-neutral-200" />
+ <div className="h-3 w-32 animate-pulse rounded bg-neutral-200" />
+ </div>
+ );
+ }
+
+ if (isUnauthenticated) {
+ return (
+ <div
+ className={cn(
+ "flex h-full flex-col items-center justify-center gap-4 p-8 text-center",
+ className,
+ )}
+ >
+ <img
+ src="https://assets.dub.co/misc/dub-avatar.svg"
+ alt="Dub Support"
+ className="size-12 rounded-full"
+ draggable={false}
+ />
+ <div>
+ <p className="text-sm font-medium text-neutral-800">
+ Please log in to chat with Dub support
+ </p>
+ <p className="mt-1 text-xs text-neutral-500">
+ You need a Dub account to access support.
+ </p>
+ </div>
+ <a
+ href="https://app.dub.co/login"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-700"
+ >
+ Log in to Dub β†—
+ </a>
+ </div>
+ );
+ }
+
+ return (
+ <div className={cn("flex h-full flex-col", className)}>
+ <div
+ ref={scrollContainerRef}
+ className={cn(
+ "flex flex-1 flex-col gap-6 px-4 py-8",
+ embedded ? "overflow-visible" : "overflow-y-auto",
+ )}
+ >
+ <SupportMessage
+ avatar="https://assets.dub.co/misc/dub-avatar.svg"
+ animate={false}
+ >
+ <p className="text-sm text-neutral-700">
+ Hi there! I'm Dub's AI support assistant.{" "}
+ {context === "docs"
+ ? "I can help with SDK setup, API authentication, webhooks, conversion tracking, and more. What can I help you with today?"
+ : "Which account would you like help with today?"}
+ </p>
+
+ {(context === "docs" || context === undefined) &&
+ !effectiveAccountType && (
+ <div className="mt-3 flex flex-wrap gap-2">
+ {[
+ {
+ type: "workspace" as AccountType,
+ label: "Dub workspace",
+ sublabel: "app.dub.co",
+ icon: <OfficeBuilding className="size-3.5" />,
+ },
+ {
+ type: "partner" as AccountType,
+ label: "Partner account",
+ sublabel: "partners.dub.co",
+ icon: <Users2 className="size-3.5" />,
+ },
+ ].map(({ type, label, sublabel, icon }) => (
+ <button
+ key={type}
+ type="button"
+ onClick={() => handleAccountTypeChange(type)}
+ className="flex items-center gap-1.5 rounded-lg border border-neutral-200 bg-white py-1.5 pl-2.5 pr-3 text-xs font-medium text-neutral-600 shadow-sm transition-colors hover:border-neutral-300 hover:bg-neutral-50 hover:text-neutral-800"
+ >
+ {icon}
+ <span>{label}</span>
+ <span className="text-neutral-400">Β· {sublabel}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </SupportMessage>
+
+ {effectiveAccountType === "workspace" &&
+ !selection.selectedWorkspace && (
+ <SupportMessage
+ avatar="https://assets.dub.co/misc/dub-avatar.svg"
+ animate
+ >
+ <p className="text-sm text-neutral-700">
+ Which workspace is this about?
+ </p>
+ <div className="mt-3 w-full max-w-72">
+ <WorkspaceCombobox
+ workspaces={workspaces}
+ onSelect={(ws) =>
+ setSelection((s) => ({
+ ...s,
+ selectedWorkspace: {
+ id: ws.id,
+ slug: ws.slug,
+ name: ws.name,
+ },
+ }))
+ }
+ />
+ </div>
+ </SupportMessage>
+ )}
+
+ {effectiveAccountType === "workspace" &&
+ selection.selectedWorkspace && (
+ <SupportMessage
+ avatar="https://assets.dub.co/misc/dub-avatar.svg"
+ animate
+ >
+ <p className="text-sm text-neutral-700">
+ Got it β€”{" "}
+ <span className="font-medium">
+ {selection.selectedWorkspace.name}
+ </span>{" "}
+ (Dub workspace). How can I help you today?
+ </p>
+ {showStarterQuestions && (
+ <StarterQuestions
+ context={context === "docs" ? "docs" : "app"}
+ onSelect={handleSend}
+ className="mt-3"
+ />
+ )}
+ </SupportMessage>
+ )}
+
+ {effectiveAccountType === "partner" && !selection.selectedProgram && (
+ <SupportMessage
+ avatar="https://assets.dub.co/misc/dub-avatar.svg"
+ animate
+ >
+ {!hasPartnerProfile ? (
+ <>
+ <p className="text-sm text-neutral-700">
+ It looks like you don't have a partner account linked to your
+ profile.
+ </p>
+ <a
+ href="https://partners.dub.co"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="mt-3 inline-flex items-center gap-1 rounded-lg border border-neutral-200 bg-white px-3 py-1.5 text-xs font-medium text-neutral-600 shadow-sm transition-colors hover:bg-neutral-50"
+ >
+ Go to partners.dub.co β†—
+ </a>
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-neutral-700">
+ Which program is this about?
+ </p>
+ <div className="mt-3 w-full max-w-72">
+ <ProgramCombobox
+ enrollments={programEnrollments}
+ isLoading={isLoadingPrograms}
+ onSelect={(program) =>
+ setSelection((s) => ({
+ ...s,
+ selectedProgram: {
+ id: program.id,
+ slug: program.slug,
+ name: program.name,
+ },
+ }))
+ }
+ />
+ </div>
+ </>
+ )}
+ </SupportMessage>
+ )}
+
+ {effectiveAccountType === "partner" && selection.selectedProgram && (
+ <SupportMessage
+ avatar="https://assets.dub.co/misc/dub-avatar.svg"
+ animate
+ >
+ <p className="text-sm text-neutral-700">
+ Got it β€”{" "}
+ <span className="font-medium">
+ {selection.selectedProgram.name}
+ </span>{" "}
+ (Partner Program). How can I help you today?
+ </p>
+ {showStarterQuestions && (
+ <StarterQuestions
+ context={context === "docs" ? "docs" : "partners"}
+ onSelect={handleSend}
+ className="mt-3"
+ />
+ )}
+ </SupportMessage>
+ )}
+
+ {context === "docs" &&
+ showStarterQuestions &&
+ !selection.selectedWorkspace &&
+ !selection.selectedProgram && (
+ <StarterQuestions
+ context="docs"
+ onSelect={handleSend}
+ className="px-1"
+ />
+ )}
+
+ {canChat &&
+ messages.map((message, index) => {
+ const isUser = message.role === "user";
+ const textContent = message.parts
+ .filter((p) => p.type === "text")
+ .map((p) => (p as { type: "text"; text: string }).text)
+ .join("");
+
+ if (!textContent) return null;
+
+ return (
+ <SupportMessage
+ key={message.id}
+ avatar={
+ isUser
+ ? userAvatar
+ : "https://assets.dub.co/misc/dub-avatar.svg"
+ }
+ isUser={isUser}
+ animate
+ >
+ {isUser ? (
+ <p className="text-sm">{textContent}</p>
+ ) : (
+ <Streamdown
+ key={index}
+ isAnimating={status === "streaming"}
+ className="text-content-emphasis"
+ components={{
+ h1: () => null,
+ h2: () => null,
+ h3: () => null,
+ h4: () => null,
+ h5: () => null,
+ h6: () => null,
+ a: ({ children, href }) => (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="cursor-help font-medium text-neutral-900 underline decoration-dotted underline-offset-2 hover:text-neutral-600"
+ >
+ {children}
+ </a>
+ ),
+ ul: ({ children }) => {
+ return (
+ <ul
+ style={{
+ listStylePosition: "inside",
+ }}
+ className="list-disc"
+ >
+ {children}
+ </ul>
+ );
+ },
+ }}
+ >
+ {textContent}
+ </Streamdown>
+ )}
+ </SupportMessage>
+ );
+ })}
+
+ {status === "submitted" && (
+ <SupportMessage avatar="https://assets.dub.co/misc/dub-avatar.svg">
+ <div className="flex gap-1 py-1">
+ {[0, 1, 2].map((i) => (
+ <span
+ key={i}
+ className="size-1.5 animate-bounce rounded-full bg-neutral-400"
+ style={{ animationDelay: `${i * 150}ms` }}
+ />
+ ))}
+ </div>
+ </SupportMessage>
+ )}
+
+ {ticketCreated && (
+ <div className="rounded-xl border border-green-100 bg-green-50 px-4 py-3 text-sm text-green-800">
+ βœ“ Your support ticket has been created. Our team will get back to
+ you shortly.
+ </div>
+ )}
+
+ <div />
+ </div>
+
+ <div className="shrink-0 border-t border-neutral-100 bg-white p-3">
+ <div className="relative">
+ <TextareaAutosize
+ minRows={3}
+ maxRows={6}
+ placeholder={
+ !canChat
+ ? "Select an account above to start chatting..."
+ : effectiveAccountType === "partner"
+ ? "Ask about payouts, referrals, or commissions..."
+ : context === "docs"
+ ? "Ask about API, SDK, webhooks..."
+ : "Ask about links, analytics, or your account..."
+ }
+ value={input}
+ disabled={
+ !canChat || status === "streaming" || status === "submitted"
+ }
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ handleSend();
+ }
+ }}
+ className={cn(
+ "w-full resize-none rounded-xl border border-neutral-200 py-2.5 pl-3 pr-[72px] text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors",
+ "focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200 disabled:cursor-not-allowed disabled:bg-neutral-50 disabled:opacity-60",
+ )}
+ />
+ <button
+ type="button"
+ onClick={() => handleSend()}
+ disabled={
+ !canChat ||
+ status === "streaming" ||
+ status === "submitted" ||
+ !input.trim()
+ }
+ className={cn(
+ "absolute bottom-4 right-3 flex size-8 items-center justify-center rounded-full transition-all",
+ canChat && input.trim() && status === "ready"
+ ? "bg-neutral-900 text-white hover:bg-neutral-700"
+ : "cursor-not-allowed bg-neutral-200 text-neutral-400",
+ )}
+ aria-label="Send message"
+ >
+ <PaperPlane className="size-4" />
+ </button>
+ </div>
+
+ <div className="mt-px flex flex-col items-center gap-1">
+ <p className="text-center text-xs text-neutral-400">
+ AI may make mistakes. Verify important information.
+ </p>
+ {canEscalate && (
+ <button
+ type="button"
+ onClick={handleEscalate}
+ className="text-xs font-medium text-neutral-500 underline decoration-dotted underline-offset-2 hover:text-neutral-700"
+ >
+ Convert to support ticket β†’
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/support/embedded-chat.tsx b/apps/web/ui/support/embedded-chat.tsx
new file mode 100644
index 0000000000..35bbb0dcc8
--- /dev/null
+++ b/apps/web/ui/support/embedded-chat.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import { ChatInterface } from "./chat-interface";
+import { SupportChatContext } from "./types";
+
+export function EmbeddedSupportChat({
+ context = "app",
+}: {
+ context?: SupportChatContext;
+}) {
+ return (
+ <div className="flex min-h-[500px] flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-sm">
+ <div className="flex shrink-0 items-center gap-3 border-b border-neutral-100 bg-neutral-50 px-5 py-4">
+ <img
+ src="https://assets.dub.co/misc/dub-avatar.svg"
+ alt="Dub Support"
+ className="size-8 rounded-full"
+ draggable={false}
+ />
+ <div>
+ <p className="text-sm font-semibold text-neutral-900">Dub Support</p>
+ <p className="text-xs text-neutral-500">
+ AI-powered Β· escalates to human when needed
+ </p>
+ </div>
+ </div>
+
+ <ChatInterface context={context} className="flex-1 px-1" embedded />
+ </div>
+ );
+}
diff --git a/apps/web/ui/support/message.tsx b/apps/web/ui/support/message.tsx
new file mode 100644
index 0000000000..5000ca1ab3
--- /dev/null
+++ b/apps/web/ui/support/message.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { cn } from "@dub/utils";
+import { PropsWithChildren } from "react";
+
+export function SupportMessage({
+ avatar,
+ content,
+ animate = false,
+ children,
+ isUser = false,
+}: PropsWithChildren<{
+ avatar: string;
+ content?: string;
+ animate?: boolean;
+ isUser?: boolean;
+}>) {
+ return (
+ <div
+ className={cn(
+ "flex origin-top-left items-start gap-3",
+ isUser && "flex-row-reverse items-end",
+ animate && "animate-scale-in-fade",
+ )}
+ >
+ <img
+ src={avatar}
+ alt={`${name} avatar`}
+ className={cn("size-8 shrink-0 rounded-full", isUser && "mb-1")}
+ draggable={false}
+ />
+
+ <div
+ className={cn(
+ "max-w-[85%] grow py-1",
+ isUser && "flex flex-col items-end",
+ )}
+ >
+ {content && (
+ <p
+ className={cn(
+ "rounded-2xl rounded-br px-3 py-2 text-sm",
+ isUser ? "bg-neutral-900 text-white" : "text-neutral-800",
+ )}
+ >
+ {content}
+ </p>
+ )}
+ {children && (
+ <div
+ className={cn(
+ "text-sm",
+ isUser &&
+ "rounded-2xl rounded-br bg-neutral-900 px-3 py-2 text-white",
+ )}
+ >
+ {children}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/support/program-combobox.tsx b/apps/web/ui/support/program-combobox.tsx
new file mode 100644
index 0000000000..182bed8905
--- /dev/null
+++ b/apps/web/ui/support/program-combobox.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { Combobox } from "@dub/ui";
+import { cn, OG_AVATAR_URL } from "@dub/utils";
+import { useMemo, useState } from "react";
+
+export type ProgramSummary = {
+ id: string;
+ name: string;
+ slug: string;
+ logo?: string | null;
+};
+
+export function ProgramCombobox({
+ enrollments,
+ isLoading,
+ selectedSlug,
+ onSelect,
+}: {
+ enrollments: { program: ProgramSummary }[] | undefined;
+ isLoading: boolean;
+ selectedSlug?: string;
+ onSelect: (program: ProgramSummary) => void;
+}) {
+ const [open, setOpen] = useState(false);
+
+ const options = useMemo(
+ () =>
+ enrollments?.map((e) => ({
+ value: e.program.slug,
+ label: e.program.name,
+ icon: (
+ <img
+ src={
+ e.program.logo ||
+ `${OG_AVATAR_URL}${encodeURIComponent(e.program.name)}`
+ }
+ alt={e.program.name}
+ className="size-3.5 rounded-full"
+ />
+ ),
+ })),
+ [enrollments],
+ );
+
+ const selected = useMemo(
+ () => options?.find((o) => o.value === selectedSlug) ?? null,
+ [options, selectedSlug],
+ );
+
+ const isReady = !isLoading && enrollments !== undefined;
+
+ return (
+ <Combobox
+ forceDropdown
+ options={isReady ? options : undefined}
+ setSelected={(opt) => {
+ if (!opt) return;
+ const enrollment = enrollments?.find(
+ (e) => e.program.slug === opt.value,
+ );
+ if (enrollment) onSelect(enrollment.program);
+ }}
+ selected={selected}
+ icon={selected?.icon}
+ caret
+ placeholder={isReady ? "Select program" : ""}
+ searchPlaceholder="Search programs..."
+ matchTriggerWidth
+ open={open}
+ onOpenChange={setOpen}
+ buttonProps={{
+ className: cn(
+ "w-full max-w-[360px] justify-start border-neutral-300 px-2.5 h-9 text-sm",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
+ ),
+ }}
+ labelProps={{
+ className: "text-sm text-neutral-600",
+ }}
+ inputClassName="text-sm h-10"
+ optionClassName="h-8"
+ emptyState={
+ <div className="flex w-full flex-col items-center gap-2 py-3 text-xs text-neutral-500">
+ No programs found
+ </div>
+ }
+ >
+ {!isReady ? (
+ <div className="flex items-center gap-1.5 text-sm">
+ <div className="size-3.5 animate-pulse rounded-full bg-neutral-200" />
+ <div className="h-3.5 w-24 animate-pulse rounded bg-neutral-200" />
+ </div>
+ ) : (
+ selected?.label
+ )}
+ </Combobox>
+ );
+}
diff --git a/apps/web/ui/support/starter-questions.tsx b/apps/web/ui/support/starter-questions.tsx
new file mode 100644
index 0000000000..0054f3e497
--- /dev/null
+++ b/apps/web/ui/support/starter-questions.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { cn } from "@dub/utils";
+import { SupportChatContext } from "./types";
+
+const STARTER_QUESTIONS: Record<SupportChatContext, string[]> = {
+ app: [
+ "How do I set up custom domain?",
+ "How do I set up conversion tracking?",
+ "How does attribution work?",
+ "How do I use the Dub API?",
+ "How do I set up a partner program?",
+ "How do I update my billing information?",
+ ],
+ partners: [
+ "How do I set up my bank account for payouts?",
+ "Which countries support payouts?",
+ "How is my commission calculated?",
+ "When will I receive my payout?",
+ "How do I track my referral clicks?",
+ "How do I update my partner profile?",
+ ],
+ docs: [
+ "How do I install the Dub SDK?",
+ "How do webhooks work?",
+ "How do I track conversions?",
+ "What are the API rate limits?",
+ "How do I authenticate with the API?",
+ "How do I shorten links programmatically?",
+ ],
+};
+
+export function StarterQuestions({
+ context,
+ onSelect,
+ className,
+}: {
+ context: SupportChatContext;
+ onSelect: (question: string) => void;
+ className?: string;
+}) {
+ const questions = STARTER_QUESTIONS[context] ?? STARTER_QUESTIONS.app;
+
+ return (
+ <div className={cn("flex flex-wrap gap-2", className)}>
+ {questions.map((q) => (
+ <button
+ key={q}
+ type="button"
+ onClick={() => onSelect(q)}
+ className="rounded-full border border-neutral-200 bg-white px-3 py-1.5 text-xs font-medium text-neutral-600 shadow-sm transition-colors hover:border-neutral-300 hover:bg-neutral-50 hover:text-neutral-800"
+ >
+ {q}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/ui/support/types.ts b/apps/web/ui/support/types.ts
new file mode 100644
index 0000000000..3dead90166
--- /dev/null
+++ b/apps/web/ui/support/types.ts
@@ -0,0 +1,20 @@
+export type SupportChatVariant = "embedded" | "bubble";
+export type SupportChatContext = "app" | "partners" | "docs";
+
+const CONTEXT_MAP: Record<string, Exclude<SupportChatContext, undefined>> = {
+ app: "app",
+ partners: "partners",
+ docs: "docs",
+};
+
+export function parseSupportChatVariant(
+ value: string | undefined,
+): SupportChatVariant {
+ return value === "embedded" ? "embedded" : "bubble";
+}
+
+export function parseSupportChatContext(
+ value: string | undefined,
+): SupportChatContext {
+ return (value && CONTEXT_MAP[value]) || CONTEXT_MAP.docs;
+}
diff --git a/apps/web/ui/support/workspace-combobox.tsx b/apps/web/ui/support/workspace-combobox.tsx
new file mode 100644
index 0000000000..3e0022cd81
--- /dev/null
+++ b/apps/web/ui/support/workspace-combobox.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { Combobox } from "@dub/ui";
+import { cn, OG_AVATAR_URL } from "@dub/utils";
+import { useMemo, useState } from "react";
+
+export type WorkspaceSummary = {
+ id: string;
+ name: string;
+ slug: string;
+ logo?: string | null;
+};
+
+export function WorkspaceCombobox({
+ workspaces,
+ selectedSlug,
+ onSelect,
+}: {
+ workspaces: WorkspaceSummary[] | undefined;
+ selectedSlug?: string;
+ onSelect: (ws: WorkspaceSummary) => void;
+}) {
+ const [open, setOpen] = useState(false);
+
+ const options = useMemo(
+ () =>
+ workspaces?.map((ws) => ({
+ value: ws.slug,
+ label: ws.name,
+ icon: (
+ <img
+ src={ws.logo || `${OG_AVATAR_URL}${encodeURIComponent(ws.name)}`}
+ alt={ws.name}
+ className="size-3.5 rounded-full"
+ />
+ ),
+ })),
+ [workspaces],
+ );
+
+ const selected = useMemo(
+ () => options?.find((o) => o.value === selectedSlug) ?? null,
+ [options, selectedSlug],
+ );
+
+ return (
+ <Combobox
+ forceDropdown
+ options={workspaces === undefined ? undefined : options}
+ setSelected={(opt) => {
+ if (!opt) return;
+ const ws = workspaces?.find((w) => w.slug === opt.value);
+ if (ws) onSelect(ws);
+ }}
+ selected={selected}
+ icon={selected?.icon}
+ caret
+ placeholder={workspaces === undefined ? "" : "Select workspace"}
+ searchPlaceholder="Search workspaces..."
+ matchTriggerWidth
+ open={open}
+ onOpenChange={setOpen}
+ buttonProps={{
+ className: cn(
+ "w-full max-w-[360px] justify-start border-neutral-300 px-2.5 h-9 text-sm",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
+ ),
+ }}
+ labelProps={{
+ className: "text-sm text-neutral-600",
+ }}
+ inputClassName="text-sm h-10"
+ optionClassName="h-8"
+ emptyState={
+ <div className="flex w-full flex-col items-center gap-2 py-3 text-xs text-neutral-500">
+ No workspaces found
+ </div>
+ }
+ >
+ {workspaces === undefined ? (
+ <div className="flex items-center gap-1.5 text-sm">
+ <div className="size-3.5 animate-pulse rounded-full bg-neutral-200" />
+ <div className="h-3.5 w-24 animate-pulse rounded bg-neutral-200" />
+ </div>
+ ) : (
+ selected?.label
+ )}
+ </Combobox>
+ );
+}
diff --git a/packages/ui/src/carousel/nav-bar.tsx b/packages/ui/src/carousel/nav-bar.tsx
index 6017a9789b..58e6256c8e 100644
--- a/packages/ui/src/carousel/nav-bar.tsx
+++ b/packages/ui/src/carousel/nav-bar.tsx
@@ -89,7 +89,7 @@ export const CarouselNavBar = ({
transition={{
type: "tween",
duration:
- (autoplay?.options.delay ?? AUTOPLAY_DEFAULT_DELAY) /
+ (autoplay?.options.delay ?? AUTOPLAY_DEFAULT_DELAY) as number /
1000,
}}
className="animate-fill-width h-full w-full rounded-full bg-black"
diff --git a/packages/ui/src/combobox/index.tsx b/packages/ui/src/combobox/index.tsx
index d0b63aa6b0..ad0a4867fc 100644
--- a/packages/ui/src/combobox/index.tsx
+++ b/packages/ui/src/combobox/index.tsx
@@ -75,6 +75,7 @@ export type ComboboxProps<
optionClassName?: string;
matchTriggerWidth?: boolean;
hideSearch?: boolean;
+ forceDropdown?: boolean;
}>;
function isMultipleSelection(
@@ -116,6 +117,7 @@ export function Combobox({
optionClassName,
matchTriggerWidth,
hideSearch = false,
+ forceDropdown = false,
children,
}: ComboboxProps<boolean | undefined, any>) {
const isMultiple = isMultipleSelection(multiple, setSelected);
@@ -241,6 +243,7 @@ export function Combobox({
setOpenPopover={setIsOpen}
align="start"
side={side}
+ forceDropdown={forceDropdown}
onWheel={(e) => {
// Allows scrolling to work when the popover's in a modal
e.stopPropagation();
diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsx
index c066f926d5..7c1a1d7f92 100644
--- a/packages/ui/src/popover.tsx
+++ b/packages/ui/src/popover.tsx
@@ -13,6 +13,7 @@ export type PopoverProps = PropsWithChildren<{
openPopover: boolean;
setOpenPopover: (open: boolean) => void;
mobileOnly?: boolean;
+ forceDropdown?: boolean;
popoverContentClassName?: string;
onOpenAutoFocus?: PopoverPrimitive.PopoverContentProps["onOpenAutoFocus"];
collisionBoundary?: Element | Element[];
@@ -30,6 +31,7 @@ export function Popover({
openPopover,
setOpenPopover,
mobileOnly,
+ forceDropdown,
popoverContentClassName,
onOpenAutoFocus,
collisionBoundary,
@@ -40,7 +42,7 @@ export function Popover({
}: PopoverProps) {
const { isMobile } = useMediaQuery();
- if (mobileOnly || isMobile) {
+ if (!forceDropdown && (mobileOnly || isMobile)) {
return (
<Drawer.Root open={openPopover} onOpenChange={setOpenPopover}>
<Drawer.Trigger className="sm:hidden" asChild>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a6f9e2e903..24475f382d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -155,6 +155,9 @@ importers:
'@upstash/redis':
specifier: ^1.35.3
version: 1.35.3
+ '@upstash/vector':
+ specifier: ^1.2.2
+ version: 1.2.2
'@upstash/workflow':
specifier: ^0.2.19
version: 0.2.19([email protected])
@@ -356,6 +359,9 @@ importers:
sonner:
specifier: ^1.4.41
+ streamdown:
+ specifier: ^2.3.0
stripe:
specifier: ^18.2.0
version: 18.2.0(@types/[email protected])
@@ -6037,6 +6043,9 @@ packages:
'@upstash/[email protected]':
resolution: {integrity: sha512-hSjv66NOuahW3MisRGlSgoszU2uONAY2l5Qo3Sae8OT3/Tng9K+2/cBRuyPBX8egwEGcNNCF9+r0V6grNnhL+w==}
+ '@upstash/[email protected]':
+ resolution: {integrity: sha512-ptQ9xnxtKqmpNK52PCcHCszlPOLxIBfjsv7ty8RoF95pkjctS9rSjTQ3Pl9bx5VFbpDj+0dMXw88WLt6swDkgQ==}
+
'@upstash/[email protected]':
resolution: {integrity: sha512-i3MoVV4XVaE1dhYBrSDGDlRGkB7gWuTjVcU4c/nnDIUzJWIfZdtjsH8FprfDG/RMS9PK51MtLg7SsUXxWtjD5g==}
@@ -8715,12 +8724,33 @@ packages:
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==}
+
+ resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}
+
+ resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}
+
+ resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
+
resolution: {integrity: sha512-H/y0+IWPdsLLS738P8tDnrQ8Z+dj12zQQ6WC11TIM21C8WFVoIxcqWXf2H3hiTVZjF1AWqoimGwrTWecWrnmRQ==}
+ resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+
+ resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}
+
resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
+ resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==}
+
resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}
hasBin: true
@@ -8763,6 +8793,12 @@ packages:
resolution: {integrity: sha512-/sXbVCWayk6GDVg3ctOX6nxaVj7So40FcFAnWlWGNAB1LpYKcV5Cd10APjPjW80O7zYW2MsjBV4zZ7IZO5fVow==}
+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+
+ resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
+
resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
@@ -8904,6 +8940,9 @@ packages:
resolution: {integrity: sha512-qlD8YNDqyTKTyuITrDOffsl6Tdhv+UC4hcdAVuQsK4IMQ99nSgd1MIA/Q+jQYoh9r3hVUXhYh7urSRmXPkW04g==}
+ resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
+
resolution: {integrity: sha512-md6rhmD+zmMnUh5crQNSQxq3keBRYvE3odbr4Qb9g2NWzQv9azi+t1a3X4TBTbh98fsGHgEEJlzbe1q860uGCA==}
peerDependencies:
@@ -9851,6 +9890,11 @@ packages:
engines: {node: '>= 18'}
hasBin: true
+ resolution: {integrity: sha512-jt1v2ObpyOKR8p4XaUJVk3YWRJ5n+i4+rjQopxvV32rSndTJXvIzuUdWWIy/1pFQMkQmvTXawzDNqOH/CUmx6A==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==}
@@ -11092,6 +11136,9 @@ packages:
resolution: {integrity: sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==}
+ resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
+
resolution: {integrity: sha512-j0kORIBm8ayJNl3zQvD1TTPHJX3g042et6y/KQhZhnPrruO8exkTgG8X+NRpj7kIyMMEx74Xb3DyMIBtO0IKkQ==}
@@ -11467,18 +11514,36 @@ packages:
resolution: {integrity: sha512-+crtS5QjFRqFCoQmvGduwYWEBng99ZvmFvF+cUJkGYF1L1BfU8C6Zp9T7f5vPAwyLkUExpvK+ANVZmGU49qi4Q==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw==}
+
+ resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}
+
+ resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}
+
resolution: {integrity: sha512-U92vJgBPkbw4Zfu/IiW2oTZLSL3Zpv+uI7My2eq8JxKgqraFdU8YUGicEJCEgSbeaG+QDFqIcwwfMTOEelPxuA==}
+ resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
+
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
resolution: {integrity: sha512-z3tJrAs2kIs1AqIIy6pzHmAHlF1hWQ+OdY4/hv+Wxe35EhyLKcajL33iUEn3ScxtFox9nUvRufR/Zre8Q08H/g==}
+ resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}
+
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
+ resolution: {integrity: sha512-4wC12bgXsfKAjF1ewwkNIQz5sqewz/z1xgIgjEMb3r1pEytQ37F0Cm6i+OhbTWEvguJD7lhOUJhK5fSasw9f0w==}
+
resolution: {integrity: sha512-/hS+Y0u3aOfIETiaiirUFwDBDzmXPvO+jAfKTitUngIPzdKc6Z0LoFjM/CK5PL4C+eKwHohlHAb6H0VFfmmUsw==}
@@ -11991,6 +12056,12 @@ packages:
prettier:
optional: true
+ resolution: {integrity: sha512-OqS3by/lt91lSicE8RQP2nTsYI6Q/dQgGP2vcyn9YesCmRHhNjswAuBAZA1z0F4+oBU3II/eV51LqjCqwTb1lw==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-znKXEBxfatz2GBNK02kRnCXjV+AA4kjZIUxeWSr3UGirZMJfTE9uiwKHobnbgxWyL/JWro8tTq+vOqAK1/qbSA==}
@@ -12113,6 +12184,12 @@ packages:
resolution: {integrity: sha512-H2N9c26eXjzL/S/K+i/RHHcFanE74dptvvjM8iwzwbVcWY/zjBbgRqF3K0DY4+OD+uTTASTBvDoxPDaPN02D7g==}
+ resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}
+
+ resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
+
resolution: {integrity: sha512-khxq+Qm3xEyZfKd/y9L3oIWQimxuc4STrQKtQn8aSDRHb8mFgpukgX1hdzfrMEW6JCjyJ8p89x+IUMVnCBI1PA==}
@@ -12222,6 +12299,9 @@ packages:
resolution: {integrity: sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==}
+ resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==}
+
resolution: {integrity: sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA==}
@@ -13016,6 +13096,9 @@ packages:
resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==}
engines: {'0': node >=0.6.0}
+ resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==}
+
resolution: {integrity: sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==}
@@ -13204,6 +13287,9 @@ packages:
resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==}
+ resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}
+
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
@@ -19669,6 +19755,8 @@ snapshots:
dependencies:
uncrypto: 0.1.3
+ '@upstash/[email protected]': {}
+
dependencies:
'@ai-sdk/openai': 1.3.24([email protected])
@@ -21614,8 +21702,7 @@ snapshots:
- optional: true
optional: true
@@ -22991,6 +23078,43 @@ snapshots:
dependencies:
function-bind: 1.1.2
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.2
+ devlop: 1.1.0
+ hastscript: 9.0.1
+ property-information: 7.1.0
+ vfile: 6.0.2
+ vfile-location: 5.0.3
+ web-namespaces: 2.0.1
+
+ dependencies:
+ '@types/hast': 3.0.4
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.2
+ '@ungap/structured-clone': 1.2.0
+ hast-util-from-parse5: 8.0.3
+ hast-util-to-parse5: 8.0.1
+ html-void-elements: 3.0.0
+ mdast-util-to-hast: 13.2.0
+ parse5: 7.3.0
+ unist-util-position: 5.0.0
+ unist-util-visit: 5.0.0
+ vfile: 6.0.2
+ web-namespaces: 2.0.1
+ zwitch: 2.0.4
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@ungap/structured-clone': 1.2.0
+ unist-util-position: 5.0.0
+
dependencies:
'@types/estree': 1.0.8
@@ -23011,10 +23135,48 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/estree': 1.0.8
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.2
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ estree-util-is-identifier-name: 3.0.0
+ hast-util-whitespace: 3.0.0
+ mdast-util-mdx-expression: 2.0.0
+ mdast-util-mdx-jsx: 3.1.2
+ mdast-util-mdxjs-esm: 2.0.1
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ style-to-js: 1.1.21
+ unist-util-position: 5.0.0
+ vfile-message: 4.0.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.4
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ web-namespaces: 2.0.1
+ zwitch: 2.0.4
+
dependencies:
'@types/hast': 3.0.4
+ dependencies:
+ '@types/hast': 3.0.4
+ comma-separated-tokens: 2.0.3
+ hast-util-parse-selector: 4.0.0
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+
@@ -23054,6 +23216,10 @@ snapshots:
+
+
dependencies:
domelementtype: 2.3.0
@@ -23234,6 +23400,8 @@ snapshots:
+
dependencies:
react: 19.1.3
@@ -24473,6 +24641,8 @@ snapshots:
+
@@ -25526,7 +25696,6 @@ snapshots:
dependencies:
entities: 6.0.1
- optional: true
dependencies:
@@ -25899,6 +26068,8 @@ snapshots:
+
dependencies:
prosemirror-transform: 1.10.4
@@ -26443,6 +26614,21 @@ snapshots:
dependencies:
rc: 1.2.8
+ dependencies:
+ unist-util-visit: 5.0.0
+
+ dependencies:
+ '@types/hast': 3.0.4
+ hast-util-raw: 9.1.0
+ vfile: 6.0.2
+
+ dependencies:
+ '@types/hast': 3.0.4
+ hast-util-sanitize: 5.0.2
+
dependencies:
'@types/mdast': 4.0.4
@@ -26454,6 +26640,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-gfm: 3.0.0
+ micromark-extension-gfm: 3.0.0
+ remark-parse: 11.0.0
+ remark-stringify: 11.0.0
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 4.0.4
@@ -26471,12 +26668,22 @@ snapshots:
unified: 11.0.5
vfile: 6.0.2
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ mdast-util-to-hast: 13.2.0
+ unified: 11.0.5
+ vfile: 6.0.2
+
dependencies:
'@types/mdast': 4.0.4
mdast-util-to-markdown: 2.1.0
unified: 11.0.5
+
@@ -27160,6 +27367,28 @@ snapshots:
- utf-8-validate
optional: true
+ dependencies:
+ clsx: 2.1.1
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ marked: 17.0.3
+ react: 19.1.3
+ react-dom: 19.1.3([email protected])
+ rehype-harden: 1.1.8
+ rehype-raw: 7.0.0
+ rehype-sanitize: 6.0.0
+ remark-gfm: 4.0.1
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ remend: 1.2.1
+ tailwind-merge: 3.5.0
+ unified: 11.0.5
+ unist-util-visit: 5.0.0
+ unist-util-visit-parents: 6.0.1
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
fast-fifo: 1.3.2
@@ -27313,6 +27542,14 @@ snapshots:
+ dependencies:
+ style-to-object: 1.0.14
+
+ dependencies:
+ inline-style-parser: 0.2.7
+
dependencies:
inline-style-parser: 0.2.3
@@ -27433,6 +27670,8 @@ snapshots:
optional: true
+
@@ -28491,6 +28730,11 @@ snapshots:
extsprintf: 1.3.0
optional: true
+ dependencies:
+ '@types/unist': 3.0.2
+ vfile: 6.0.2
+
dependencies:
'@types/unist': 3.0.2
@@ -28646,6 +28890,8 @@ snapshots:
dependencies:
defaults: 1.0.4
+