The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Embeddable support chat widget improvements (#3522)
Pedro Ladeirac6e14a8cd7f0
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.tsxindex 656d3ca8cd..cbbddf489c 100644--- a/apps/web/app/app.dub.co/embed/support-chat/page.tsx+++ b/apps/web/app/app.dub.co/embed/support-chat/page.tsx@@ -1,20 +1,19 @@import { SupportChatBubble } from "@/ui/support/chat-bubble";import { EmbeddedSupportChat } from "@/ui/support/embedded-chat";-import { SupportChatContext, SupportChatVariant } from "@/ui/support/types";+import { 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;+ const { variant } = await props.searchParams;if (variant === "embedded") {return (<div className="min-h-[500px] bg-white p-4">- <EmbeddedSupportChat context={context} />+ <EmbeddedSupportChat /><SupportChatDynamicHeightMessenger /></div>);@@ -22,7 +21,7 @@ export default async function SupportChatEmbedPage(props: {return (<div className="min-h-screen bg-transparent">- <SupportChatBubble context={context} />+ <SupportChatBubble /></div>);}diff --git a/apps/web/lib/ai/build-system-prompt.ts b/apps/web/lib/ai/build-system-prompt.tsindex 15f5b88be4..c3549721da 100644--- a/apps/web/lib/ai/build-system-prompt.ts+++ b/apps/web/lib/ai/build-system-prompt.ts@@ -24,10 +24,12 @@ const CONTEXT_SYSTEM_PROMPTS: Record<SupportChatContext, string> = {};const BASE_SYSTEM_PROMPT = `- You are powered by Dub's documentation and help articles. Always ground your answers in the retrieved content.+ You are powered by Dub's documentation and help articles.+ ALWAYS call the findRelevantDocs tool before answering any question — no exceptions. Do not answer from memory.+ Ground every answer in the content retrieved by findRelevantDocs.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.+ If findRelevantDocs returns no useful results, acknowledge it and offer to create a support ticket.Never make up information — if unsure, say so and offer to escalate.`.trim();@@ -64,7 +66,5 @@ export function buildSystemPrompt(globalContext?: GlobalChatContext): string {...accountSpecificPrompts,].join("\n\n");- console.log(systemPrompt);-return systemPrompt;}diff --git a/apps/web/ui/support/chat-bubble.tsx b/apps/web/ui/support/chat-bubble.tsxindex ce9a5d9fec..0d61b73f74 100644--- a/apps/web/ui/support/chat-bubble.tsx+++ b/apps/web/ui/support/chat-bubble.tsx@@ -1,32 +1,25 @@"use client";-import { MsgsFill, Xmark } from "@dub/ui/icons";+import { Tooltip } from "@dub/ui";+import { MsgsFill, Trash, 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;-}) {+export function SupportChatBubble() {const [isOpen, setIsOpen] = useState(false);+ const [resetKey, setResetKey] = useState(0);const panelRef = useRef<HTMLDivElement>(null);- const handleClose = () => {- setIsOpen(false);- };+ const handleClose = () => setIsOpen(false);+ const handleOpen = () => setIsOpen(true);+ const handleReset = () => setResetKey((k) => k + 1);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>@@ -52,18 +45,33 @@ export function SupportChatBubble({</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 className="flex items-center gap-0.5">+ <Tooltip content="Clear chat">+ <button+ type="button"+ onClick={handleReset}+ className="flex size-7 items-center justify-center rounded-lg text-neutral-400 transition-colors hover:bg-white/10 hover:text-white"+ aria-label="Clear chat"+ >+ <Trash className="size-3.5" />+ </button>+ </Tooltip>+ <Tooltip content="Close">+ <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>+ </Tooltip>+ </div></div><ChatInterface- context={context}+ key={resetKey}+ onReset={handleReset}className="flex-1 overflow-hidden"/></motion.div>diff --git a/apps/web/ui/support/chat-interface.tsx b/apps/web/ui/support/chat-interface.tsxindex 3f6fa26d7b..0037f0fa4e 100644--- a/apps/web/ui/support/chat-interface.tsx+++ b/apps/web/ui/support/chat-interface.tsx@@ -3,6 +3,7 @@import { GlobalChatContext } from "@/lib/ai/build-system-prompt";import useProgramEnrollments from "@/lib/swr/use-program-enrollments";import { useChat } from "@ai-sdk/react";+import { Combobox } from "@dub/ui";import { OfficeBuilding, PaperPlane, Users2 } from "@dub/ui/icons";import { cn, fetcher, OG_AVATAR_URL } from "@dub/utils";import { DefaultChatTransport } from "ai";@@ -12,23 +13,25 @@ import TextareaAutosize from "react-textarea-autosize";import { toast } from "sonner";import { Streamdown } from "streamdown";import "streamdown/styles.css";+import { MarkdownCodeBlock } from "./code-block";import useSWR from "swr";import { SupportMessage } from "./message";-import { ProgramCombobox } from "./program-combobox";+import { ProgramCombobox, ProgramSummary } from "./program-combobox";+import { extractSources, SourceCitations } from "./source-citations";+import { StatusIndicator } from "./status-indicator";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,+ onReset,}: {- context?: SupportChatContext;className?: string;embedded?: boolean;+ onReset?: () => void;}) {const { data: session, status: sessionStatus } = useSession();const scrollContainerRef = useRef<HTMLDivElement>(null);@@ -36,14 +39,7 @@ export function ChatInterface({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 effectiveAccountType = selection.accountType;const { data: workspaces } = useSWR<WorkspaceSummary[]>(effectiveAccountType === "workspace" ? "/api/workspaces" : null,@@ -54,18 +50,10 @@ export function ChatInterface({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;+ if (effectiveAccountType === "workspace") canChat = !!selection.selectedWorkspace;+ else if (effectiveAccountType === "partner") canChat = !!selection.selectedProgram;+ else canChat = false;const { messages, sendMessage, status, setMessages } = useChat({transport: new DefaultChatTransport({@@ -94,7 +82,8 @@ export function ChatInterface({body: {globalContext: {...selection,- chatLocation: context,+ chatLocation:+ effectiveAccountType === "partner" ? "partners" : "app",accountType: effectiveAccountType,},},@@ -115,27 +104,48 @@ export function ChatInterface({setMessages([]);};+ const handleWorkspaceSelect = (ws: WorkspaceSummary) => {+ if (selection.selectedWorkspace?.slug !== ws.slug) setMessages([]);+ setSelection((s) => ({+ ...s,+ selectedWorkspace: { id: ws.id, slug: ws.slug, name: ws.name },+ }));+ };++ const handleProgramSelect = (program: ProgramSummary) => {+ if (selection.selectedProgram?.slug !== program.slug) setMessages([]);+ setSelection((s) => ({+ ...s,+ selectedProgram: { id: program.id, slug: program.slug, name: program.name },+ }));+ };++ const accountTypeOptions = [+ {+ value: "workspace",+ label: "Workspace (app.dub.co)",+ icon: <OfficeBuilding className="size-3.5 shrink-0" />,+ },+ {+ value: "partner",+ label: "Partner (partners.dub.co)",+ icon: <Users2 className="size-3.5 shrink-0" />,+ },+ ];+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 assistantAvatar = embedded+ ? "https://assets.dub.co/misc/dub-avatar.svg"+ : undefined;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 (@@ -190,108 +200,69 @@ export function ChatInterface({<divref={scrollContainerRef}className={cn(- "flex flex-1 flex-col gap-6 px-4 py-8",+ "flex flex-1 flex-col gap-6 p-4",embedded ? "overflow-visible" : "overflow-y-auto",)}>- <SupportMessage- avatar="https://assets.dub.co/misc/dub-avatar.svg"- animate={false}- >+ <SupportMessage avatar={assistantAvatar} 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?"}+ Hi there! I'm Dub's AI support assistant. 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>- )}+ <div className="mt-3 w-full max-w-72">+ <Combobox+ forceDropdown+ selected={+ accountTypeOptions.find(+ (o) => o.value === effectiveAccountType,+ ) ?? null+ }+ setSelected={(opt) => {+ if (opt && opt.value !== effectiveAccountType)+ handleAccountTypeChange(opt.value as AccountType);+ }}+ options={accountTypeOptions}+ icon={+ accountTypeOptions.find((o) => o.value === effectiveAccountType)+ ?.icon+ }+ caret+ placeholder="Select account type"+ hideSearch+ matchTriggerWidth+ popoverProps={{+ contentClassName: "w-[var(--radix-popover-trigger-width)]",+ }}+ buttonProps={{+ className: cn(+ "w-full max-w-72 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" }}+ optionClassName="h-8"+ />+ </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 === "workspace" && (+ <SupportMessage avatar={assistantAvatar} 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}+ selectedSlug={selection.selectedWorkspace?.slug}+ onSelect={handleWorkspaceSelect}+ />+ </div>+ </SupportMessage>+ )}- {effectiveAccountType === "partner" && !selection.selectedProgram && (- <SupportMessage- avatar="https://assets.dub.co/misc/dub-avatar.svg"- animate- >+ {effectiveAccountType === "partner" && (+ <SupportMessage avatar={assistantAvatar} animate>{!hasPartnerProfile ? (<><p className="text-sm text-neutral-700">@@ -316,16 +287,8 @@ export function ChatInterface({<ProgramComboboxenrollments={programEnrollments}isLoading={isLoadingPrograms}- onSelect={(program) =>- setSelection((s) => ({- ...s,- selectedProgram: {- id: program.id,- slug: program.slug,- name: program.name,- },- }))- }+ selectedSlug={selection.selectedProgram?.slug}+ onSelect={handleProgramSelect}/></div></>@@ -333,21 +296,14 @@ export function ChatInterface({</SupportMessage>)}- {effectiveAccountType === "partner" && selection.selectedProgram && (- <SupportMessage- avatar="https://assets.dub.co/misc/dub-avatar.svg"- animate- >+ {showStarterQuestions && (+ <SupportMessage avatar={assistantAvatar} 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?+ How can I help you today?</p>- {showStarterQuestions && (+ {effectiveAccountType !== "partner" && (<StarterQuestions- context={context === "docs" ? "docs" : "partners"}+ context="app"onSelect={handleSend}className="mt-3"/>@@ -355,173 +311,188 @@ export function ChatInterface({</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("");+ .join("\n\n");++ const isCurrentlyStreaming =+ status === "streaming" && index === messages.length - 1;+ const sources =+ !isUser && !isCurrentlyStreaming+ ? extractSources(+ message.parts as { type: string; [key: string]: unknown }[],+ )+ : [];+- if (!textContent) return null;+ // Skip user messages with no text, but keep assistant messages+ // visible during tool calls (they temporarily have no text parts)+ if (isUser && !textContent) return null;+ if (!isUser && !textContent && !message.parts?.length) return null;return (<SupportMessagekey={message.id}- avatar={- isUser- ? userAvatar- : "https://assets.dub.co/misc/dub-avatar.svg"- }+ avatar={isUser ? userAvatar : assistantAvatar}isUser={isUser}animate>{isUser ? (<p className="text-sm">{textContent}</p>+ ) : !textContent ? (+ (() => {+ const isSearching = message.parts?.some(+ (p: any) =>+ p.type === "tool-findRelevantDocs" &&+ p.state !== "output-available",+ );+ return (+ <StatusIndicator+ label={isSearching ? "Searching docs..." : "Thinking..."}+ className="py-0.5"+ />+ );+ })()) : (- <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"+ <>+ <Streamdown+ key={index}+ isAnimating={status === "streaming"}+ className="text-content-emphasis"+ controls={false}+ 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 }) => (+ <ul className="list-disc list-outside pl-6">+ {children}</ul>- );- },- }}- >- {textContent}- </Streamdown>+ ),+ ol: ({ children }) => (+ <ol className="list-decimal list-outside pl-6">+ {children}+ </ol>+ ),+ code: MarkdownCodeBlock,+ }}+ >+ {textContent}+ </Streamdown>+ <SourceCitations sources={sources} />+ </>)}</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 avatar={assistantAvatar}>+ <StatusIndicator label="Thinking..." className="py-0.5" /></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",- )}- />+ {ticketSubmitted ? (+ <div className="shrink-0 border-t border-neutral-100 bg-neutral-50 px-4 py-4 text-center">+ <p className="text-sm font-medium text-neutral-700">+ Your ticket has been submitted.+ </p>+ <p className="mt-0.5 text-xs text-neutral-500">+ To ask more questions, please start a new session.+ </p><buttontype="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"+ onClick={onReset ?? (() => window.location.reload())}+ className="mt-3 rounded-lg bg-neutral-900 px-4 py-1.5 text-xs font-medium text-white transition-colors hover:bg-neutral-700">- <PaperPlane className="size-4" />+ Start new session</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 && (+ ) : (+ <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..."+ : "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",+ )}+ /><buttontype="button"- onClick={handleEscalate}- className="text-xs font-medium text-neutral-500 underline decoration-dotted underline-offset-2 hover:text-neutral-700"+ 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">- Convert to support ticket →+ <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>+ )}</div>);}diff --git a/apps/web/ui/support/code-block.tsx b/apps/web/ui/support/code-block.tsxnew file mode 100644index 0000000000..59e2acc9dd--- /dev/null+++ b/apps/web/ui/support/code-block.tsx@@ -0,0 +1,213 @@+"use client";++import { cn } from "@dub/utils";+import { Check, Copy, Download } from "@dub/ui/icons";+import {+ isValidElement,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";+import type { BundledLanguage, Highlighter } from "shiki";++let _highlighterPromise: Promise<Highlighter> | null = null;++function getHighlighter(): Promise<Highlighter> {+ if (!_highlighterPromise) {+ _highlighterPromise = import("shiki").then(({ createHighlighter }) =>+ createHighlighter({ themes: ["github-light"], langs: [] }),+ );+ }+ return _highlighterPromise;+}++async function highlightCode(+ code: string,+ lang: string,+): Promise<string | null> {+ try {+ const highlighter = await getHighlighter();+ const loaded = highlighter.getLoadedLanguages();+ if (lang && !loaded.includes(lang as BundledLanguage)) {+ try {+ await highlighter.loadLanguage(lang as BundledLanguage);+ } catch {+ return null;+ }+ }+ const html = highlighter.codeToHtml(code, {+ lang: lang || "text",+ theme: "github-light",+ });++ const start = html.indexOf("<code");+ const codeStart = html.indexOf(">", start) + 1;+ const codeEnd = html.lastIndexOf("</code>");+ if (start !== -1 && codeEnd !== -1) return html.slice(codeStart, codeEnd);+ return null;+ } catch {+ return null;+ }+}++const LANG_EXTENSIONS: Record<string, string> = {+ javascript: "js", js: "js",+ typescript: "ts", ts: "ts",+ tsx: "tsx", jsx: "jsx",+ python: "py", py: "py",+ bash: "sh", sh: "sh", shell: "sh", shellscript: "sh", zsh: "zsh",+ ruby: "rb", rb: "rb",+ go: "go", rust: "rs", rs: "rs",+ css: "css", scss: "scss", sass: "sass",+ html: "html", xml: "xml",+ json: "json", yaml: "yaml", yml: "yml",+ toml: "toml", sql: "sql",+ php: "php", java: "java", kotlin: "kt", swift: "swift",+ c: "c", cpp: "cpp", cs: "cs",+ markdown: "md", md: "md",+};++function CopyButton({ code }: { code: string }) {+ const [copied, setCopied] = useState(false);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(+ () => () => {+ if (timerRef.current) clearTimeout(timerRef.current);+ },+ [],+ );++ const handleCopy = useCallback(async () => {+ if (copied || !navigator?.clipboard?.writeText) return;+ await navigator.clipboard.writeText(code);+ setCopied(true);+ timerRef.current = setTimeout(() => setCopied(false), 2000);+ }, [code, copied]);++ return (+ <button+ type="button"+ onClick={handleCopy}+ className="rounded p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600"+ title={copied ? "Copied!" : "Copy code"}+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </button>+ );+}++function DownloadButton({+ code,+ language,+}: {+ code: string;+ language: string;+}) {+ const handleDownload = useCallback(() => {+ const trimmed = language?.trim().toLowerCase();+ const ext = (trimmed && (LANG_EXTENSIONS[trimmed] ?? trimmed)) || "txt";+ const blob = new Blob([code], { type: "text/plain" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `code.${ext}`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ }, [code, language]);++ return (+ <button+ type="button"+ onClick={handleDownload}+ className="rounded p-1 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600"+ title="Download file"+ >+ <Download className="size-3.5" />+ </button>+ );+}++export function CodeBlock({+ code,+ language,+}: {+ code: string;+ language: string;+}) {+ const trimmedCode = code.replace(/\n+$/, "");+ const [highlightedHtml, setHighlightedHtml] = useState<string | null>(null);++ useEffect(() => {+ if (!trimmedCode) return;+ highlightCode(trimmedCode, language).then(setHighlightedHtml);+ }, [trimmedCode, language]);++ return (+ <div className="my-2 overflow-hidden rounded-xl border border-neutral-200 text-sm">+ <div className="flex h-9 items-center justify-between border-b border-neutral-200 bg-neutral-50 px-3">+ <span className="font-mono text-xs lowercase text-neutral-400">+ {language || "code"}+ </span>+ <div className="flex items-center gap-0.5">+ <DownloadButton code={trimmedCode} language={language} />+ <CopyButton code={trimmedCode} />+ </div>+ </div>++ <div className="overflow-x-auto bg-white px-4 py-3">+ <pre className="m-0 bg-transparent font-mono text-[13px] leading-relaxed">+ {highlightedHtml ? (+ <code dangerouslySetInnerHTML={{ __html: highlightedHtml }} />+ ) : (+ <code className="text-neutral-700">{trimmedCode}</code>+ )}+ </pre>+ </div>+ </div>+ );+}++export function MarkdownCodeBlock({+ className,+ children,+ node: _node,+ "data-block": dataBlock,+}: React.HTMLAttributes<HTMLElement> & {+ node?: unknown;+ "data-block"?: string;+}) {+ if (!dataBlock) {+ return (+ <code+ className={cn(+ "rounded bg-neutral-100 px-1.5 py-0.5 font-mono text-[0.8em] text-neutral-700",+ className,+ )}+ >+ {children}+ </code>+ );+ }++ const langMatch = className?.match(/language-([^\s]+)/);+ const language = langMatch?.[1] ?? "";++ let code = "";+ if (+ isValidElement(children) &&+ children.props !== null &&+ typeof children.props === "object" &&+ "children" in children.props &&+ typeof (children.props as { children: unknown }).children === "string"+ ) {+ code = (children.props as { children: string }).children;+ } else if (typeof children === "string") {+ code = children;+ }++ return <CodeBlock code={code} language={language} />;+}diff --git a/apps/web/ui/support/embedded-chat.tsx b/apps/web/ui/support/embedded-chat.tsxindex 35bbb0dcc8..ce12e345e2 100644--- a/apps/web/ui/support/embedded-chat.tsx+++ b/apps/web/ui/support/embedded-chat.tsx@@ -1,31 +1,52 @@"use client";+import { Tooltip } from "@dub/ui";+import { Trash } from "@dub/ui/icons";+import { useState } from "react";import { ChatInterface } from "./chat-interface";-import { SupportChatContext } from "./types";-export function EmbeddedSupportChat({- context = "app",-}: {- context?: SupportChatContext;-}) {+export function EmbeddedSupportChat() {+ const [resetKey, setResetKey] = useState(0);+ const handleReset = () => setResetKey((k) => k + 1);+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 className="flex shrink-0 items-center justify-between border-b border-neutral-100 bg-neutral-50 px-5 py-4">+ <div className="flex items-center gap-3">+ <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>++ <Tooltip content="Clear chat">+ <button+ type="button"+ onClick={handleReset}+ className="flex size-8 items-center justify-center rounded-lg text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-700"+ aria-label="Clear chat"+ >+ <Trash className="size-4" />+ </button>+ </Tooltip></div>- <ChatInterface context={context} className="flex-1 px-1" embedded />+ <ChatInterface+ key={resetKey}+ onReset={handleReset}+ className="flex-1 px-1"+ embedded+ /></div>);}diff --git a/apps/web/ui/support/message.tsx b/apps/web/ui/support/message.tsxindex 5000ca1ab3..272c00c881 100644--- a/apps/web/ui/support/message.tsx+++ b/apps/web/ui/support/message.tsx@@ -10,7 +10,7 @@ export function SupportMessage({children,isUser = false,}: PropsWithChildren<{- avatar: string;+ avatar?: string;content?: string;animate?: boolean;isUser?: boolean;@@ -23,12 +23,14 @@ export function SupportMessage({animate && "animate-scale-in-fade",)}>- <img- src={avatar}- alt={`${name} avatar`}- className={cn("size-8 shrink-0 rounded-full", isUser && "mb-1")}- draggable={false}- />+ {avatar && (+ <img+ src={avatar}+ alt="avatar"+ className={cn("size-8 shrink-0 rounded-full", isUser && "mb-1")}+ draggable={false}+ />+ )}<divclassName={cn(@@ -51,7 +53,7 @@ export function SupportMessage({className={cn("text-sm",isUser &&- "rounded-2xl rounded-br bg-neutral-900 px-3 py-2 text-white",+ "rounded-2xl rounded-br bg-neutral-900 px-3 py-2 text-white",)}>{children}diff --git a/apps/web/ui/support/program-combobox.tsx b/apps/web/ui/support/program-combobox.tsxindex 182bed8905..fbff2c5467 100644--- a/apps/web/ui/support/program-combobox.tsx+++ b/apps/web/ui/support/program-combobox.tsx@@ -67,6 +67,7 @@ export function ProgramCombobox({placeholder={isReady ? "Select program" : ""}searchPlaceholder="Search programs..."matchTriggerWidth+ popoverProps={{ contentClassName: "w-[var(--radix-popover-trigger-width)]" }}open={open}onOpenChange={setOpen}buttonProps={{diff --git a/apps/web/ui/support/source-citations.tsx b/apps/web/ui/support/source-citations.tsxnew file mode 100644index 0000000000..65ccb73e9c--- /dev/null+++ b/apps/web/ui/support/source-citations.tsx@@ -0,0 +1,98 @@+"use client";++import { Book2Small } from "@dub/ui/icons";+import { useState } from "react";++export type SourceCitation = {+ url: string;+ heading: string;+ type: "docs" | "help";+};++export function SourceCitations({ sources }: { sources: SourceCitation[] }) {+ const [open, setOpen] = useState(false);++ if (!sources.length) return null;++ return (+ <div className="mt-4">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="flex items-center gap-1.5 text-xs font-medium text-blue-600 hover:text-blue-800"+ >+ <Book2Small className="size-3.5 shrink-0" />+ <span>+ Used {sources.length} source{sources.length > 1 ? "s" : ""}+ </span>+ <svg+ width="10"+ height="10"+ viewBox="0 0 10 10"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.75}+ strokeLinecap="round"+ strokeLinejoin="round"+ className={`transition-transform duration-150 ${open ? "rotate-180" : ""}`}+ >+ <path d="M2 3.5L5 6.5L8 3.5" />+ </svg>+ </button>++ {open && (+ <ul className="mt-1.5 space-y-1 pl-1">+ {sources.map((source) => (+ <li key={source.url}>+ <a+ href={source.url}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-1.5 text-xs text-neutral-500 underline decoration-dotted underline-offset-2 hover:text-neutral-700"+ >+ <span className="shrink-0 rounded border border-neutral-200 bg-neutral-100 px-1 py-px text-[10px] font-medium text-neutral-500">+ {source.type === "help" ? "Help" : "Docs"}+ </span>+ {source.heading}+ </a>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++export function extractSources(+ parts: { type: string;[key: string]: unknown }[],+): SourceCitation[] {+ const seen = new Set<string>();+ const sources: SourceCitation[] = [];+++ for (const part of parts) {+ if (part.type !== "tool-findRelevantDocs") continue;+ if ((part as any).state !== "output-available") continue;++ const output = (part as any).output;+ if (!Array.isArray(output)) continue;++ for (const r of output) {+ const meta = r?.metadata;+ if (typeof meta?.url !== "string" || typeof meta?.heading !== "string")+ continue;++ const baseUrl = meta.url.split("#")[0];+ if (seen.has(baseUrl)) continue;+ seen.add(baseUrl);++ sources.push({+ url: baseUrl,+ heading: meta.heading,+ type: meta.type ?? "docs",+ });+ }+ }++ return sources;+}diff --git a/apps/web/ui/support/status-indicator.tsx b/apps/web/ui/support/status-indicator.tsxnew file mode 100644index 0000000000..3b80f5b2fb--- /dev/null+++ b/apps/web/ui/support/status-indicator.tsx@@ -0,0 +1,21 @@+"use client";++import { cn } from "@dub/utils";++type StatusIndicatorProps = {+ label: string;+ className?: string;+};++export function StatusIndicator({ label, className }: StatusIndicatorProps) {+ return (+ <span+ className={cn(+ "animate-pulse text-xs text-neutral-400",+ className,+ )}+ >+ {label}+ </span>+ );+}diff --git a/apps/web/ui/support/workspace-combobox.tsx b/apps/web/ui/support/workspace-combobox.tsxindex 3e0022cd81..9647ee650f 100644--- a/apps/web/ui/support/workspace-combobox.tsx+++ b/apps/web/ui/support/workspace-combobox.tsx@@ -58,6 +58,7 @@ export function WorkspaceCombobox({placeholder={workspaces === undefined ? "" : "Select workspace"}searchPlaceholder="Search workspaces..."matchTriggerWidth+ popoverProps={{ contentClassName: "w-[var(--radix-popover-trigger-width)]" }}open={open}onOpenChange={setOpen}buttonProps={{