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.

Add image upload to AI support chat (#4330)

Pedro Ladeira875e1676c2a7
diff --git a/apps/web/app/api/ai/support-chat/route.ts b/apps/web/app/api/ai/support-chat/route.ts
index 492cb7fd49..467f8c8f15 100644
--- a/apps/web/app/api/ai/support-chat/route.ts
+++ b/apps/web/app/api/ai/support-chat/route.ts
@@ -12,9 +12,37 @@ import { withSession } from "@/lib/auth";
import { getSlackClient } from "@/lib/slack/client";
import { ratelimit } from "@/lib/upstash/ratelimit";
import { anthropic } from "@ai-sdk/anthropic";
-import { convertToModelMessages, stepCountIs, streamText, UIMessage } from "ai";
+import {
+ convertToModelMessages,
+ isFileUIPart,
+ stepCountIs,
+ streamText,
+ UIMessage,
+} from "ai";
+
+const ALLOWED_CHAT_IMAGE_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+]);
+const MAX_CHAT_IMAGES = 3;
+const MAX_DATA_URL_LENGTH = 1_400_000;
+const MAX_BODY_BYTES = MAX_CHAT_IMAGES * MAX_DATA_URL_LENGTH + 512 * 1024;
+
+function isAllowedChatImage(part: { mediaType: string; url: string }) {
+ const urlMediaType = /^data:([^;,]+)[;,]/.exec(part.url)?.[1];
+ return (
+ urlMediaType === part.mediaType &&
+ ALLOWED_CHAT_IMAGE_TYPES.has(part.mediaType)
+ );
+}
export const POST = withSession(async ({ req, session }) => {
+ const contentLength = Number(req.headers.get("content-length"));
+ if (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {
+ return new Response("Request too large", { status: 413 });
+ }
+
const body = await req.json();
const { messages, globalContext } = body as {
messages: UIMessage[];
@@ -25,6 +53,56 @@ export const POST = withSession(async ({ req, session }) => {
return new Response("Invalid messages", { status: 400 });
}
+ const lastUserIndex = messages.findLastIndex((msg) => msg.role === "user");
+ if (lastUserIndex === -1 || lastUserIndex !== messages.length - 1) {
+ return new Response("Invalid messages", { status: 400 });
+ }
+
+ const latestParts = Array.isArray(messages[lastUserIndex].parts)
+ ? messages[lastUserIndex].parts
+ : [];
+ const latestImages = latestParts
+ .filter(isFileUIPart)
+ .filter((part) => part.url?.startsWith("data:"));
+
+ if (latestImages.length > MAX_CHAT_IMAGES) {
+ return new Response("Too many images", { status: 400 });
+ }
+ for (const part of latestImages) {
+ if (!isAllowedChatImage(part)) {
+ return new Response("Invalid image type", { status: 400 });
+ }
+ if (part.url.length > MAX_DATA_URL_LENGTH) {
+ return new Response("Image too large", { status: 400 });
+ }
+ }
+
+ const modelMessages = messages.map((msg, index) => {
+ const parts = Array.isArray(msg.parts) ? msg.parts : [];
+ const nextParts: UIMessage["parts"] = [];
+
+ for (const part of parts) {
+ if (!isFileUIPart(part)) {
+ nextParts.push(part);
+ continue;
+ }
+
+ if (index === lastUserIndex) {
+ if (isAllowedChatImage(part)) {
+ nextParts.push(part);
+ }
+ continue;
+ }
+
+ nextParts.push({
+ type: "text",
+ text: `Attached image: ${part.filename || "image"}`,
+ });
+ }
+
+ return { ...msg, parts: nextParts };
+ });
+
const MAX_ATTACHMENTS = 5;
const MAX_ATTACHMENT_ID_LENGTH = 128;
const rawAttachmentIds = body.attachmentIds;
@@ -68,9 +146,6 @@ export const POST = withSession(async ({ req, session }) => {
let slackThreadTs = incomingSlackThreadTs;
let slackUserPostPromise: Promise<string | undefined> | undefined;
- const latestParts = Array.isArray(messages[messages.length - 1].parts)
- ? messages[messages.length - 1].parts
- : [];
const latestUserText = latestParts
.filter(
(p): p is { type: "text"; text: string } =>
@@ -80,9 +155,15 @@ export const POST = withSession(async ({ req, session }) => {
typeof p.text === "string",
)
.map((p) => p.text)
- .join("\n\n");
+ .join("\n\n")
+ .trim();
+ const imageNote =
+ latestImages.length > 0
+ ? `(${latestImages.length} image${latestImages.length === 1 ? "" : "s"} attached)`
+ : "";
const userLabel = session.user.name || session.user.email || "Unknown user";
- const safeUserText = escapeSlackMrkdwn(latestUserText);
+ const slackUserBody = [latestUserText, imageNote].filter(Boolean).join(" ");
+ const safeUserText = escapeSlackMrkdwn(slackUserBody);
const safeUserLabel = escapeSlackMrkdwn(userLabel);
const safeUserEmail = escapeSlackMrkdwn(session.user.email);
@@ -111,7 +192,7 @@ export const POST = withSession(async ({ req, session }) => {
const result = streamText({
model: anthropic("claude-sonnet-4-6"),
system: buildSystemPrompt(globalContext),
- messages: await convertToModelMessages(messages),
+ messages: await convertToModelMessages(modelMessages),
stopWhen: stepCountIs(5),
tools: {
findRelevantDocs: findRelevantDocsTool,
diff --git a/apps/web/lib/ai/build-system-prompt.ts b/apps/web/lib/ai/build-system-prompt.ts
index 623fc5d6ef..3aa53f73b2 100644
--- a/apps/web/lib/ai/build-system-prompt.ts
+++ b/apps/web/lib/ai/build-system-prompt.ts
@@ -25,6 +25,7 @@ const CONTEXT_SYSTEM_PROMPTS: Record<SupportChatContext, string> = {
const BASE_SYSTEM_PROMPT = `
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.
+ If the user attached images, inspect them first. You may skip findRelevantDocs only when the question is purely about what is shown in the screenshot (error UI, unexpected screen). Still call findRelevantDocs for how-to or product questions.
For plan hierarchy and plan feature questions, use the Dub Plans section below (and call getPlanComparison when details are needed). Do not infer plan order from plan names.
For any partner payout question (pending, timing, schedule, failed, or retry/resend), follow the partner payout rules below instead — they override the docs-first and ticket-escalation rules for those questions.
For partner profile country change requests, follow the partner profile country rules below instead — they override the docs-first rules for those questions.
diff --git a/apps/web/lib/ai/create-support-ticket.ts b/apps/web/lib/ai/create-support-ticket.ts
index 17f3ed6fc6..419b6d7200 100644
--- a/apps/web/lib/ai/create-support-ticket.ts
+++ b/apps/web/lib/ai/create-support-ticket.ts
@@ -36,7 +36,13 @@ export function createSupportTicketTool(options: CreateSupportTicketOptions) {
.filter((p) => p.type === "text")
.map((p) => (p as { type: "text"; text: string }).text)
.join("");
- return `${msg.role === "user" ? "User" : "Dub Support"}: ${text}`;
+ const imageCount = msg.parts.filter((p) => p.type === "file").length;
+ const imageNote =
+ imageCount > 0
+ ? `(${imageCount} image${imageCount === 1 ? "" : "s"} attached)`
+ : "";
+ const body = [text, imageNote].filter(Boolean).join(" ");
+ return `${msg.role === "user" ? "User" : "Dub Support"}: ${body}`;
})
.join("\n\n");
diff --git a/apps/web/ui/support/chat-interface.tsx b/apps/web/ui/support/chat-interface.tsx
index 0aed6c19f0..346663ff15 100644
--- a/apps/web/ui/support/chat-interface.tsx
+++ b/apps/web/ui/support/chat-interface.tsx
@@ -4,17 +4,23 @@ 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 { OfficeBuilding, PaperPlane, Users2, Xmark } from "@dub/ui/icons";
import { cn, fetcher, OG_AVATAR_URL } from "@dub/utils";
-import { DefaultChatTransport } from "ai";
+import { DefaultChatTransport, isFileUIPart, UIMessage } from "ai";
+import { Paperclip } from "lucide-react";
import { useSession } from "next-auth/react";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, 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 { MarkdownCodeBlock } from "./code-block";
+import {
+ compressChatImage,
+ isChatImageFile,
+ MAX_CHAT_IMAGES,
+} from "./compress-chat-image";
import { SupportMessage } from "./message";
import { ProgramCombobox, ProgramSummary } from "./program-combobox";
import { extractSources, SourceCitations } from "./source-citations";
@@ -25,6 +31,36 @@ import { WorkspaceCombobox, WorkspaceSummary } from "./workspace-combobox";
type AccountType = "workspace" | "partner";
+type PendingImage = {
+ id: string;
+ file: File;
+ previewUrl: string;
+};
+
+function blankFilePartUrls<
+ M extends { parts?: Array<{ type: string; url?: string }> },
+>(messages: M[]): M[] {
+ return messages.map((message) => ({
+ ...message,
+ parts: message.parts?.map((part) =>
+ part.type === "file" ? { ...part, url: "" } : part,
+ ),
+ }));
+}
+
+function stripHistoricalFileUrls(messages: UIMessage[]): UIMessage[] {
+ const lastUserIndex = messages.findLastIndex((msg) => msg.role === "user");
+ return messages.map((message, index) => {
+ if (index === lastUserIndex || !message.parts) return message;
+ return {
+ ...message,
+ parts: message.parts.map((part) =>
+ part.type === "file" ? { ...part, url: "" } : part,
+ ),
+ };
+ });
+}
+
export function ChatInterface({
className,
embedded,
@@ -37,7 +73,14 @@ export function ChatInterface({
const { data: session, status: sessionStatus } = useSession();
const scrollContainerRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const pendingImagesRef = useRef<PendingImage[]>([]);
+ const pendingSendRef = useRef<PendingImage[] | null>(null);
+ const sendingRef = useRef(false);
const [input, setInput] = useState("");
+ const [pendingImages, setPendingImages] = useState<PendingImage[]>([]);
+ const [isDragging, setIsDragging] = useState(false);
+ const [isCompressing, setIsCompressing] = useState(false);
const [ticketSubmitted, setTicketSubmitted] = useState(false);
const [selection, setSelection] = useState<GlobalChatContext>({});
@@ -71,8 +114,24 @@ export function ChatInterface({
const { messages, sendMessage, status, setMessages } = useChat({
transport: new DefaultChatTransport({
api: "/api/ai/support-chat",
+ prepareSendMessagesRequest: ({
+ id,
+ messages: nextMessages,
+ body,
+ trigger,
+ messageId,
+ }) => ({
+ body: {
+ ...body,
+ id,
+ messages: stripHistoricalFileUrls(nextMessages),
+ trigger,
+ messageId,
+ },
+ }),
}),
onError: (err) => {
+ sendingRef.current = false;
toast.error(err.message || "Something went wrong. Please try again.");
},
});
@@ -87,10 +146,43 @@ export function ChatInterface({
}, [messages, status, embedded]);
useEffect(() => {
- if (status === "ready") {
- textareaRef.current?.focus();
+ if (status === "error") {
+ sendingRef.current = false;
+ if (pendingSendRef.current?.length) {
+ setMessages((current) => {
+ if (current.length === 0) return current;
+ const last = current[current.length - 1];
+ return last.role === "user" ? current.slice(0, -1) : current;
+ });
+ pendingSendRef.current = null;
+ }
+ return;
}
- }, [status]);
+
+ if (status !== "ready") return;
+
+ sendingRef.current = false;
+
+ if (pendingSendRef.current?.length) {
+ pendingSendRef.current.forEach((image) =>
+ URL.revokeObjectURL(image.previewUrl),
+ );
+ pendingSendRef.current = null;
+ setPendingImages([]);
+ }
+
+ setMessages((current) => {
+ const needsStrip = current.some((message) =>
+ message.parts?.some(
+ (part) => part.type === "file" && "url" in part && part.url,
+ ),
+ );
+ if (!needsStrip) return current;
+ return blankFilePartUrls(current);
+ });
+
+ textareaRef.current?.focus();
+ }, [status, setMessages]);
useEffect(() => {
if (!storageKey || restoredRef.current) return;
@@ -128,7 +220,11 @@ export function ChatInterface({
const stored = raw ? JSON.parse(raw) : {};
localStorage.setItem(
storageKey,
- JSON.stringify({ ...stored, messages, ticketSubmitted }),
+ JSON.stringify({
+ ...stored,
+ messages: blankFilePartUrls(messages),
+ ticketSubmitted,
+ }),
);
} catch {}
}, [messages, ticketSubmitted, status, storageKey]);
@@ -141,6 +237,52 @@ export function ChatInterface({
}
};
+ pendingImagesRef.current = pendingImages;
+
+ useEffect(() => {
+ return () => {
+ pendingImagesRef.current.forEach((image) =>
+ URL.revokeObjectURL(image.previewUrl),
+ );
+ };
+ }, []);
+
+ const addFiles = useCallback(
+ (incoming: File[]) => {
+ if (isCompressing || sendingRef.current) return;
+
+ const supported = incoming.filter(isChatImageFile);
+ const rejected = incoming.length - supported.length;
+
+ if (rejected > 0) {
+ toast.error("Please attach a PNG, JPEG, or WebP image.");
+ }
+
+ if (supported.length === 0) return;
+
+ setPendingImages((prev) => {
+ const remaining = MAX_CHAT_IMAGES - prev.length;
+ if (remaining <= 0) {
+ toast.error(`You can attach up to ${MAX_CHAT_IMAGES} images.`);
+ return prev;
+ }
+
+ const next = supported.slice(0, remaining).map((file) => ({
+ id: `${file.name}-${file.size}-${Date.now()}-${Math.random()}`,
+ file,
+ previewUrl: URL.createObjectURL(file),
+ }));
+
+ if (supported.length > remaining) {
+ toast.error(`You can attach up to ${MAX_CHAT_IMAGES} images.`);
+ }
+
+ return [...prev, ...next];
+ });
+ },
+ [isCompressing],
+ );
+
const getSlackThreadTs = () => {
for (let i = messages.length - 1; i >= 0; i--) {
const meta = (messages[i] as any).metadata as
@@ -151,25 +293,73 @@ export function ChatInterface({
return undefined;
};
- const handleSend = (text?: string) => {
- const messageText = text ?? input;
- if (!messageText.trim() || status === "streaming" || !canChat) return;
- sendMessage(
- { text: messageText },
- {
- body: {
- globalContext: {
- ...selection,
- chatLocation:
- effectiveAccountType === "partner" ? "partners" : "app",
- accountType: effectiveAccountType,
- },
- slackThreadTs: getSlackThreadTs(),
- },
+ const handleSend = async (text?: string) => {
+ const messageText = (text ?? input).trim();
+ const imagesToSend = pendingImages;
+ if (
+ (!messageText && imagesToSend.length === 0) ||
+ status === "streaming" ||
+ status === "submitted" ||
+ isCompressing ||
+ sendingRef.current ||
+ !canChat
+ ) {
+ return;
+ }
+
+ sendingRef.current = true;
+
+ const requestBody = {
+ globalContext: {
+ ...selection,
+ chatLocation: effectiveAccountType === "partner" ? "partners" : "app",
+ accountType: effectiveAccountType,
},
- );
- setInput("");
- textareaRef.current?.focus();
+ slackThreadTs: getSlackThreadTs(),
+ };
+
+ if (imagesToSend.length === 0) {
+ sendMessage({ text: messageText }, { body: requestBody });
+ setInput("");
+ textareaRef.current?.focus();
+ return;
+ }
+
+ setIsCompressing(true);
+ try {
+ const files = await Promise.all(
+ imagesToSend.map(async (image) => {
+ const compressed = await compressChatImage(image.file);
+ return {
+ type: "file" as const,
+ filename: compressed.filename,
+ mediaType: compressed.mediaType,
+ url: compressed.dataUrl,
+ };
+ }),
+ );
+
+ pendingSendRef.current = imagesToSend;
+
+ if (messageText) {
+ sendMessage({ text: messageText, files }, { body: requestBody });
+ } else {
+ sendMessage({ files }, { body: requestBody });
+ }
+
+ setInput("");
+ textareaRef.current?.focus();
+ } catch (err) {
+ sendingRef.current = false;
+ pendingSendRef.current = null;
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : "Could not process image. Try a different PNG or JPEG.",
+ );
+ } finally {
+ setIsCompressing(false);
+ }
};
const handleEscalateViaForm = (
@@ -425,16 +615,44 @@ export function ChatInterface({
const textContent = message.parts
.filter((p) => p.type === "text")
.map((p) => (p as { type: "text"; text: string }).text)
- .join("\n\n");
- if (!textContent) return null;
+ .join("\n\n")
+ .trim();
+ const fileParts = message.parts.filter(isFileUIPart);
+ if (!textContent && fileParts.length === 0) return null;
return (
<SupportMessage
key={message.id}
avatar={userAvatar}
isUser
animate
+ media={
+ fileParts.length > 0 ? (
+ <div className="flex flex-wrap justify-end gap-1.5">
+ {fileParts.map((part, partIndex) =>
+ part.url ? (
+ <img
+ key={partIndex}
+ src={part.url}
+ alt={part.filename ?? "Attached image"}
+ className="max-h-32 max-w-[200px] rounded-lg object-cover"
+ draggable={false}
+ />
+ ) : (
+ <div
+ key={partIndex}
+ className="rounded-lg bg-neutral-200 px-2 py-1 text-xs text-neutral-500"
+ >
+ Image attached
+ </div>
+ ),
+ )}
+ </div>
+ ) : undefined
+ }
>
- <p className="text-sm">{textContent}</p>
+ {textContent ? (
+ <p className="text-sm">{textContent}</p>
+ ) : null}
</SupportMessage>
);
}
@@ -589,53 +807,171 @@ export function ChatInterface({
</div>
) : hasRequestedTicket ? null : (
<div className="shrink-0 border-t border-neutral-100 bg-white p-3">
- <div className="relative">
- <TextareaAutosize
- ref={textareaRef}
- 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.shiftKey) {
+ <div
+ onDragOver={(e) => {
+ if (!canChat || isCompressing) return;
+ e.preventDefault();
+ setIsDragging(true);
+ }}
+ onDragLeave={(e) => {
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
+ setIsDragging(false);
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ setIsDragging(false);
+ if (!canChat) return;
+ addFiles(Array.from(e.dataTransfer.files));
+ }}
+ >
+ {pendingImages.length > 0 && (
+ <div className="mb-2 flex flex-wrap gap-2">
+ {pendingImages.map((image) => (
+ <div key={image.id} className="relative size-16 shrink-0">
+ <img
+ src={image.previewUrl}
+ alt={image.file.name}
+ className="size-full rounded-lg object-cover"
+ />
+ <button
+ type="button"
+ onClick={() => {
+ setPendingImages((prev) => {
+ const entry = prev.find(
+ (item) => item.id === image.id,
+ );
+ if (entry) URL.revokeObjectURL(entry.previewUrl);
+ return prev.filter((item) => item.id !== image.id);
+ });
+ }}
+ disabled={
+ isCompressing ||
+ status === "streaming" ||
+ status === "submitted"
+ }
+ aria-label="Remove image"
+ className="absolute -right-1.5 -top-1.5 flex size-5 items-center justify-center rounded-full bg-neutral-900 text-white transition-colors hover:bg-neutral-700 disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ <Xmark className="size-2.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="relative">
+ <TextareaAutosize
+ ref={textareaRef}
+ minRows={3}
+ maxRows={6}
+ placeholder={
+ isDragging
+ ? "Drop image to attach..."
+ : !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" ||
+ isCompressing
+ }
+ onChange={(e) => setInput(e.target.value)}
+ onPaste={(e) => {
+ const fromFiles = Array.from(
+ e.clipboardData?.files ?? [],
+ ).filter(isChatImageFile);
+ const fromItems =
+ fromFiles.length > 0
+ ? []
+ : Array.from(e.clipboardData?.items ?? [])
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter(
+ (file): file is File =>
+ !!file && isChatImageFile(file),
+ );
+ const imageFiles =
+ fromFiles.length > 0 ? fromFiles : fromItems;
+ if (imageFiles.length === 0) return;
e.preventDefault();
- handleSend();
+ addFiles(imageFiles);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSend();
+ }
+ }}
+ className={cn(
+ "w-full resize-none rounded-xl border py-2.5 pl-3 pr-24 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors",
+ "focus:outline-none disabled:cursor-not-allowed disabled:bg-neutral-50 disabled:opacity-60",
+ isDragging
+ ? "border-dashed border-neutral-400 bg-neutral-50 shadow-none focus:border-neutral-400 focus:ring-0"
+ : "border-neutral-200 focus:border-neutral-400 focus:ring-2 focus:ring-neutral-200",
+ )}
+ />
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ multiple
+ className="hidden"
+ onChange={(e) => {
+ addFiles(Array.from(e.target.files ?? []));
+ e.target.value = "";
+ }}
+ />
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={
+ !canChat ||
+ status === "streaming" ||
+ status === "submitted" ||
+ isCompressing ||
+ pendingImages.length >= MAX_CHAT_IMAGES
}
- }}
- 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>
+ className={cn(
+ "absolute bottom-4 right-12 flex size-8 items-center justify-center rounded-full transition-all",
+ canChat &&
+ status === "ready" &&
+ !isCompressing &&
+ pendingImages.length < MAX_CHAT_IMAGES
+ ? "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-800"
+ : "cursor-not-allowed text-neutral-300",
+ )}
+ aria-label="Attach image"
+ >
+ <Paperclip className="size-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => handleSend()}
+ disabled={
+ !canChat ||
+ status === "streaming" ||
+ status === "submitted" ||
+ isCompressing ||
+ (!input.trim() && pendingImages.length === 0)
+ }
+ className={cn(
+ "absolute bottom-4 right-3 flex size-8 items-center justify-center rounded-full transition-all",
+ canChat &&
+ status === "ready" &&
+ !isCompressing &&
+ (input.trim() || pendingImages.length > 0)
+ ? "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>
<div className="mt-px flex flex-col items-center gap-1">
diff --git a/apps/web/ui/support/compress-chat-image.ts b/apps/web/ui/support/compress-chat-image.ts
new file mode 100644
index 0000000000..3e7a20b025
--- /dev/null
+++ b/apps/web/ui/support/compress-chat-image.ts
@@ -0,0 +1,111 @@
+const CHAT_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
+
+export const MAX_CHAT_IMAGES = 3;
+
+const MAX_LONG_EDGE = 1568;
+const TARGET_MAX_BYTES = 400 * 1024;
+const MAX_DATA_URL_LENGTH = 1_400_000;
+const JPEG_QUALITIES = [0.8, 0.6, 0.4];
+
+export function isChatImageFile(file: File) {
+ return CHAT_IMAGE_TYPES.has(file.type);
+}
+
+export async function compressChatImage(file: File) {
+ if (!isChatImageFile(file)) {
+ throw new Error("Please attach a PNG, JPEG, or WebP image.");
+ }
+
+ const img = await new Promise<HTMLImageElement>((resolve, reject) => {
+ const url = URL.createObjectURL(file);
+ const image = new Image();
+ image.onload = () => {
+ URL.revokeObjectURL(url);
+ resolve(image);
+ };
+ image.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error("Could not decode image. Try PNG or JPEG."));
+ };
+ image.src = url;
+ });
+
+ const needsResize = Math.max(img.width, img.height) > MAX_LONG_EDGE;
+ const needsCompress = file.size > TARGET_MAX_BYTES;
+
+ if (!needsResize && !needsCompress) {
+ const dataUrl = await blobToDataUrl(file);
+ assertDataUrlFits(dataUrl);
+ return {
+ filename: file.name || "screenshot.png",
+ mediaType: file.type,
+ dataUrl,
+ };
+ }
+
+ const scale = Math.min(1, MAX_LONG_EDGE / Math.max(img.width, img.height));
+ const width = Math.max(1, Math.round(img.width * scale));
+ const height = Math.max(1, Math.round(img.height * scale));
+
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ throw new Error("Could not process image. Try a different PNG or JPEG.");
+ }
+
+ ctx.drawImage(img, 0, 0, width, height);
+
+ let blob: Blob | undefined;
+ for (const quality of JPEG_QUALITIES) {
+ blob = await canvasToJpegBlob(canvas, quality);
+ if (blob.size <= TARGET_MAX_BYTES) break;
+ }
+
+ if (!blob) {
+ throw new Error("Could not process image. Try a different PNG or JPEG.");
+ }
+
+ const base = file.name.replace(/\.[^.]+$/, "") || "screenshot";
+ const dataUrl = await blobToDataUrl(blob);
+ assertDataUrlFits(dataUrl);
+
+ return {
+ filename: `${base}.jpg`,
+ mediaType: "image/jpeg",
+ dataUrl,
+ };
+}
+
+function canvasToJpegBlob(canvas: HTMLCanvasElement, quality: number) {
+ return new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (result) => {
+ if (result) resolve(result);
+ else
+ reject(
+ new Error("Could not process image. Try a different PNG or JPEG."),
+ );
+ },
+ "image/jpeg",
+ quality,
+ );
+ });
+}
+
+function assertDataUrlFits(dataUrl: string) {
+ if (dataUrl.length > MAX_DATA_URL_LENGTH) {
+ throw new Error("Image too large. Try a smaller screenshot.");
+ }
+}
+
+function blobToDataUrl(blob: Blob) {
+ return new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(new Error("Failed to read image"));
+ reader.readAsDataURL(blob);
+ });
+}
diff --git a/apps/web/ui/support/message.tsx b/apps/web/ui/support/message.tsx
index a5e8341b8a..43371fb580 100644
--- a/apps/web/ui/support/message.tsx
+++ b/apps/web/ui/support/message.tsx
@@ -1,19 +1,21 @@
"use client";
import { cn } from "@dub/utils";
-import { PropsWithChildren } from "react";
+import { PropsWithChildren, ReactNode } from "react";
export function SupportMessage({
avatar,
content,
animate = false,
children,
+ media,
isUser = false,
}: PropsWithChildren<{
avatar?: string;
content?: string;
animate?: boolean;
isUser?: boolean;
+ media?: ReactNode;
}>) {
return (
<div
@@ -35,9 +37,10 @@ export function SupportMessage({
<div
className={cn(
"max-w-[85%] grow py-1",
- isUser && "flex flex-col items-end",
+ isUser && "flex flex-col items-end gap-1.5",
)}
>
+ {media}
{content && (
<p
className={cn(