Email for professionals and teams
feat(mail): conversation threading, Cc/Bcc recipients, and reply-all
Oday Bakkoura73017ef6940
diff --git a/CLAUDE.md b/CLAUDE.mdindex 50dfa09..5864745 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -44,7 +44,9 @@ It also re-exports `RealtimeHub`, which is why that class must live outside theInbound: `email` handler → R2 → queue → `processInboundMessage` (`src/lib/email/inbound.ts`) → `resolveInboundAddress` routing decision (deliver / reject / forward) → `parseRawMime` (postal-mime) → insert message + attachments → upsert contacts → `dispatchWebhooks` → `notifyUsersOfNewMessage` over the Durable Object.-Outbound: `src/lib/email/send.ts` / `sender.ts`, composing with mimetext and sending through the `EMAIL` send_email binding, with `outbound_jobs` rows tracking queued sends.+Outbound: `src/lib/email/send.ts` / `sender.ts`, composing with mimetext and sending through the `EMAIL` send_email binding, with `outbound_jobs` rows tracking queued sends. `to`, `cc` and `bcc` accept a header string or an array; `toAddr`/`ccAddr`/`bccAddr` on `messages` store the full comma-joined lists (use `splitEmailAddressList` from `src/lib/email/address.ts`, not `getEmailAddress`, when a value may be a list).++Threading: `resolveThreadId` in `src/lib/email/threading.ts` files an inbound or imported message under the thread of the stored message its `In-Reply-To`/`References` name (matched against `providerMessageId` in the same mailbox); otherwise its own Message-ID seeds a new thread. Outbound replies carry `inReplyTo`/`references`/`threadId` from the draft, and a fresh send is keyed by the Message-ID Cloudflare returns. `/api/messages/[id]/thread` returns the conversation.### Routing rules have two scopesdiff --git a/docs/api.md b/docs/api.mdindex aa1e689..76aa3d2 100644--- a/docs/api.md+++ b/docs/api.md@@ -18,12 +18,14 @@ The hostname must be the apex of a zone available to the configured Cloudflare c## Sending email-Send email through `POST /api/v1/send`. Attachments are optional and use Base64-encoded content:+Send email through `POST /api/v1/send`. `to`, `cc` and `bcc` accept either a comma-separated header string or an array of addresses; each entry may carry a display name (`"Maya Chen" <[email protected]>`). A message can reach up to 50 recipients across the three fields. Attachments are optional and use Base64-encoded content:```json{"from": "[email protected]",- "to": "[email protected]",+ "to": ["[email protected]", "\"Maya Chen\" <[email protected]>"],+ "cc": "[email protected]",+ "bcc": ["[email protected]"],"subject": "Report","text": "Attached.","attachments": [@@ -36,6 +38,21 @@ Send email through `POST /api/v1/send`. Attachments are optional and use Base64-}```+To send a reply that threads correctly in the recipient's client, pass the parent's Message-ID as `inReplyTo` and its chain as `references` (a header string or an array). Mailflare writes the `In-Reply-To` and `References` headers, files the sent copy in the same conversation, and stores `threadId`, `inReplyTo` and `references` on every message.++```json+{+ "from": "[email protected]",+ "to": "[email protected]",+ "subject": "Re: Report",+ "text": "Thanks, received.",+ "inReplyTo": "<[email protected]>",+ "references": ["<[email protected]>", "<[email protected]>"]+}+```++`GET /api/messages/{id}/thread` (session auth) returns every stored message in the same conversation, oldest first, excluding drafts and trash.+The dashboard composer accepts up to 10 attachments, with a 10 MB limit per file and a 20 MB combined limit. Attachment metadata is stored in D1 and file content is stored in R2. Downloads require access to the mailbox containing the message.## Real-time updatesdiff --git a/drizzle/migrations/0025_add_threading_and_cc_bcc.sql b/drizzle/migrations/0025_add_threading_and_cc_bcc.sqlnew file mode 100644index 0000000..9db3415--- /dev/null+++ b/drizzle/migrations/0025_add_threading_and_cc_bcc.sql@@ -0,0 +1,7 @@+-- Conversation threading and Cc/Bcc recipients.+ALTER TABLE `messages` ADD `cc_addr` text;--> statement-breakpoint+ALTER TABLE `messages` ADD `bcc_addr` text;--> statement-breakpoint+ALTER TABLE `messages` ADD `in_reply_to` text;--> statement-breakpoint+ALTER TABLE `messages` ADD `references_header` text;--> statement-breakpoint+CREATE INDEX `messages_thread_idx` ON `messages` (`mailbox_id`,`thread_id`);--> statement-breakpoint+CREATE INDEX `messages_provider_message_idx` ON `messages` (`mailbox_id`,`provider_message_id`);diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.jsonindex 683fc7e..e01418b 100644--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@ -176,6 +176,13 @@"when": 1788604800001,"tag": "0024_add_advanced_routing_and_webhook_retries","breakpoints": true+ },+ {+ "idx": 25,+ "version": "6",+ "when": 1788691200000,+ "tag": "0025_add_threading_and_cc_bcc",+ "breakpoints": true}]}diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsxindex 425816d..07367e1 100644--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx@@ -14,7 +14,10 @@ import { MessageAttachmentCard } from "@/components/message-attachment-card";import { MessageDetailSkeleton } from "@/components/page-skeletons";import { usePageLoading } from "@/components/page-loading";import { PreviousMessage } from "@/components/previous-message";+import { ConversationThread } from "@/components/messages/conversation-thread";+import { useMessageThread } from "@/components/messages/use-message-thread";import { getMessageBackHref } from "@/components/message-actions/utils";+import { getEmailAddress, getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address";import type { MessageAttachment, MessageDetailResponse } from "./types";import {fetchMessageDetail,@@ -22,6 +25,7 @@ import {getCachedMessageDetailForDisplay,getMessageBodyDisplay,getMessageHeaderParties,+ getOwnAddressForMessage,resolveInlineAttachmentUrls,} from "./utils";import { extractCloudAttachments } from "./cloud-attachment-utils";@@ -29,13 +33,14 @@ import { sanitizeEmailHtml } from "./email-html-sanitizer";export default function MessageDetailPage() {const params = useParams<{ messageId: string }>();- const { selectedMailbox } = useSelectedMailbox();+ const { selectedMailbox, mailboxes } = useSelectedMailbox();const messageId = params.messageId;const [data, setData] = useState<MessageDetailResponse | null>(null);const [loading, setLoading] = useState(true);const [previewAttachment, setPreviewAttachment] =useState<MessageAttachment | null>(null);usePageLoading(loading);+ const thread = useMessageThread(messageId, data?.message?.threadId);useEffect(() => {let cancelled = false;@@ -81,14 +86,23 @@ export default function MessageDetailPage() {}const { message, body, attachments = [] } = data;+ const messageMailbox =+ mailboxes.find((mailbox) => mailbox.id === message.mailboxId) ?? selectedMailbox;const currentAccountName =- selectedMailbox?.displayName ?? selectedMailbox?.localPart;+ messageMailbox?.displayName ?? messageMailbox?.localPart;const { fromName, fromAddress, toName } = getMessageHeaderParties(message,currentAccountName,);- const ownAddress =- message.direction === "inbound" ? message.toAddr : message.fromAddr;+ const ownAddresses = messageMailbox+ ? messageMailbox.senderAddresses?.length+ ? messageMailbox.senderAddresses+ : [`${messageMailbox.localPart}@${messageMailbox.hostname}`]+ : [];+ const ownAddress = getOwnAddressForMessage(message, ownAddresses);+ const toEntries = splitEmailAddressList(message.toAddr);+ const ccEntries = splitEmailAddressList(message.ccAddr);+ const bccEntries = splitEmailAddressList(message.bccAddr);const bodyDisplay = getMessageBodyDisplay(body?.textBody,body?.htmlBody,@@ -128,8 +142,17 @@ export default function MessageDetailPage() {subject={message.subject}bodyText={body?.textBody}ownAddress={ownAddress}+ ownAddresses={ownAddresses}+ message={message}/></div>+ <ConversationThread+ currentMessageId={message.id}+ position="before"+ messages={thread.messages}+ mailboxId={message.mailboxId}+ currentAccountName={currentAccountName}+ /><article className="px-6 py-4"><h1 className="text-2xl text-neutral-900 mb-4">{message.subject ?? "(no subject)"}@@ -153,16 +176,26 @@ export default function MessageDetailPage() {</p><p className="text-xs text-neutral-500">to{" "}- {message.direction === "outbound" ? (- <ContactDetailsTrigger+ {message.direction === "inbound" && toEntries.length <= 1 ? (+ toName+ ) : (+ <RecipientList+ entries={toEntries}mailboxId={message.mailboxId}- address={message.toAddr}- name={toName}+ firstName={message.direction === "outbound" ? toName : undefined}/>- ) : (- toName)}</p>+ {ccEntries.length > 0 && (+ <p className="text-xs text-neutral-500">+ cc <RecipientList entries={ccEntries} mailboxId={message.mailboxId} />+ </p>+ )}+ {bccEntries.length > 0 && (+ <p className="text-xs text-neutral-500">+ bcc <RecipientList entries={bccEntries} mailboxId={message.mailboxId} />+ </p>+ )}</div><p className="text-xs text-neutral-400">{dayjs(message.createdAt).format("MMM DD, YYYY, hh:mmA")}@@ -230,6 +263,13 @@ export default function MessageDetailPage() {</section>)}</article>+ <ConversationThread+ currentMessageId={message.id}+ position="after"+ messages={thread.messages}+ mailboxId={message.mailboxId}+ currentAccountName={currentAccountName}+ /><MessageAttachmentViewerattachment={previewAttachment}messageId={message.id}@@ -241,3 +281,30 @@ export default function MessageDetailPage() {</div>);}++function RecipientList({+ entries,+ mailboxId,+ firstName,+}: {+ entries: string[];+ mailboxId: string | null;+ /** A contact name already resolved for the first entry, when the caller has one. */+ firstName?: string;+}) {+ if (entries.length === 0) return <>—</>;+ return (+ <>+ {entries.map((entry, index) => (+ <span key={entry} title={getEmailAddress(entry)}>+ {index > 0 && ", "}+ <ContactDetailsTrigger+ mailboxId={mailboxId}+ address={entry}+ name={index === 0 && firstName ? firstName : getEmailDisplayName(entry)}+ />+ </span>+ ))}+ </>+ );+}diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.tsindex 8a7dff7..862c6d4 100644--- a/src/app/(dashboard)/inbox/[messageId]/utils.ts+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts@@ -1,6 +1,6 @@import { authFetch } from "@/lib/auth/client";import { fetchCachedMessageDetail, getCachedMessageDetail } from "@/lib/messages/detail-cache";-import { getEmailAddress } from "@/lib/email/address";+import { getEmailAddress, getEmailAddressList, normalizeEmailAddress } from "@/lib/email/address";import { getDisplayNameForAddress } from "@/lib/contacts/utils";import { htmlToReadableText, splitRepliedEmailContent } from "@/lib/email/reply-content-utils";import type { Message } from "@/hooks/types";@@ -32,6 +32,18 @@ export function getMessageHeaderParties(message: Message, currentAccountName?: s};}+/**+ * The mailbox address this message reached, used as the reply sender and to+ * tell "sent" from "received" in quoted history. With several recipients the+ * mailbox's own address is whichever of them it can send as.+ */+export function getOwnAddressForMessage(message: Message, ownAddresses: string[]): string {+ if (message.direction === "outbound") return getEmailAddress(message.fromAddr);+ const own = new Set(ownAddresses.map((address) => normalizeEmailAddress(address)));+ const listed = [...getEmailAddressList(message.toAddr), ...getEmailAddressList(message.ccAddr)];+ return listed.find((address) => own.has(address)) ?? ownAddresses[0] ?? getEmailAddress(message.toAddr);+}+export function getMessageBodyDisplay(textBody: string | null | undefined,htmlBody: string | null | undefined,diff --git a/src/app/api/drafts/[id]/route.ts b/src/app/api/drafts/[id]/route.tsindex 8f8daa0..b1730dd 100644--- a/src/app/api/drafts/[id]/route.ts+++ b/src/app/api/drafts/[id]/route.ts@@ -55,6 +55,8 @@ export async function PATCH(request: Request, { params }: DraftRouteParams) {mailboxId: sender.mailboxId,fromAddr: sender.fromAddr,toAddr: input.to ?? "",+ ccAddr: input.cc || null,+ bccAddr: input.bcc || null,subject: input.subject ?? null,snippet: buildSnippet(text || null, html || null),textBody: text || null,diff --git a/src/app/api/drafts/[id]/utils.ts b/src/app/api/drafts/[id]/utils.tsindex 820971a..97c341a 100644--- a/src/app/api/drafts/[id]/utils.ts+++ b/src/app/api/drafts/[id]/utils.ts@@ -12,7 +12,12 @@ export function selectDraftWithBody(db: Db, userId: string, draftId: string) {mailboxId: messages.mailboxId,fromAddr: messages.fromAddr,toAddr: messages.toAddr,+ ccAddr: messages.ccAddr,+ bccAddr: messages.bccAddr,subject: messages.subject,+ inReplyTo: messages.inReplyTo,+ references: messages.references,+ threadId: messages.threadId,status: messages.status,textBody: messages.textBody,htmlBody: messages.htmlBody,diff --git a/src/app/api/drafts/route.ts b/src/app/api/drafts/route.tsindex 3c781fa..7c1f5b3 100644--- a/src/app/api/drafts/route.ts+++ b/src/app/api/drafts/route.ts@@ -60,12 +60,17 @@ export async function POST(request: Request) {direction: "outbound",fromAddr: sender.fromAddr,toAddr: input.to ?? "",+ ccAddr: input.cc || null,+ bccAddr: input.bcc || null,subject: input.subject ?? null,snippet: buildSnippet(text || null, html || null),textBody: text || null,htmlBody: html || null,status: "draft",read: true,+ inReplyTo: input.inReplyTo || null,+ references: input.references || null,+ threadId: input.threadId || null,});return NextResponse.json({ draft: { id: draftId } });diff --git a/src/app/api/drafts/types.d.ts b/src/app/api/drafts/types.d.tsindex cb49356..4bbf9ab 100644--- a/src/app/api/drafts/types.d.ts+++ b/src/app/api/drafts/types.d.ts@@ -2,7 +2,13 @@ export type DraftPayload = {mailboxId?: string | null;from?: string;to?: string;+ cc?: string;+ bcc?: string;subject?: string;text?: string;html?: string;+ /** Set when the draft is a reply, so the send carries the threading headers. */+ inReplyTo?: string | null;+ references?: string | null;+ threadId?: string | null;};diff --git a/src/app/api/messages/[messageId]/thread/route.ts b/src/app/api/messages/[messageId]/thread/route.tsnew file mode 100644index 0000000..65c83df--- /dev/null+++ b/src/app/api/messages/[messageId]/thread/route.ts@@ -0,0 +1,25 @@+import { NextResponse } from "next/server";+import { getCurrentUser } from "@/lib/auth/cookies";+import { getEnv } from "@/lib/cloudflare";+import { getMessageThreadForUser } from "@/lib/email/thread-view";++type MessageRouteParams = {+ params: Promise<{ messageId: string }>;+};++/** Every message in the same conversation as `messageId`, oldest first, with bodies. */+export async function GET(request: Request, { params }: MessageRouteParams) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { messageId } = await params;+ const data = await getMessageThreadForUser(env, user, messageId);+ if (!data) {+ return NextResponse.json({ error: "Not found" }, { status: 404 });+ }++ return NextResponse.json(data);+}diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.tsindex 13bd1e6..3df4d35 100644--- a/src/app/api/messages/route.ts+++ b/src/app/api/messages/route.ts@@ -1,12 +1,12 @@import { NextResponse } from "next/server";-import { eq, desc, and, like, or, count, isNull, inArray, lte, gt } from "drizzle-orm";+import { eq, desc, and, like, or, count, isNull, isNotNull, inArray, lte, gt, notInArray } from "drizzle-orm";import type { SQL } from "drizzle-orm";import { getEnv } from "@/lib/cloudflare";import { getCurrentUser } from "@/lib/auth/cookies";import { getDb } from "@/db";import { messages } from "@/db/schema";import { getContactDisplayNameMap } from "@/lib/contacts/service";-import { normalizeEmailAddress } from "@/lib/email/address";+import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";import { buildSnippet } from "@/lib/email/parse";import { getMailboxAccessLevel, listAccessibleMailboxes } from "@/lib/mailboxes/access";@@ -98,6 +98,25 @@ export async function GET(request: Request) {.orderBy(desc(messages.createdAt)).limit(limit).offset(offset);+ // Conversation sizes for the rows on this page, so the list can show "(3)"+ // next to a subject the way threaded clients do.+ const threadIds = Array.from(new Set(rows.map((row) => row.threadId).filter((id): id is string => !!id)));+ const threadCounts = new Map<string, number>();+ if (threadIds.length > 0) {+ const scope = mailboxId+ ? eq(messages.mailboxId, mailboxId)+ : accessibleMailboxIds.length > 0+ ? inArray(messages.mailboxId, accessibleMailboxIds)+ : eq(messages.userId, user.id);+ const countRows = await db+ .select({ threadId: messages.threadId, total: count() })+ .from(messages)+ .where(and(scope, inArray(messages.threadId, threadIds), isNotNull(messages.threadId), notInArray(messages.status, ["draft", "trash"])))+ .groupBy(messages.threadId);+ for (const row of countRows) {+ if (row.threadId) threadCounts.set(row.threadId, row.total);+ }+ }const mailboxNameMap = new Map(accessibleMailboxes.map((mailbox) => [mailbox.id,@@ -113,7 +132,7 @@ export async function GET(request: Request) {userId,rows.filter((message) => message.userId === userId)- .flatMap((message) => [message.fromAddr, message.toAddr]),+ .flatMap((message) => [message.fromAddr, getFirstEmailAddressEntry(message.toAddr)]),),] as const),),@@ -128,7 +147,8 @@ export async function GET(request: Request) {(message.direction === "outbound" ? accountName : null) ??contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??null,- toContactName: contactMap?.get(normalizeEmailAddress(message.toAddr)) ?? null,+ toContactName: contactMap?.get(normalizeEmailAddress(getFirstEmailAddressEntry(message.toAddr))) ?? null,+ threadCount: message.threadId ? threadCounts.get(message.threadId) ?? 1 : 1,};});diff --git a/src/app/api/send/types.d.ts b/src/app/api/send/types.d.tsindex 437d388..6b7ea24 100644--- a/src/app/api/send/types.d.ts+++ b/src/app/api/send/types.d.ts@@ -8,4 +8,9 @@ export interface SendRequestPayload {subject: string;text?: string;to: string;+ cc?: string;+ bcc?: string;+ inReplyTo?: string;+ references?: string;+ threadId?: string;}diff --git a/src/app/api/send/utils.ts b/src/app/api/send/utils.tsindex cafb92b..dc09007 100644--- a/src/app/api/send/utils.ts+++ b/src/app/api/send/utils.ts@@ -29,6 +29,11 @@ export async function parseSendRequest(request: Request): Promise<SendRequestPayreturn {from: String(form.get("from") ?? ""),to: String(form.get("to") ?? ""),+ cc: getOptionalFormValue(form, "cc"),+ bcc: getOptionalFormValue(form, "bcc"),+ inReplyTo: getOptionalFormValue(form, "inReplyTo"),+ references: getOptionalFormValue(form, "references"),+ threadId: getOptionalFormValue(form, "threadId"),subject: String(form.get("subject") ?? ""),text: getOptionalFormValue(form, "text"),html: getOptionalFormValue(form, "html"),diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsxindex 1d5cf88..f2eab4c 100644--- a/src/components/compose/compose-form.tsx+++ b/src/components/compose/compose-form.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { FileText, Minimize2, Paperclip, Send, X } from "lucide-react";+import { FileText, Minimize2, Paperclip, Reply, Send, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -12,7 +12,9 @@ import { authFetch } from "@/lib/auth/client";import { formatEmailAddress, getEmailAddress } from "@/lib/email/address";import { cn } from "@/lib/utils";import { applyMailboxSignature, buildSendFormData, fetchDraft, formatAttachmentSize } from "./utils";-import type { ComposeAttachment } from "./types";+import { RecipientInput } from "./recipient-input";+import { headerToRecipients, isValidRecipient, recipientsToHeader } from "./recipient-utils";+import type { ComposeAttachment, ComposeThreading } from "./types";type Toast = { type: "success" | "error"; message: string } | null;@@ -27,7 +29,12 @@ export function ComposeForm({}) {const { selectedMailbox, setSelectedMailbox, mailboxes } = useSelectedMailbox();const [draftId, setDraftId] = useState<string | null>(null);- const [to, setTo] = useState("");+ const [to, setTo] = useState<string[]>([]);+ const [cc, setCc] = useState<string[]>([]);+ const [bcc, setBcc] = useState<string[]>([]);+ const [showCc, setShowCc] = useState(false);+ const [showBcc, setShowBcc] = useState(false);+ const [threading, setThreading] = useState<ComposeThreading | null>(null);const [subject, setSubject] = useState("");const [text, setText] = useState("");const [attachments, setAttachments] = useState<ComposeAttachment[]>([]);@@ -88,7 +95,22 @@ export function ComposeForm({if (cancelled) return;setDraftId(draft.id);- setTo(draft.toAddr);+ setTo(headerToRecipients(draft.toAddr));+ const draftCc = headerToRecipients(draft.ccAddr);+ const draftBcc = headerToRecipients(draft.bccAddr);+ setCc(draftCc);+ setBcc(draftBcc);+ setShowCc(draftCc.length > 0);+ setShowBcc(draftBcc.length > 0);+ setThreading(+ draft.inReplyTo || draft.threadId+ ? {+ inReplyTo: draft.inReplyTo ?? null,+ references: draft.references ?? null,+ threadId: draft.threadId ?? null,+ }+ : null,+ );setSubject(draft.subject ?? "");setText(draft.textBody ?? "");setLoadedDraftMailboxId(draft.mailboxId);@@ -131,7 +153,7 @@ export function ComposeForm({useEffect(() => {const bodyContent = text.trim();const signatureOnly = bodyContent === (selectedMailbox?.signature?.trim() ?? "");- const hasContent = to.trim() || subject.trim() || (bodyContent && !signatureOnly);+ const hasContent = to.length > 0 || cc.length > 0 || bcc.length > 0 || subject.trim() || (bodyContent && !signatureOnly);if (!fromAddr || !hasContent || loadingDraft) return;if (saveTimer.current) clearTimeout(saveTimer.current);@@ -139,9 +161,14 @@ export function ComposeForm({const payload = {mailboxId: selectedMailbox?.id,from: fromAddr,- to,+ to: recipientsToHeader(to),+ cc: recipientsToHeader(cc),+ bcc: recipientsToHeader(bcc),subject,text,+ inReplyTo: threading?.inReplyTo ?? null,+ references: threading?.references ?? null,+ threadId: threading?.threadId ?? null,};const res = await authFetch(draftId ? `/api/drafts/${draftId}` : "/api/drafts", {method: draftId ? "PATCH" : "POST",@@ -155,20 +182,32 @@ export function ComposeForm({return () => {if (saveTimer.current) clearTimeout(saveTimer.current);};- }, [draftId, fromAddr, loadingDraft, selectedMailbox?.id, selectedMailbox?.signature, subject, text, to]);+ }, [bcc, cc, draftId, fromAddr, loadingDraft, selectedMailbox?.id, selectedMailbox?.signature, subject, text, threading, to]);async function onSubmit(event: React.FormEvent<HTMLFormElement>) {event.preventDefault();+ if (to.length === 0) {+ setToast({ type: "error", message: "Add at least one recipient" });+ return;+ }+ const invalid = [...to, ...cc, ...bcc].find((entry) => !isValidRecipient(entry));+ if (invalid) {+ setToast({ type: "error", message: `"${invalid}" is not a valid email address` });+ return;+ }setLoading(true);const res = await authFetch("/api/send", {method: "POST",body: buildSendFormData({attachments,from: fromAddr,- to,+ to: recipientsToHeader(to),+ cc: recipientsToHeader(cc),+ bcc: recipientsToHeader(bcc),subject,text,mailboxId: selectedMailbox?.id,+ threading: threading ?? undefined,}),});const data = (await res.json()) as { messageId?: string; error?: string };@@ -185,7 +224,12 @@ export function ComposeForm({});}setDraftId(null);- setTo("");+ setTo([]);+ setCc([]);+ setBcc([]);+ setShowCc(false);+ setShowBcc(false);+ setThreading(null);setSubject("");setText(applyMailboxSignature("", "", selectedMailbox?.signature));setAttachments([]);@@ -248,7 +292,10 @@ export function ComposeForm({)}<form onSubmit={onSubmit} className={frameClass}><div className="flex h-9 items-center justify-between bg-neutral-800 px-4 text-sm font-medium text-white">- <span>{loadingDraft ? "Loading draft" : draftId ? "Draft saved" : "New Message"}</span>+ <span className="flex items-center gap-2">+ {threading?.inReplyTo && <Reply className="h-3.5 w-3.5 text-neutral-300" />}+ {loadingDraft ? "Loading draft" : threading?.inReplyTo ? "Reply" : draftId ? "Draft saved" : "New Message"}+ </span>{mode === "popup" && (<div className="flex items-center gap-3 text-neutral-300"><Minimize2 className="h-4 w-4" />@@ -275,19 +322,51 @@ export function ComposeForm({))}</Select></div>- <div className="border-b border-neutral-100 px-4 py-1">- <Label htmlFor={`${mode}-to`} className="sr-only">To</Label>- <Input- id={`${mode}-to`}- value={to}- onChange={(event) => setTo(event.target.value)}- type="text"- placeholder='Recipients, or "Maya Chen" <[email protected]>'- required+ <RecipientInput+ id={`${mode}-to`}+ label="To"+ value={to}+ onChange={setTo}+ placeholder='Recipients, or "Maya Chen" <[email protected]>'+ required+ disabled={loadingDraft}+ trailing={+ <>+ {!showCc && (+ <button type="button" className="rounded px-1 hover:text-neutral-800" onClick={() => setShowCc(true)}>+ Cc+ </button>+ )}+ {!showBcc && (+ <button type="button" className="rounded px-1 hover:text-neutral-800" onClick={() => setShowBcc(true)}>+ Bcc+ </button>+ )}+ </>+ }+ />+ {showCc && (+ <RecipientInput+ id={`${mode}-cc`}+ label="Cc"+ value={cc}+ onChange={setCc}+ placeholder="Carbon copy"disabled={loadingDraft}- className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"+ autoFocus={!loadingDraft && cc.length === 0}/>- </div>+ )}+ {showBcc && (+ <RecipientInput+ id={`${mode}-bcc`}+ label="Bcc"+ value={bcc}+ onChange={setBcc}+ placeholder="Blind carbon copy, hidden from other recipients"+ disabled={loadingDraft}+ autoFocus={!loadingDraft && bcc.length === 0}+ />+ )}<div className="border-b border-neutral-100 px-4 py-1"><Label htmlFor={`${mode}-subject`} className="sr-only">Subject</Label><Inputdiff --git a/src/components/compose/recipient-input-types.d.ts b/src/components/compose/recipient-input-types.d.tsnew file mode 100644index 0000000..f7486ba--- /dev/null+++ b/src/components/compose/recipient-input-types.d.ts@@ -0,0 +1,13 @@+export type RecipientInputProps = {+ id: string;+ label: string;+ value: string[];+ onChange: (next: string[]) => void;+ placeholder?: string;+ disabled?: boolean;+ required?: boolean;+ /** Focus the field when it first appears, e.g. after the Cc/Bcc toggle reveals it. */+ autoFocus?: boolean;+ /** Rendered at the right edge of the row, e.g. the Cc/Bcc toggles. */+ trailing?: React.ReactNode;+};diff --git a/src/components/compose/recipient-input.tsx b/src/components/compose/recipient-input.tsxnew file mode 100644index 0000000..cbf997a--- /dev/null+++ b/src/components/compose/recipient-input.tsx@@ -0,0 +1,126 @@+"use client";++import { useRef, useState } from "react";+import type { KeyboardEvent } from "react";+import { X } from "lucide-react";+import { Label } from "@/components/ui/label";+import { getEmailAddress } from "@/lib/email/address";+import { cn } from "@/lib/utils";+import type { RecipientInputProps } from "./recipient-input-types";+import { getRecipientLabel, isValidRecipient, parseRecipientEntries } from "./recipient-utils";++/**+ * A To/Cc/Bcc row. Addresses become chips as soon as the user types a comma,+ * presses Enter or Tab, pastes a list, or leaves the field; Backspace on an+ * empty field pulls the last chip back out for editing.+ */+export function RecipientInput({+ id,+ label,+ value,+ onChange,+ placeholder,+ disabled,+ required,+ autoFocus,+ trailing,+}: RecipientInputProps) {+ const [draft, setDraft] = useState("");+ const inputRef = useRef<HTMLInputElement | null>(null);++ function commit(raw = draft) {+ const entries = parseRecipientEntries(raw, value);+ if (entries.length > 0) onChange([...value, ...entries]);+ setDraft("");+ }++ function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {+ if (event.key === "," || event.key === ";" || event.key === "Enter" || (event.key === "Tab" && draft.trim())) {+ if (event.key !== "Tab") event.preventDefault();+ commit();+ return;+ }+ if (event.key === "Backspace" && !draft && value.length > 0) {+ event.preventDefault();+ const last = value[value.length - 1];+ onChange(value.slice(0, -1));+ setDraft(last);+ }+ }++ return (+ <div+ className="flex min-h-9 items-center gap-2 border-b border-neutral-100 px-4 py-1"+ onClick={() => inputRef.current?.focus()}+ >+ <Label htmlFor={id} className="w-8 shrink-0 text-sm text-neutral-500">+ {label}+ </Label>+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">+ {value.map((entry) => {+ const valid = isValidRecipient(entry);+ return (+ <span+ key={entry}+ title={getEmailAddress(entry)}+ className={cn(+ "inline-flex max-w-full items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs",+ valid+ ? "border-neutral-200 bg-neutral-50 text-neutral-800"+ : "border-red-200 bg-red-50 text-red-700",+ )}+ >+ <span className="truncate">{getRecipientLabel(entry)}</span>+ {!disabled && (+ <button+ type="button"+ aria-label={`Remove ${getEmailAddress(entry)}`}+ className="rounded-full p-0.5 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700"+ onClick={(event) => {+ event.stopPropagation();+ onChange(value.filter((item) => item !== entry));+ }}+ >+ <X className="h-3 w-3" />+ </button>+ )}+ </span>+ );+ })}+ <input+ ref={inputRef}+ id={id}+ value={draft}+ onChange={(event) => {+ // A pasted list should split immediately instead of waiting for a comma.+ if (/[,;]/.test(event.target.value) && event.target.value.length - draft.length > 1) {+ commit(event.target.value);+ return;+ }+ setDraft(event.target.value);+ }}+ onKeyDown={onKeyDown}+ onBlur={() => commit()}+ type="text"+ autoComplete="off"+ autoFocus={autoFocus}+ spellCheck={false}+ placeholder={value.length === 0 ? placeholder : undefined}+ disabled={disabled}+ // Native `required` would block submit while chips exist; the form checks itself.+ aria-required={required}+ className="h-7 min-w-32 flex-1 border-0 bg-transparent p-0 text-sm outline-none placeholder:text-neutral-400 disabled:cursor-not-allowed"+ />+ </div>+ {trailing && (+ // Toggles live inside the clickable row; keep their clicks from refocusing this field.+ <div+ className="flex shrink-0 items-center gap-1 text-xs text-neutral-500"+ onClick={(event) => event.stopPropagation()}+ >+ {trailing}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/compose/recipient-utils.ts b/src/components/compose/recipient-utils.tsnew file mode 100644index 0000000..394c239--- /dev/null+++ b/src/components/compose/recipient-utils.ts@@ -0,0 +1,34 @@+import { getEmailAddress, joinEmailAddressList, parseEmailAddressParts, splitEmailAddressList } from "@/lib/email/address";++const EMAIL_RE = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/;++export function isValidRecipient(entry: string): boolean {+ return EMAIL_RE.test(getEmailAddress(entry).trim());+}++/** Turn raw typed text into recipient entries, deduplicated by bare address. */+export function parseRecipientEntries(value: string, existing: string[] = []): string[] {+ const seen = new Set(existing.map((entry) => getEmailAddress(entry).toLowerCase()));+ const result: string[] = [];+ for (const entry of splitEmailAddressList(value)) {+ const key = getEmailAddress(entry).toLowerCase();+ if (!key || seen.has(key)) continue;+ seen.add(key);+ result.push(entry);+ }+ return result;+}++export function recipientsToHeader(entries: string[]): string {+ return joinEmailAddressList(entries);+}++export function headerToRecipients(value: string | null | undefined): string[] {+ return parseRecipientEntries(value ?? "");+}++/** Short label for a chip: the display name if there is one, else the address. */+export function getRecipientLabel(entry: string): string {+ const parts = parseEmailAddressParts(entry);+ return parts.name && parts.name !== parts.address ? parts.name : parts.address;+}diff --git a/src/components/compose/types.d.ts b/src/components/compose/types.d.tsindex 2c4c088..e8c03f8 100644--- a/src/components/compose/types.d.ts+++ b/src/components/compose/types.d.ts@@ -3,9 +3,21 @@ export type ComposeDraft = {mailboxId: string | null;fromAddr: string;toAddr: string;+ ccAddr?: string | null;+ bccAddr?: string | null;subject: string | null;textBody: string | null;htmlBody: string | null;+ inReplyTo?: string | null;+ references?: string | null;+ threadId?: string | null;+};++/** Headers a reply draft carries so the sent message joins its conversation. */+export type ComposeThreading = {+ inReplyTo: string | null;+ references: string | null;+ threadId: string | null;};export type DraftResponse = {diff --git a/src/components/compose/utils.ts b/src/components/compose/utils.tsindex a3f4587..47fec37 100644--- a/src/components/compose/utils.ts+++ b/src/components/compose/utils.ts@@ -1,5 +1,5 @@import { authFetch } from "@/lib/auth/client";-import type { ComposeAttachment, ComposeDraft, DraftResponse } from "./types";+import type { ComposeAttachment, ComposeDraft, ComposeThreading, DraftResponse } from "./types";export async function fetchDraft(draftId: string): Promise<ComposeDraft> {const res = await authFetch(`/api/drafts/${draftId}`);@@ -19,13 +19,21 @@ export function buildSendFormData(input: {subject: string;text: string;to: string;+ cc?: string;+ bcc?: string;+ threading?: ComposeThreading;}): FormData {const form = new FormData();form.set("from", input.from);form.set("to", input.to);+ if (input.cc) form.set("cc", input.cc);+ if (input.bcc) form.set("bcc", input.bcc);form.set("subject", input.subject);form.set("text", input.text);if (input.mailboxId) form.set("mailboxId", input.mailboxId);+ if (input.threading?.inReplyTo) form.set("inReplyTo", input.threading.inReplyTo);+ if (input.threading?.references) form.set("references", input.threading.references);+ if (input.threading?.threadId) form.set("threadId", input.threading.threadId);for (const attachment of input.attachments) {form.append("attachments", attachment.file);}diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsxindex f594fda..48f7523 100644--- a/src/components/message-actions/message-actions.tsx+++ b/src/components/message-actions/message-actions.tsx@@ -2,12 +2,12 @@import { createElement, useState } from "react";import { useRouter } from "next/navigation";-import { Archive, Ban, BellOff, Mail, MailOpen, MoreVertical, Reply, ShieldAlert, Trash2 } from "lucide-react";+import { Archive, Ban, BellOff, Mail, MailOpen, MoreVertical, Reply, ReplyAll, ShieldAlert, Trash2 } from "lucide-react";import { useCompose } from "@/components/compose/compose-context";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import type { BulkMessageAction } from "@/app/api/messages/bulk/types";-import type { MessageActionsProps } from "./types";+import type { MessageActionsProps, ReplyMode } from "./types";import {confirmTrashWithoutUnsubscribe,blockMessageContact,@@ -15,6 +15,9 @@ import {createTrashSenderRule,getMessageActionRedirect,getMoveMessageActions,+ getReplyRecipients,+ getReplyThreading,+ hasAdditionalRecipients,openUnsubscribeUrl,runSingleMessageAction,} from "./utils";@@ -30,11 +33,13 @@ export function MessageActions({subject,bodyText,ownAddress,+ ownAddresses = [],+ message,}: MessageActionsProps) {const router = useRouter();const { openDraftComposer } = useCompose();const [pendingAction, setPendingAction] = useState<- BulkMessageAction | "unsubscribe" | "reply" | "block" | null+ BulkMessageAction | "unsubscribe" | ReplyMode | "block" | null>(null);const [error, setError] = useState<string | null>(null);const [moreOpen, setMoreOpen] = useState(false);@@ -80,8 +85,19 @@ export function MessageActions({}}- async function handleReply() {- setPendingAction("reply");+ const replyable = message ?? {+ direction,+ fromAddr: senderAddress,+ toAddr: "",+ ccAddr: null,+ providerMessageId: null,+ references: null,+ threadId: null,+ };+ const canReplyAll = hasAdditionalRecipients(replyable, ownAddresses);++ async function handleReply(mode: ReplyMode) {+ setPendingAction(mode);setError(null);try {const draftId = await createReplyDraft({@@ -90,6 +106,8 @@ export function MessageActions({ownAddress,subject,bodyText,+ recipients: getReplyRecipients(replyable, ownAddresses, mode),+ threading: getReplyThreading(replyable),});openDraftComposer(draftId);} catch (replyError) {@@ -135,11 +153,25 @@ export function MessageActions({size="sm"aria-label="Reply"disabled={disabled}- onClick={handleReply}+ onClick={() => handleReply("reply")}><Reply className="h-5 w-5" /></Button></Tooltip>+ {canReplyAll && (+ <Tooltip label="Reply all">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ aria-label="Reply all"+ disabled={disabled}+ onClick={() => handleReply("replyAll")}+ >+ <ReplyAll className="h-5 w-5" />+ </Button>+ </Tooltip>+ )}<Tooltip label="Archive"><Buttonvariant="ghost"diff --git a/src/components/message-actions/types.d.ts b/src/components/message-actions/types.d.tsindex cf886d9..92e439d 100644--- a/src/components/message-actions/types.d.ts+++ b/src/components/message-actions/types.d.ts@@ -1,5 +1,5 @@import type { BulkMessageAction } from "@/app/api/messages/bulk/types";-import type { MessageDirection } from "@/hooks/types";+import type { Message, MessageDirection } from "@/hooks/types";import { IconNode } from "lucide-react";export type MessageActionsProps = {@@ -13,9 +13,25 @@ export type MessageActionsProps = {subject?: string | null;bodyText?: string | null;ownAddress?: string | null;+ /** Every address the mailbox can send as; used to drop "me" from reply-all. */+ ownAddresses?: string[];+ /** Recipient and threading headers of the message being acted on. */+ message?: ReplyableMessage;};-export type SingleMessageAction = BulkMessageAction | "reply";+export type SingleMessageAction = BulkMessageAction | "reply" | "replyAll";++export type ReplyMode = "reply" | "replyAll";++export type ReplyableMessage = Pick<+ Message,+ "direction" | "fromAddr" | "toAddr" | "ccAddr" | "providerMessageId" | "references" | "threadId"+>;++export type ReplyRecipients = {+ to: string[];+ cc: string[];+};export type ReplyDraftInput = {mailboxId: string | null;@@ -23,6 +39,12 @@ export type ReplyDraftInput = {ownAddress?: string | null;subject?: string | null;bodyText?: string | null;+ recipients: ReplyRecipients;+ threading?: {+ inReplyTo: string | null;+ references: string | null;+ threadId: string | null;+ };};export type TrashSenderRuleInput = {diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.tsindex 85fb4ce..a3241fd 100644--- a/src/components/message-actions/utils.ts+++ b/src/components/message-actions/utils.ts@@ -1,11 +1,14 @@import type { BulkMessageAction } from "@/app/api/messages/bulk/types";import { authFetch } from "@/lib/auth/client";-import { getEmailAddress } from "@/lib/email/address";+import { getEmailAddress, normalizeEmailAddress, splitEmailAddressList } from "@/lib/email/address";import { getLatestEmailContent } from "@/lib/email/reply-content-utils";import type {BlockMessageContactInput,MoveMessageActionItem,+ ReplyableMessage,ReplyDraftInput,+ ReplyMode,+ ReplyRecipients,TrashSenderRuleInput,} from "./types";import {@@ -140,15 +143,71 @@ export function buildReplyQuote(return `\n\n${getEmailAddress(senderAddress)} wrote:\n${quoted}\n`;}+/**+ * Who a reply goes to. A plain reply answers the sender; reply-all also keeps+ * everyone else on the To and Cc lines, minus the mailbox's own addresses so+ * the author is not mailing themselves. Replying to a sent message re-addresses+ * its original recipients.+ */+export function getReplyRecipients(+ message: ReplyableMessage,+ ownAddresses: string[],+ mode: ReplyMode,+): ReplyRecipients {+ const own = new Set(ownAddresses.map((address) => normalizeEmailAddress(address)));+ const seen = new Set<string>();+ const unique = (entries: string[]) =>+ entries.filter((entry) => {+ const key = normalizeEmailAddress(entry);+ if (!key || own.has(key) || seen.has(key)) return false;+ seen.add(key);+ return true;+ });++ if (message.direction === "outbound") {+ const to = unique(splitEmailAddressList(message.toAddr));+ const cc = mode === "replyAll" ? unique(splitEmailAddressList(message.ccAddr)) : [];+ return { to, cc };+ }++ const to = unique([message.fromAddr]);+ if (mode !== "replyAll") return { to, cc: [] };+ const cc = unique([...splitEmailAddressList(message.toAddr), ...splitEmailAddressList(message.ccAddr)]);+ return { to, cc };+}++/** Reply-all is only worth offering when it would reach someone a plain reply would not. */+export function hasAdditionalRecipients(message: ReplyableMessage, ownAddresses: string[]): boolean {+ const all = getReplyRecipients(message, ownAddresses, "replyAll");+ const single = getReplyRecipients(message, ownAddresses, "reply");+ return all.to.length + all.cc.length > single.to.length + single.cc.length;+}++/** The threading headers a reply must carry so both sides file it in the same conversation. */+export function getReplyThreading(message: ReplyableMessage) {+ const parentId = (message.providerMessageId ?? "").trim().replace(/^<|>$/g, "") || null;+ const chain = (message.references ?? "")+ .split(/\s+/)+ .map((id) => id.replace(/^<|>$/g, ""))+ .filter(Boolean);+ if (parentId && !chain.includes(parentId)) chain.push(parentId);+ return {+ inReplyTo: parentId,+ references: chain.length ? chain.join(" ") : null,+ threadId: message.threadId ?? parentId,+ };+}+export async function createReplyDraft({mailboxId,senderAddress,ownAddress,subject,bodyText,+ recipients,+ threading,}: ReplyDraftInput) {- const to = getEmailAddress(senderAddress).trim();- if (!to) throw new Error("Sender address is required");+ if (recipients.to.length === 0) throw new Error("Sender address is required");const response = await authFetch("/api/drafts", {method: "POST",@@ -157,9 +216,11 @@ export async function createReplyDraft({mailboxId,// The API rejects the draft unless `from` matches the mailbox address.from: getEmailAddress(ownAddress ?? ""),- to,+ to: recipients.to.join(", "),+ cc: recipients.cc.join(", "),subject: buildReplySubject(subject),text: buildReplyQuote(senderAddress, bodyText),+ ...threading,}),});const data = (await response.json()) as {diff --git a/src/components/messages/conversation-thread-types.d.ts b/src/components/messages/conversation-thread-types.d.tsnew file mode 100644index 0000000..2808620--- /dev/null+++ b/src/components/messages/conversation-thread-types.d.ts@@ -0,0 +1,23 @@+import type { ThreadMessage } from "@/hooks/types";++export type ConversationThreadProps = {+ /** The message the reader is currently viewing; it is rendered by the page, not here. */+ currentMessageId: string;+ /** Which side of the current message to render. */+ position: "before" | "after";+ messages: ThreadMessage[];+ mailboxId: string | null;+ currentAccountName?: string;+};++export type ConversationMessageCardProps = {+ message: ThreadMessage;+ mailboxId: string | null;+ currentAccountName?: string;+ defaultExpanded?: boolean;+};++export type UseMessageThreadResult = {+ messages: ThreadMessage[];+ loading: boolean;+};diff --git a/src/components/messages/conversation-thread-utils.ts b/src/components/messages/conversation-thread-utils.tsnew file mode 100644index 0000000..2f1e0bd--- /dev/null+++ b/src/components/messages/conversation-thread-utils.ts@@ -0,0 +1,33 @@+import { getEmailAddress, getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address";+import type { ThreadMessage } from "@/hooks/types";++/** Messages on one side of the current one, in chronological order. */+export function partitionThread(+ messages: ThreadMessage[],+ currentMessageId: string,+ position: "before" | "after",+): ThreadMessage[] {+ const index = messages.findIndex((message) => message.id === currentMessageId);+ if (index < 0) return position === "before" ? messages : [];+ return position === "before" ? messages.slice(0, index) : messages.slice(index + 1);+}++export function getConversationSender(message: ThreadMessage, currentAccountName?: string): string {+ if (message.direction === "outbound") return currentAccountName ?? getEmailDisplayName(message.fromAddr);+ return message.fromContactName ?? getEmailDisplayName(message.fromAddr);+}++/** "to Maya, Sam" style summary for a collapsed card. */+export function getConversationRecipients(message: ThreadMessage): string {+ const names = [...splitEmailAddressList(message.toAddr), ...splitEmailAddressList(message.ccAddr)].map(+ (entry) => getEmailDisplayName(entry),+ );+ if (names.length === 0) return "";+ if (names.length <= 3) return names.join(", ");+ return `${names.slice(0, 3).join(", ")}, +${names.length - 3}`;+}++export function getAvatarInitial(message: ThreadMessage, currentAccountName?: string): string {+ const name = getConversationSender(message, currentAccountName) || getEmailAddress(message.fromAddr);+ return name.trim().charAt(0).toUpperCase() || "?";+}diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsxnew file mode 100644index 0000000..d103628--- /dev/null+++ b/src/components/messages/conversation-thread.tsx@@ -0,0 +1,160 @@+"use client";++import Link from "next/link";+import { useState } from "react";+import dayjs from "dayjs";+import { ChevronDown, Paperclip, Reply } from "lucide-react";+import { ContactDetailsTrigger } from "@/components/contacts/contact-details";+import { getMessageBackHref } from "@/components/message-actions/utils";+import { sanitizeEmailHtml } from "@/app/(dashboard)/inbox/[messageId]/email-html-sanitizer";+import { getMessageBodyDisplay, resolveInlineAttachmentUrls } from "@/app/(dashboard)/inbox/[messageId]/utils";+import { getEmailAddress } from "@/lib/email/address";+import { cn } from "@/lib/utils";+import type { ConversationMessageCardProps, ConversationThreadProps } from "./conversation-thread-types";+import {+ getAvatarInitial,+ getConversationRecipients,+ getConversationSender,+ partitionThread,+} from "./conversation-thread-utils";++/**+ * The other messages in a conversation, collapsed to one line each and expanded+ * in place on click, so a reader can follow a whole exchange without leaving the+ * message they opened.+ */+export function ConversationThread({+ currentMessageId,+ position,+ messages,+ mailboxId,+ currentAccountName,+}: ConversationThreadProps) {+ const slice = partitionThread(messages, currentMessageId, position);+ if (slice.length === 0) return null;++ return (+ <section+ aria-label={position === "before" ? "Earlier messages in this conversation" : "Later messages in this conversation"}+ className={cn("px-6", position === "before" ? "pt-4" : "pb-6")}+ >+ {position === "before" && (+ <p className="mb-2 text-xs font-medium uppercase tracking-wide text-neutral-400">+ Conversation · {messages.length} messages+ </p>+ )}+ <ol className="space-y-2">+ {slice.map((message) => (+ <li key={message.id}>+ <ConversationMessageCard+ message={message}+ mailboxId={mailboxId}+ currentAccountName={currentAccountName}+ />+ </li>+ ))}+ </ol>+ </section>+ );+}++export function ConversationMessageCard({+ message,+ mailboxId,+ currentAccountName,+ defaultExpanded = false,+}: ConversationMessageCardProps) {+ const [expanded, setExpanded] = useState(defaultExpanded);+ const sender = getConversationSender(message, currentAccountName);+ const recipients = getConversationRecipients(message);+ const href = `${getMessageBackHref(message.direction, message.status)}/${message.id}`;+ const outbound = message.direction === "outbound";+ const attachments = message.attachments.filter((attachment) => attachment.disposition === "attachment");++ let body: { html: string | null; text: string } | null = null;+ if (expanded) {+ const display = getMessageBodyDisplay(message.textBody, message.htmlBody, message.snippet);+ body = {+ html: sanitizeEmailHtml(resolveInlineAttachmentUrls(display.htmlBody, message.id, message.attachments)),+ text: display.latestContent,+ };+ }++ return (+ <article+ className={cn(+ "rounded-lg border transition-colors",+ outbound ? "border-blue-100 bg-blue-50/40" : "border-neutral-200 bg-white",+ expanded ? "shadow-sm" : "hover:bg-neutral-50",+ )}+ >+ <button+ type="button"+ onClick={() => setExpanded((open) => !open)}+ aria-expanded={expanded}+ className="flex w-full items-center gap-3 px-4 py-3 text-left"+ >+ <span+ className={cn(+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-semibold",+ outbound ? "bg-blue-600 text-white" : "bg-neutral-200 text-neutral-700",+ )}+ aria-hidden+ >+ {outbound ? <Reply className="h-4 w-4" /> : getAvatarInitial(message, currentAccountName)}+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex items-baseline justify-between gap-3">+ <span className={cn("truncate text-sm", message.read || outbound ? "text-neutral-900" : "font-semibold text-neutral-900")}>+ {sender}+ {recipients && <span className="ml-2 text-xs font-normal text-neutral-500">to {recipients}</span>}+ </span>+ <span className="flex shrink-0 items-center gap-2 text-xs text-neutral-400">+ {attachments.length > 0 && <Paperclip className="h-3.5 w-3.5" aria-label={`${attachments.length} attachments`} />}+ {dayjs(message.createdAt).format("MMM DD, YYYY, hh:mmA")}+ <ChevronDown className={cn("h-4 w-4 transition-transform", expanded && "rotate-180")} />+ </span>+ </span>+ {!expanded && (+ <span className="mt-0.5 block truncate text-xs text-neutral-500">{message.snippet || "No preview"}</span>+ )}+ </span>+ </button>+ {expanded && body && (+ <div className="border-t border-neutral-100 px-4 py-4">+ <p className="mb-3 text-xs text-neutral-500">+ {message.direction === "inbound" ? (+ <ContactDetailsTrigger mailboxId={mailboxId} address={message.fromAddr} name={sender} />+ ) : (+ sender+ )}{" "}+ <{getEmailAddress(message.fromAddr)}>+ </p>+ {body.html ? (+ <div className="prose max-w-none text-sm text-neutral-900" dangerouslySetInnerHTML={{ __html: body.html }} />+ ) : (+ <pre className="whitespace-pre-wrap font-sans text-sm text-neutral-900">{body.text}</pre>+ )}+ {attachments.length > 0 && (+ <ul className="mt-4 flex flex-wrap gap-2">+ {attachments.map((attachment) => (+ <li key={attachment.id}>+ <a+ href={`/api/messages/${message.id}/attachments/${attachment.id}`}+ className="inline-flex items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-2.5 py-1 text-xs text-neutral-700 hover:bg-neutral-50"+ >+ <Paperclip className="h-3 w-3" />+ <span className="max-w-48 truncate">{attachment.filename}</span>+ </a>+ </li>+ ))}+ </ul>+ )}+ <Link href={href} className="mt-4 inline-block text-xs font-medium text-blue-600 hover:underline">+ Open this message+ </Link>+ </div>+ )}+ </article>+ );+}diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsxindex d81f026..90e5b7b 100644--- a/src/components/messages/message-folder-page.tsx+++ b/src/components/messages/message-folder-page.tsx@@ -108,6 +108,9 @@ function MessageListRow({}`}>{message.subject ?? "(no subject)"}+ {(message.threadCount ?? 1) > 1 && (+ <span className="ml-1 text-xs font-normal text-neutral-500">({message.threadCount})</span>+ )}</span><span className="mt-0.5 block truncate text-xs leading-5 text-neutral-500">{preview}@@ -150,6 +153,9 @@ function MessageListRow({<span className={unread ? "font-bold text-neutral-900" : ""}>{rowMessage.subject ?? "(no subject)"}</span>+ {(message.threadCount ?? 1) > 1 && (+ <span className="ml-1 text-xs text-neutral-500">({message.threadCount})</span>+ )}<span className="text-neutral-500"> - {getMessagePreview(rowMessage, config.folder)}</span></span><timediff --git a/src/components/messages/use-message-thread.ts b/src/components/messages/use-message-thread.tsnew file mode 100644index 0000000..e14bb85--- /dev/null+++ b/src/components/messages/use-message-thread.ts@@ -0,0 +1,35 @@+import { useEffect, useState } from "react";+import { authFetch } from "@/lib/auth/client";+import type { ThreadMessage, ThreadResponse } from "@/hooks/types";+import type { UseMessageThreadResult } from "./conversation-thread-types";++/** Loads every message in the conversation of `messageId`; refetches when mail changes. */+export function useMessageThread(messageId: string, threadId: string | null | undefined): UseMessageThreadResult {+ const [messages, setMessages] = useState<ThreadMessage[]>([]);+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ if (!threadId) return;+ let cancelled = false;+ async function load() {+ setLoading(true);+ try {+ const response = await authFetch(`/api/messages/${messageId}/thread`);+ const data = (await response.json()) as ThreadResponse;+ if (!cancelled) setMessages(response.ok ? data.messages ?? [] : []);+ } catch {+ if (!cancelled) setMessages([]);+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ void load();+ window.addEventListener("mailflare:messages-changed", load);+ return () => {+ cancelled = true;+ window.removeEventListener("mailflare:messages-changed", load);+ };+ }, [messageId, threadId]);++ return { messages: threadId ? messages : [], loading };+}diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.tsindex 4b4b0a1..765bb84 100644--- a/src/components/messages/utils.ts+++ b/src/components/messages/utils.ts@@ -1,6 +1,6 @@import type { Message } from "@/hooks/types";import { authFetch } from "@/lib/auth/client";-import { getEmailDisplayName } from "@/lib/email/address";+import { getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address";import dayjs from "dayjs";import type { MailboxOption } from "@/components/mailbox-provider";import type { EmailPageTitleInput } from "./types";@@ -13,11 +13,19 @@ export function getMessageParty(currentAccountName?: string,) {if (folder === "drafts") return "Draft";- if (folder === "sent") return message.toContactName ?? (message.toAddr ? getEmailDisplayName(message.toAddr) : "No recipient");+ if (folder === "sent") return formatRecipientSummary(message.toAddr, message.toContactName);if (message.direction === "outbound" && currentAccountName) return currentAccountName;return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : "Unknown sender");}+/** "Maya Chen, +2" for a multi-recipient message, or just the one name. */+export function formatRecipientSummary(toAddr: string, firstContactName?: string | null): string {+ const entries = splitEmailAddressList(toAddr);+ if (entries.length === 0) return "No recipient";+ const first = firstContactName ?? getEmailDisplayName(entries[0]);+ return entries.length > 1 ? `${first}, +${entries.length - 1}` : first;+}+export function getMessagePartyClassName(message: Message, folder: MessageFolderConfig["folder"]) {if (folder === "drafts") return "truncate font-semibold text-red-600";diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex db8656d..b12b36e 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -208,6 +208,8 @@ export const messages = sqliteTable(folderId: text("folder_id").references(() => folders.id, { onDelete: "set null" }),fromAddr: text("from_addr").notNull(),toAddr: text("to_addr").notNull(),+ ccAddr: text("cc_addr"),+ bccAddr: text("bcc_addr"),subject: text("subject"),snippet: text("snippet"),textBody: text("text_body"),@@ -218,6 +220,10 @@ export const messages = sqliteTable(starred: integer("starred", { mode: "boolean" }).notNull().default(false),snoozedUntil: integer("snoozed_until", { mode: "timestamp" }),threadId: text("thread_id"),+ // RFC 5322 threading headers, kept so replies land in the right conversation+ // and so outgoing replies can carry them on to the recipient's client.+ inReplyTo: text("in_reply_to"),+ references: text("references_header"),createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),@@ -226,6 +232,8 @@ export const messages = sqliteTable(index("messages_user_created_idx").on(t.userId, t.createdAt),index("messages_mailbox_idx").on(t.mailboxId),index("messages_folder_idx").on(t.folderId),+ index("messages_thread_idx").on(t.mailboxId, t.threadId),+ index("messages_provider_message_idx").on(t.mailboxId, t.providerMessageId),],);diff --git a/src/hooks/types.d.ts b/src/hooks/types.d.tsindex 669a528..b8eb0a6 100644--- a/src/hooks/types.d.ts+++ b/src/hooks/types.d.ts@@ -12,7 +12,10 @@ export type Message = {direction: MessageDirection;providerMessageId: string | null;fromAddr: string;+ /** Comma-separated recipient list; may include display names. */toAddr: string;+ ccAddr?: string | null;+ bccAddr?: string | null;fromContactName?: string | null;toContactName?: string | null;subject: string | null;@@ -24,9 +27,33 @@ export type Message = {starred: boolean;snoozedUntil?: string | null;threadId: string | null;+ inReplyTo?: string | null;+ references?: string | null;+ /** Messages in the same conversation (excluding drafts and trash), when the list API computed it. */+ threadCount?: number;createdAt: string;};+export type ThreadMessage = Message & {+ textBody: string | null;+ htmlBody: string | null;+ attachments: Array<{+ contentId: string | null;+ disposition: "attachment" | "inline";+ filename: string;+ id: string;+ messageId: string;+ size: number;+ type: string;+ }>;+};++export type ThreadResponse = {+ threadId: string | null;+ messages?: ThreadMessage[];+ error?: string;+};+export type MessageReadFilter = "all" | "read" | "unread";export type MessageFilterOptions = {diff --git a/src/lib/contacts/service.ts b/src/lib/contacts/service.tsindex 8b47941..2bd8936 100644--- a/src/lib/contacts/service.ts+++ b/src/lib/contacts/service.ts@@ -1,7 +1,7 @@import { and, eq, inArray } from "drizzle-orm";import { getDb } from "@/db";import { contacts, routingRules } from "@/db/schema";-import { normalizeEmailAddress } from "@/lib/email/address";+import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";import type { BlockContactInput, ContactInput, MessageContactNames } from "@/lib/contacts/types";import { getContactId, getContactNameFromAddress } from "@/lib/contacts/utils";@@ -70,11 +70,13 @@ export async function getMessageContactNames(fromAddr: string,toAddr: string,): Promise<MessageContactNames> {- const contactMap = await getContactDisplayNameMap(env, userId, [fromAddr, toAddr]);+ // `toAddr` may be a full recipient list; the name shown belongs to the first one.+ const firstTo = getFirstEmailAddressEntry(toAddr);+ const contactMap = await getContactDisplayNameMap(env, userId, [fromAddr, firstTo]);return {fromContactName: contactMap.get(normalizeEmailAddress(fromAddr)) ?? null,- toContactName: contactMap.get(normalizeEmailAddress(toAddr)) ?? null,+ toContactName: contactMap.get(normalizeEmailAddress(firstTo)) ?? null,};}diff --git a/src/lib/email/address.ts b/src/lib/email/address.tsindex 317f682..1e2e85e 100644--- a/src/lib/email/address.ts+++ b/src/lib/email/address.ts@@ -45,21 +45,73 @@ export function getEmailDisplayName(value: string): string {}export function formatPostalAddress(address: Address | undefined, fallback: string | null): string | null {- const mailbox = getFirstPostalMailbox(address);+ const [mailbox] = getPostalMailboxes(address);if (!mailbox?.address) return fallback;return formatEmailAddress(mailbox.address, mailbox.name);}+/**+ * Every mailbox in a header address list, formatted and comma-joined, so that a+ * message's full To/Cc line survives storage and reply-all can see it.+ */export function formatPostalAddressList(addresses: Address[] | undefined, fallback: string | null): string | null {- const mailbox = addresses?.map(getFirstPostalMailbox).find((item): item is Mailbox => !!item?.address);- if (!mailbox?.address) return fallback;+ const mailboxes = (addresses ?? []).flatMap(getPostalMailboxes).filter((item) => !!item.address);+ if (mailboxes.length === 0) return fallback;- return formatEmailAddress(mailbox.address, mailbox.name);+ return mailboxes.map((mailbox) => formatEmailAddress(mailbox.address, mailbox.name)).join(", ");+}++function getPostalMailboxes(address: Address | undefined): Mailbox[] {+ if (!address) return [];+ if ("address" in address && address.address) return [address];+ return address.group ?? [];+}++/**+ * Split a comma-separated header value into individual addresses, leaving+ * commas inside quoted display names (`"Chen, Maya" <[email protected]>`) alone.+ */+export function splitEmailAddressList(value: string | null | undefined): string[] {+ const result: string[] = [];+ let current = "";+ let inQuotes = false;+ let inAngle = false;++ for (const char of value ?? "") {+ if (char === '"' && !inAngle) inQuotes = !inQuotes;+ else if (char === "<" && !inQuotes) inAngle = true;+ else if (char === ">" && !inQuotes) inAngle = false;++ if ((char === "," || char === ";") && !inQuotes && !inAngle) {+ if (current.trim()) result.push(current.trim());+ current = "";+ continue;+ }+ current += char;+ }+ if (current.trim()) result.push(current.trim());+ return result;+}++/** Bare, lower-cased addresses from a header list, deduplicated in order. */+export function getEmailAddressList(value: string | null | undefined): string[] {+ const seen = new Set<string>();+ const result: string[] = [];+ for (const entry of splitEmailAddressList(value)) {+ const address = normalizeEmailAddress(entry);+ if (!address || seen.has(address)) continue;+ seen.add(address);+ result.push(address);+ }+ return result;+}++export function joinEmailAddressList(values: string[]): string {+ return values.map((value) => value.trim()).filter(Boolean).join(", ");}-function getFirstPostalMailbox(address: Address | undefined): Mailbox | null {- if (!address) return null;- if ("address" in address && address.address) return address;- return address.group ? address.group[0] : null;+/** The first address of a list, for places that show a single party. */+export function getFirstEmailAddressEntry(value: string | null | undefined): string {+ return splitEmailAddressList(value)[0] ?? (value ?? "").trim();}diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.tsindex e0dedb0..33435af 100644--- a/src/lib/email/inbound.ts+++ b/src/lib/email/inbound.ts@@ -11,6 +11,7 @@ import { sendMailboxAutoReply } from "@/lib/email/auto-reply";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import { listMessageAttachments, storeMessageAttachments } from "@/lib/email/attachments";import { getUnsubscribeUrlFromRawR2Key } from "@/lib/email/unsubscribe";+import { resolveThreadId } from "@/lib/email/threading";import type { SessionUser } from "@/lib/auth/types";import {getMailboxNotificationUserIds,@@ -63,11 +64,13 @@ export async function processInboundMessage(const messageId = newId("msg");const snippet = buildSnippet(parsed.text, parsed.html);const deliveredAddress = getEmailAddress(payload.to) || `${decision.mailbox.localPart}@${decision.mailbox.hostname}`;- const toAddr = payload.to;+ // Keep the whole To header so reply-all can address everyone; rules and+ // webhooks still see the envelope recipient the message was delivered to.+ const toAddr = parsed.toAddr ?? payload.to;const fromAddr = parsed.fromAddr ?? payload.from;const destination = await resolveInboxRuleDestination(db, {mailboxId: decision.mailbox.mailboxId,- toAddress: toAddr,+ toAddress: payload.to,fromAddress: fromAddr,subject: parsed.subject,content: [parsed.text, parsed.html, snippet].filter(Boolean).join(" "),@@ -77,6 +80,12 @@ export async function processInboundMessage(address: fromAddr,source: "inbound",});+ const threadId = await resolveThreadId(db, {+ mailboxId: decision.mailbox.mailboxId,+ messageId: parsed.messageId,+ inReplyTo: parsed.inReplyTo,+ references: parsed.references,+ });try {await db.insert(messages).values({@@ -88,13 +97,16 @@ export async function processInboundMessage(providerMessageId: parsed.messageId,fromAddr,toAddr,+ ccAddr: parsed.ccAddr,subject: parsed.subject,snippet,textBody: parsed.text,htmlBody: parsed.html,rawR2Key: payload.rawR2Key,status: destination.status,- threadId: parsed.messageId,+ threadId,+ inReplyTo: parsed.inReplyTo,+ references: parsed.references.length ? parsed.references.join(" ") : null,});await storeMessageAttachments(env, messageId, parsed.attachments, { validate: false });@@ -134,8 +146,10 @@ export async function processInboundMessage(await dispatchWebhooks(env, decision.mailbox.userId, "message.inbound", {messageId,from: fromAddr,- to: toAddr,+ to: payload.to,+ cc: parsed.ccAddr ?? undefined,subject: parsed.subject,+ threadId,});}diff --git a/src/lib/email/parse.ts b/src/lib/email/parse.tsindex d5025e1..faa3acb 100644--- a/src/lib/email/parse.ts+++ b/src/lib/email/parse.ts@@ -1,5 +1,6 @@import PostalMime from "postal-mime";import { formatPostalAddress, formatPostalAddressList } from "@/lib/email/address";+import { normalizeMessageId, parseMessageIdList } from "@/lib/email/threading";import { normalizeAttachmentContent } from "@/lib/email/attachments";import { getLatestEmailContent, htmlToReadableText } from "@/lib/email/reply-content-utils";import type { AttachmentContent } from "@/lib/email/attachment-types";@@ -10,7 +11,12 @@ export type ParsedEmail = {html: string | null;messageId: string | null;fromAddr: string | null;+ /** Full To header, comma-joined. */toAddr: string | null;+ /** Full Cc header, comma-joined. */+ ccAddr: string | null;+ inReplyTo: string | null;+ references: string[];date: Date | null;attachments: AttachmentContent[];};@@ -25,6 +31,9 @@ export async function parseRawMime(raw: ArrayBuffer): Promise<ParsedEmail> {messageId: email.messageId ?? null,fromAddr: formatPostalAddress(email.from, null),toAddr: formatPostalAddressList(email.to, null),+ ccAddr: formatPostalAddressList(email.cc, null),+ inReplyTo: normalizeMessageId(email.inReplyTo),+ references: parseMessageIdList(email.references),date: date && !Number.isNaN(date.getTime()) ? date : null,attachments: email.attachments.map((attachment, index) => ({filename: attachment.filename ?? `attachment-${index + 1}`,diff --git a/src/lib/email/send.ts b/src/lib/email/send.tsindex b62b4f3..a02af5f 100644--- a/src/lib/email/send.ts+++ b/src/lib/email/send.ts@@ -6,6 +6,8 @@ import { buildSnippet } from "@/lib/email/parse";import { dispatchWebhooks } from "@/lib/email/webhooks";import { upsertContactFromAddress } from "@/lib/contacts/service";import { getAuthorizedSenderAddress } from "@/lib/email/sender";+import { getEmailAddressList, joinEmailAddressList, splitEmailAddressList } from "@/lib/email/address";+import { formatMessageIdHeader, normalizeMessageId, parseMessageIdList } from "@/lib/email/threading";import { createAuditLog } from "@/lib/mailboxes/audit";import { storeMessageAttachments, validateAttachments } from "@/lib/email/attachments";import type { AttachmentContent } from "@/lib/email/attachment-types";@@ -13,27 +15,67 @@ import type { AttachmentContent } from "@/lib/email/attachment-types";export type SendEmailInput = {userId: string;from: string;- to: string;+ /** One header-style list or an array; each entry may carry a display name. */+ to: string | string[];+ cc?: string | string[];+ bcc?: string | string[];subject: string;html?: string;text?: string;headers?: Record<string, string>;+ /** Message-ID of the message being replied to, with or without angle brackets. */+ inReplyTo?: string | null;+ /** References chain, as a header string or a list of Message-IDs. */+ references?: string | string[] | null;+ /** Conversation to file the sent copy under; defaults to its own Message-ID. */+ threadId?: string | null;mailboxId: string;attachments?: AttachmentContent[];};+const MAX_RECIPIENTS = 50;++function toRecipientList(value: string | string[] | undefined): string[] {+ const entries = Array.isArray(value) ? value : splitEmailAddressList(value);+ const seen = new Set<string>();+ const result: string[] = [];+ for (const entry of entries) {+ const [address] = getEmailAddressList(entry);+ if (!address || seen.has(address)) continue;+ seen.add(address);+ result.push(entry.trim());+ }+ return result;+}+export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Promise<{ messageId: string }> {const db = getDb(env);const sender = await getAuthorizedSenderAddress(env, input);const attachments = input.attachments ?? [];validateAttachments(attachments);- await upsertContactFromAddress(env, {- userId: input.userId,- address: input.to,- source: "outbound",- });++ const to = toRecipientList(input.to);+ const cc = toRecipientList(input.cc);+ const bcc = toRecipientList(input.bcc);+ if (to.length === 0) throw new Error("At least one recipient is required");+ if (to.length + cc.length + bcc.length > MAX_RECIPIENTS) {+ throw new Error(`A message can have at most ${MAX_RECIPIENTS} recipients`);+ }+ for (const address of [...to, ...cc, ...bcc]) {+ await upsertContactFromAddress(env, { userId: input.userId, address, source: "outbound" });+ }++ const inReplyTo = normalizeMessageId(input.inReplyTo);+ const references = Array.isArray(input.references)+ ? input.references.map((id) => normalizeMessageId(id)).filter((id): id is string => !!id)+ : parseMessageIdList(input.references);+ const headers: Record<string, string> = { ...input.headers };+ if (inReplyTo) headers["In-Reply-To"] = `<${inReplyTo}>`;+ if (references.length > 0) headers.References = formatMessageIdHeader(references);+const messageId = newId("msg");const snippet = buildSnippet(input.text ?? null, input.html ?? null);+ const toAddr = joinEmailAddressList(to);await db.insert(messages).values({id: messageId,@@ -41,12 +83,17 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): PrommailboxId: sender.mailboxId,direction: "outbound",fromAddr: sender.fromAddr,- toAddr: input.to,+ toAddr,+ ccAddr: cc.length ? joinEmailAddressList(cc) : null,+ bccAddr: bcc.length ? joinEmailAddressList(bcc) : null,subject: input.subject,snippet,textBody: input.text ?? null,htmlBody: input.html ?? null,status: "queued",+ threadId: input.threadId ?? null,+ inReplyTo,+ references: references.length ? references.join(" ") : null,});try {await storeMessageAttachments(env, messageId, attachments);@@ -64,6 +111,9 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Prompayload: JSON.stringify({...input,from: sender.fromAddr,+ to,+ cc,+ bcc,mailboxId: sender.mailboxId,attachments: attachments.map(({ content: _content, ...attachment }) => attachment),}),@@ -72,9 +122,11 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Promtry {const response = await env.EMAIL.send({from: sender.fromAddr,- to: input.to,+ to,+ ...(cc.length ? { cc } : {}),+ ...(bcc.length ? { bcc } : {}),subject: input.subject,- headers: input.headers,+ headers: Object.keys(headers).length ? headers : undefined,html: input.html,text: input.text,attachments: attachments.map((attachment) =>@@ -95,23 +147,30 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Prom),});+ // A fresh message starts its own conversation; Cloudflare's Message-ID is what+ // any reply will name in In-Reply-To, so key the thread by it.await db.update(messages)- .set({ status: "sent", providerMessageId: response.messageId })+ .set({+ status: "sent",+ providerMessageId: response.messageId,+ threadId: input.threadId ?? normalizeMessageId(response.messageId) ?? messageId,+ }).where(eq(messages.id, messageId));await db.update(outboundJobs).set({ status: "sent", updatedAt: new Date() }).where(eq(outboundJobs.id, jobId));await dispatchWebhooks(env, input.userId, "message.outbound", {messageId,providerMessageId: response.messageId,- to: input.to,+ to: toAddr,+ cc: cc.length ? joinEmailAddressList(cc) : undefined,});await createAuditLog(env, {actorUserId: input.userId,mailboxId: sender.mailboxId,messageId,action: "email.send",- metadata: { to: input.to, subject: input.subject },+ metadata: { to: toAddr, cc: cc.length ? joinEmailAddressList(cc) : undefined, subject: input.subject },});return { messageId };diff --git a/src/lib/email/thread-view.ts b/src/lib/email/thread-view.tsnew file mode 100644index 0000000..55fc3dd--- /dev/null+++ b/src/lib/email/thread-view.ts@@ -0,0 +1,85 @@+import { and, asc, eq, inArray, notInArray } from "drizzle-orm";+import { getDb } from "@/db";+import { messageAttachments, messages } from "@/db/schema";+import { getContactDisplayNameMap } from "@/lib/contacts/service";+import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";+import type { SessionUser } from "@/lib/auth/types";++/**+ * The conversation a message belongs to: every stored message in the same+ * mailbox sharing its thread id, oldest first. Drafts and trashed messages are+ * left out, matching what threaded clients show. Bodies come along so the+ * reader can expand any message without another round trip.+ */+/** The R2 key is an internal pointer and never leaves the server. */+function withoutRawKey<T extends { rawR2Key: string | null }>(row: T): Omit<T, "rawR2Key"> {+ const copy: Partial<T> = { ...row };+ delete copy.rawR2Key;+ return copy as Omit<T, "rawR2Key">;+}++export async function getMessageThreadForUser(env: CloudflareEnv, user: SessionUser, messageId: string) {+ const db = getDb(env);+ const [message] = await db+ .select({ mailboxId: messages.mailboxId, userId: messages.userId, threadId: messages.threadId })+ .from(messages)+ .where(eq(messages.id, messageId))+ .limit(1);+ if (!message?.mailboxId) return null;+ const access = await getMailboxAccessLevel(db, user, message.mailboxId);+ if (!access?.canRead) return null;++ const rows = message.threadId+ ? await db+ .select()+ .from(messages)+ .where(+ and(+ eq(messages.mailboxId, message.mailboxId),+ eq(messages.threadId, message.threadId),+ notInArray(messages.status, ["draft", "trash"]),+ ),+ )+ .orderBy(asc(messages.createdAt))+ .limit(200)+ : await db.select().from(messages).where(eq(messages.id, messageId)).limit(1);++ const ids = rows.map((row) => row.id);+ const attachmentRows = ids.length+ ? await db+ .select({+ id: messageAttachments.id,+ messageId: messageAttachments.messageId,+ filename: messageAttachments.filename,+ type: messageAttachments.contentType,+ size: messageAttachments.size,+ disposition: messageAttachments.disposition,+ contentId: messageAttachments.contentId,+ })+ .from(messageAttachments)+ .where(inArray(messageAttachments.messageId, ids))+ : [];+ const attachmentsByMessage = new Map<string, typeof attachmentRows>();+ for (const attachment of attachmentRows) {+ const list = attachmentsByMessage.get(attachment.messageId) ?? [];+ list.push(attachment);+ attachmentsByMessage.set(attachment.messageId, list);+ }++ const contactMap = await getContactDisplayNameMap(+ env,+ message.userId,+ rows.flatMap((row) => [row.fromAddr, getFirstEmailAddressEntry(row.toAddr)]),+ );++ return {+ threadId: message.threadId,+ messages: rows.map((row) => ({+ ...withoutRawKey(row),+ fromContactName: contactMap.get(normalizeEmailAddress(row.fromAddr)) ?? null,+ toContactName: contactMap.get(normalizeEmailAddress(getFirstEmailAddressEntry(row.toAddr))) ?? null,+ attachments: attachmentsByMessage.get(row.id) ?? [],+ })),+ };+}diff --git a/src/lib/email/threading-types.d.ts b/src/lib/email/threading-types.d.tsnew file mode 100644index 0000000..d21b2b9--- /dev/null+++ b/src/lib/email/threading-types.d.ts@@ -0,0 +1,7 @@+export type ResolveThreadInput = {+ mailboxId: string | null;+ /** The message's own Message-ID; seeds a new thread when no parent is stored. */+ messageId: string | null;+ inReplyTo?: string | null;+ references?: string[];+};diff --git a/src/lib/email/threading.ts b/src/lib/email/threading.tsnew file mode 100644index 0000000..0cdebc6--- /dev/null+++ b/src/lib/email/threading.ts@@ -0,0 +1,73 @@+import { and, asc, eq, inArray } from "drizzle-orm";+import type { getDb } from "@/db";+import { messages } from "@/db/schema";+import { newId } from "@/lib/ids";+import type { ResolveThreadInput } from "@/lib/email/threading-types";++type Db = ReturnType<typeof getDb>;++/** RFC 5322 Message-IDs are compared without their angle brackets or surrounding space. */+export function normalizeMessageId(value: string | null | undefined): string | null {+ const trimmed = (value ?? "").trim().replace(/^<|>$/g, "").trim();+ return trimmed || null;+}++/** A References header is a whitespace (occasionally comma) separated list of Message-IDs. */+export function parseMessageIdList(value: string | null | undefined): string[] {+ const seen = new Set<string>();+ const result: string[] = [];+ for (const token of (value ?? "").split(/[\s,]+/)) {+ const id = normalizeMessageId(token);+ if (!id || seen.has(id)) continue;+ seen.add(id);+ result.push(id);+ }+ return result;+}++export function formatMessageIdHeader(ids: string[]): string {+ return ids.map((id) => `<${id}>`).join(" ");+}++/**+ * The References line a reply should carry: the parent's own chain followed by+ * the parent itself. Long chains keep the root and the most recent ancestors,+ * which is what mail clients use to reconstruct a conversation.+ */+export function buildReplyReferences(parentReferences: string[], parentMessageId: string | null): string[] {+ const ids = [...parentReferences];+ const parent = normalizeMessageId(parentMessageId);+ if (parent && !ids.includes(parent)) ids.push(parent);+ const MAX = 30;+ if (ids.length <= MAX) return ids;+ return [ids[0], ...ids.slice(ids.length - (MAX - 1))];+}++/**+ * Work out which conversation a message belongs to. A reply names its parent in+ * In-Reply-To or References; if that parent is stored in the same mailbox, the+ * new message joins the parent's thread. Otherwise it starts a thread keyed by+ * its own Message-ID so later replies can find it.+ */+export async function resolveThreadId(db: Db, input: ResolveThreadInput): Promise<string> {+ const candidates = new Set<string>();+ for (const id of [normalizeMessageId(input.inReplyTo), ...(input.references ?? [])]) {+ if (id) candidates.add(id);+ }++ if (input.mailboxId && candidates.size > 0) {+ // Stored Message-IDs may or may not include their angle brackets.+ const variants = Array.from(candidates).flatMap((id) => [id, `<${id}>`]);+ const [parent] = await db+ .select({ threadId: messages.threadId, providerMessageId: messages.providerMessageId })+ .from(messages)+ .where(and(eq(messages.mailboxId, input.mailboxId), inArray(messages.providerMessageId, variants)))+ .orderBy(asc(messages.createdAt))+ .limit(1);+ if (parent) {+ return parent.threadId ?? normalizeMessageId(parent.providerMessageId) ?? newId("thr");+ }+ }++ return normalizeMessageId(input.messageId) ?? newId("thr");+}diff --git a/src/lib/export/mbox.ts b/src/lib/export/mbox.tsindex 2c7998d..3f89456 100644--- a/src/lib/export/mbox.ts+++ b/src/lib/export/mbox.ts@@ -21,6 +21,9 @@ export async function exportMailboxToMbox(env: CloudflareEnv, mailboxId: string)id: messages.id,fromAddr: messages.fromAddr,toAddr: messages.toAddr,+ ccAddr: messages.ccAddr,+ inReplyTo: messages.inReplyTo,+ references: messages.references,subject: messages.subject,providerMessageId: messages.providerMessageId,direction: messages.direction,@@ -43,6 +46,11 @@ export async function exportMailboxToMbox(env: CloudflareEnv, mailboxId: string)`Date: ${date.toUTCString()}`,`From: ${escapeHeader(message.fromAddr)}`,`To: ${escapeHeader(message.toAddr)}`,+ ...(message.ccAddr ? [`Cc: ${escapeHeader(message.ccAddr)}`] : []),+ ...(message.inReplyTo ? [`In-Reply-To: <${escapeHeader(message.inReplyTo)}>`] : []),+ ...(message.references+ ? [`References: ${message.references.split(/\s+/).filter(Boolean).map((id) => `<${id}>`).join(" ")}`]+ : []),`Subject: ${escapeHeader(message.subject)}`,`X-Mailflare-Direction: ${escapeHeader(message.direction)}`,`X-Mailflare-Status: ${escapeHeader(message.status)}`,diff --git a/src/lib/import/service.ts b/src/lib/import/service.tsindex 6231bab..08425f5 100644--- a/src/lib/import/service.ts+++ b/src/lib/import/service.ts@@ -3,6 +3,7 @@ import { getDb } from "@/db";import { messages } from "@/db/schema";import { storeMessageAttachments } from "@/lib/email/attachments";import { buildSnippet, parseRawMime } from "@/lib/email/parse";+import { resolveThreadId } from "@/lib/email/threading";import { upsertContactFromAddress } from "@/lib/contacts/service";import { newId } from "@/lib/ids";import { getImportMessagePlacement } from "./destination";@@ -77,13 +78,21 @@ async function importMessageToMailbox(providerMessageId,fromAddr,toAddr,+ ccAddr: parsed.ccAddr,subject: parsed.subject,snippet: buildSnippet(parsed.text, parsed.html),textBody: parsed.text,htmlBody: parsed.html,status: placement.status,read: placement.direction === "outbound",- threadId: parsed.messageId,+ threadId: await resolveThreadId(db, {+ mailboxId: input.mailboxId,+ messageId: parsed.messageId,+ inReplyTo: parsed.inReplyTo,+ references: parsed.references,+ }),+ inReplyTo: parsed.inReplyTo,+ references: parsed.references.length ? parsed.references.join(" ") : null,createdAt,});diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.tsindex 9e6e136..73aadbf 100644--- a/src/lib/setup/migration.ts+++ b/src/lib/setup/migration.ts@@ -24,6 +24,7 @@ const MIGRATION_NAMES = ["0022_add_mailbox_auto_reply.sql","0023_add_mailbox_aliases.sql","0024_add_advanced_routing_and_webhook_retries.sql",+ "0025_add_threading_and_cc_bcc.sql",];const INITIAL_SCHEMA_SQL = `@@ -52,10 +53,12 @@ CREATE UNIQUE INDEX IF NOT EXISTS folders_mailbox_name_idx ON folders(mailbox_idCREATE INDEX IF NOT EXISTS folders_user_idx ON folders(user_id);CREATE INDEX IF NOT EXISTS folders_mailbox_idx ON folders(mailbox_id);CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, name text NOT NULL, prefix text NOT NULL, key_hash text NOT NULL, scopes text NOT NULL, created_at integer NOT NULL, last_used_at integer);-CREATE TABLE IF NOT EXISTS messages (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, direction text NOT NULL, provider_message_id text, folder_id text REFERENCES folders(id) ON DELETE set null, from_addr text NOT NULL, to_addr text NOT NULL, subject text, snippet text, text_body text, html_body text, raw_r2_key text, status text DEFAULT 'received' NOT NULL, read integer DEFAULT false NOT NULL, starred integer DEFAULT false NOT NULL, snoozed_until integer, thread_id text, created_at integer NOT NULL);+CREATE TABLE IF NOT EXISTS messages (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, direction text NOT NULL, provider_message_id text, folder_id text REFERENCES folders(id) ON DELETE set null, from_addr text NOT NULL, to_addr text NOT NULL, cc_addr text, bcc_addr text, subject text, snippet text, text_body text, html_body text, raw_r2_key text, status text DEFAULT 'received' NOT NULL, read integer DEFAULT false NOT NULL, starred integer DEFAULT false NOT NULL, snoozed_until integer, thread_id text, in_reply_to text, references_header text, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS messages_user_created_idx ON messages(user_id, created_at);CREATE INDEX IF NOT EXISTS messages_mailbox_idx ON messages(mailbox_id);CREATE INDEX IF NOT EXISTS messages_folder_idx ON messages(folder_id);+CREATE INDEX IF NOT EXISTS messages_thread_idx ON messages(mailbox_id, thread_id);+CREATE INDEX IF NOT EXISTS messages_provider_message_idx ON messages(mailbox_id, provider_message_id);CREATE TABLE IF NOT EXISTS message_attachments (id text PRIMARY KEY NOT NULL, message_id text NOT NULL REFERENCES messages(id) ON DELETE cascade, filename text NOT NULL, content_type text NOT NULL, size integer NOT NULL, disposition text DEFAULT 'attachment' NOT NULL, content_id text, r2_key text NOT NULL UNIQUE, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS message_attachments_message_idx ON message_attachments(message_id);CREATE TABLE IF NOT EXISTS outbound_jobs (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, message_id text REFERENCES messages(id) ON DELETE set null, status text DEFAULT 'queued' NOT NULL, payload text NOT NULL, error text, scheduled_at integer, created_at integer NOT NULL, updated_at integer NOT NULL);diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex d09ef99..669cdb9 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -1,10 +1,31 @@import { z } from "zod";+import { getEmailAddress, splitEmailAddressList } from "@/lib/email/address";import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_VALUES } from "@/lib/folders/colors";+/**+ * Recipients arrive either as one comma-separated header string (the composer)+ * or as an array (the public API). Both normalise to a trimmed list of entries+ * that still carry their display names.+ */+const recipientListSchema = z+ .union([z.string().max(5000), z.array(z.string().trim().min(3).max(500)).max(50)])+ .transform((value) => (Array.isArray(value) ? value : splitEmailAddressList(value)))+ .refine((list) => list.length <= 50, "A message can have at most 50 recipients per field")+ .refine((list) => list.every((entry) => getEmailAddress(entry).includes("@")), "Enter valid email addresses");++const messageIdListSchema = z+ .union([z.string().max(5000), z.array(z.string().max(998)).max(50)])+ .transform((value) => (Array.isArray(value) ? value.join(" ") : value));+export const sendEmailSchema = z.object({from: z.string().min(3).max(500),- to: z.string().min(3).max(500),+ to: recipientListSchema.refine((list) => list.length > 0, "At least one recipient is required"),+ cc: recipientListSchema.optional(),+ bcc: recipientListSchema.optional(),subject: z.string().min(1).max(500),+ inReplyTo: z.string().max(998).optional(),+ references: messageIdListSchema.optional(),+ threadId: z.string().max(998).optional(),html: z.string().max(2 * 1024 * 1024).optional(),text: z.string().max(2 * 1024 * 1024).optional(),mailboxId: z.string().min(1).max(200),