Email for professionals and teams
fix: keep per-message sender display names (#226)
Antonio1302bbae7d94
diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.tsindex 812a781..7f958c1 100644--- a/src/app/api/messages/route.ts+++ b/src/app/api/messages/route.ts@@ -6,6 +6,7 @@ import { getCurrentUser } from "@/lib/auth/cookies";import { getDb } from "@/db";import { messages, outboundJobs } from "@/db/schema";import { getContactDisplayNameMap } from "@/lib/contacts/service";+import { getSenderDisplayName } from "@/lib/contacts/utils";import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";import { getMailboxAccessLevel, hasMailboxPermission, listAccessibleMailboxes } from "@/lib/mailboxes/access";import { tracksAccountIdentity } from "@/lib/profile/identity-utils";@@ -225,9 +226,9 @@ export async function GET(request: Request) {...(openCounts.has(message.id) ? { openCount: openCounts.get(message.id) } : {}),fromContactName:(message.direction === "outbound" ? accountName : null) ??- contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??- null,- toContactName: contactMap?.get(normalizeEmailAddress(getFirstEmailAddressEntry(message.toAddr))) ?? null,+ getSenderDisplayName(message.fromAddr, contactMap?.get(normalizeEmailAddress(message.fromAddr))),+ toContactName:+ contactMap?.get(normalizeEmailAddress(getFirstEmailAddressEntry(message.toAddr)))?.displayName ?? null,threadCount: threadStats?.total || 1,threadUnread: (groupByThread ? folderUnread : threadStats?.unread) || 0,...(groupByThreaddiff --git a/src/hooks/types.d.ts b/src/hooks/types.d.tsindex 7aeb490..44522d2 100644--- a/src/hooks/types.d.ts+++ b/src/hooks/types.d.ts@@ -18,6 +18,7 @@ export type Message = {bccAddr?: string | null;/** Comma-separated Reply-To list; replies go here instead of `fromAddr` when set. */replyTo?: string | null;+ /** Resolved sender label: a manually named contact, otherwise this message's From name. */fromContactName?: string | null;fromContactHasAvatar?: boolean;toContactName?: string | null;diff --git a/src/lib/contacts/service.ts b/src/lib/contacts/service.tsindex d3c64a7..99b4382 100644--- a/src/lib/contacts/service.ts+++ b/src/lib/contacts/service.ts@@ -2,8 +2,8 @@ import { and, eq, inArray } from "drizzle-orm";import { getDb } from "@/db";import { contacts, routingRules } from "@/db/schema";import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";-import type { BlockContactInput, ContactInput, MessageContactNames } from "@/lib/contacts/types";-import { getContactId, getContactNameFromAddress } from "@/lib/contacts/utils";+import type { BlockContactInput, ContactDisplayName, ContactInput, MessageContactNames } from "@/lib/contacts/types";+import { getContactId, getContactNameFromAddress, getSenderDisplayName } from "@/lib/contacts/utils";import { importGravatarAvatar } from "@/lib/contacts/gravatar";export async function upsertContactFromAddress(env: CloudflareEnv, input: ContactInput) {@@ -56,7 +56,7 @@ export async function upsertContactFromAddress(env: CloudflareEnv, input: Contacexport async function getContactDisplayNameMap(env: CloudflareEnv, userId: string, addresses: string[]) {const emails = Array.from(new Set(addresses.map(normalizeEmailAddress).filter(Boolean)));- if (emails.length === 0) return new Map<string, string>();+ if (emails.length === 0) return new Map<string, ContactDisplayName>();const db = getDb(env);const rows = await db@@ -64,11 +64,13 @@ export async function getContactDisplayNameMap(env: CloudflareEnv, userId: strin.from(contacts).where(and(eq(contacts.userId, userId), inArray(contacts.email, emails)));- return new Map(- rows- .filter((contact) => !!contact.displayName)- .map((contact) => [contact.email, contact.displayName!]),- );+ const entries = rows+ .filter((contact) => !!contact.displayName)+ .map((contact): [string, ContactDisplayName] => [+ contact.email,+ { displayName: contact.displayName!, source: contact.source },+ ]);+ return new Map(entries);}export async function getContactAvatarMap(env: CloudflareEnv, userId: string, addresses: string[]) {@@ -95,8 +97,8 @@ export async function getMessageContactNames(const contactMap = await getContactDisplayNameMap(env, userId, [fromAddr, firstTo]);return {- fromContactName: contactMap.get(normalizeEmailAddress(fromAddr)) ?? null,- toContactName: contactMap.get(normalizeEmailAddress(firstTo)) ?? null,+ fromContactName: getSenderDisplayName(fromAddr, contactMap.get(normalizeEmailAddress(fromAddr))),+ toContactName: contactMap.get(normalizeEmailAddress(firstTo))?.displayName ?? null,};}diff --git a/src/lib/contacts/types.d.ts b/src/lib/contacts/types.d.tsindex 151ee9c..1e3f96b 100644--- a/src/lib/contacts/types.d.ts+++ b/src/lib/contacts/types.d.ts@@ -18,7 +18,13 @@ export type BlockContactInput = {address: string;};+export type ContactDisplayName = {+ displayName: string;+ source: ContactSource;+};+export type MessageContactNames = {+ /** Resolved sender label: a manually named contact, otherwise the message's From name. */fromContactName: string | null;toContactName: string | null;};diff --git a/src/lib/contacts/utils.ts b/src/lib/contacts/utils.tsindex a9be60a..f9424d8 100644--- a/src/lib/contacts/utils.ts+++ b/src/lib/contacts/utils.ts@@ -1,3 +1,4 @@+import type { ContactDisplayName } from "@/lib/contacts/types";import { getEmailDisplayName, normalizeEmailAddress, parseEmailAddressParts } from "@/lib/email/address";export function getContactId(userId: string, email: string): string {@@ -13,3 +14,16 @@ export function getContactNameFromAddress(address: string): string | null {export function getDisplayNameForAddress(address: string, contactName?: string | null): string {return contactName?.trim() || getEmailDisplayName(address);}++/**+ * The sender label for one message. A name the user set on the contact wins,+ * then the message's own From header, then a name learned from other mail from+ * the same address. A shared address such as a recruiting no-reply can carry a+ * different company name on every message, so the header must beat the+ * contact's last-learned name.+ */+export function getSenderDisplayName(address: string, contact?: ContactDisplayName | null): string | null {+ const contactName = contact?.displayName.trim() || null;+ if (contact?.source === "manual" && contactName) return contactName;+ return getContactNameFromAddress(address) ?? contactName;+}diff --git a/src/lib/email/thread-view.ts b/src/lib/email/thread-view.tsindex f057abe..99352db 100644--- a/src/lib/email/thread-view.ts+++ b/src/lib/email/thread-view.ts@@ -2,6 +2,7 @@ import { and, asc, eq, inArray, isNull, ne, notInArray, or } from "drizzle-orm";import { getDb } from "@/db";import { messageAttachments, messages } from "@/db/schema";import { getContactAvatarMap, getContactDisplayNameMap } from "@/lib/contacts/service";+import { getSenderDisplayName } from "@/lib/contacts/utils";import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import type { SessionUser } from "@/lib/auth/types";@@ -84,9 +85,10 @@ export async function getMessageThreadForUser(env: CloudflareEnv, user: SessionUthreadId: message.threadId,messages: rows.map((row) => ({...withoutRawKey(row),- fromContactName: contactMap.get(normalizeEmailAddress(row.fromAddr)) ?? null,+ fromContactName: getSenderDisplayName(row.fromAddr, contactMap.get(normalizeEmailAddress(row.fromAddr))),fromContactHasAvatar: contactAvatarMap.get(normalizeEmailAddress(row.fromAddr)) ?? false,- toContactName: contactMap.get(normalizeEmailAddress(getFirstEmailAddressEntry(row.toAddr))) ?? null,+ toContactName:+ contactMap.get(normalizeEmailAddress(getFirstEmailAddressEntry(row.toAddr)))?.displayName ?? null,attachments: attachmentsByMessage.get(row.id) ?? [],})),};diff --git a/tests/messages-route-performance.test.mjs b/tests/messages-route-performance.test.mjsindex f607edc..22d2723 100644--- a/tests/messages-route-performance.test.mjs+++ b/tests/messages-route-performance.test.mjs@@ -73,15 +73,15 @@ async function fixture(t) {async contacts(userId, addresses) {await this.read(`contacts:${userId}`);assert.ok(addresses.includes("[email protected]"));- return new Map([["[email protected]", `Friend of ${userId}`]]);+ return new Map([["[email protected]", { displayName: `Friend of ${userId}`, source: "inbound" }]]);},async opens(ids) {await this.read("opens");return new Map(ids.map((id) => [id, 3]));},- message(id, { mailbox = "mine", user = "owner", thread = "thread", status = "received", direction = "inbound", read = false, time = 1 } = {}) {+ message(id, { mailbox = "mine", user = "owner", thread = "thread", status = "received", direction = "inbound", read = false, time = 1, fromAddr = "[email protected]" } = {}) {database.db.prepare(`INSERT INTO messages (id, user_id, mailbox_id, direction, from_addr, to_addr, status, read, thread_id, snippet, text_body, html_body, raw_r2_key, created_at)- VALUES (?, ?, ?, ?, '[email protected]', '[email protected]', ?, ?, ?, 'preview', 'private body', '<p>private</p>', 'raw-key', ?)`).run(id, user, mailbox, direction, status, Number(read), thread, time);+ VALUES (?, ?, ?, ?, ?, '[email protected]', ?, ?, ?, 'preview', 'private body', '<p>private</p>', 'raw-key', ?)`).run(id, user, mailbox, direction, fromAddr, status, Number(read), thread, time);},};const prepare = database.prepare.bind(database);@@ -234,6 +234,24 @@ test("all-mailbox lists keep per-owner contacts and reflect revoked sharing on tassert.equal((await GET(request("mailboxId=shared"))).status, 404);});+test("a shared sender address keeps each message's own display name", async (t) => {+ const f = await fixture(t);+ f.message("posthog", { fromAddr: '"PostHog Team" <[email protected]>', time: 1 });+ f.message("livekit", { fromAddr: '"LiveKit Hiring Team" <[email protected]>', time: 2 });+ // The contact learned the most recent sender's name for the shared address.+ f.contacts = async () => new Map([["[email protected]", { displayName: "LiveKit Hiring Team", source: "inbound" }]]);+ const body = await (await GET(request("mailboxId=mine"))).json();+ assert.deepEqual(body.messages.map((row) => [row.id, row.fromContactName]), [+ ["livekit", "LiveKit Hiring Team"],+ ["posthog", "PostHog Team"],+ ]);++ // A name the user set on the contact is deliberate and wins for every message.+ f.contacts = async () => new Map([["[email protected]", { displayName: "Ashby Recruiting", source: "manual" }]]);+ const manual = await (await GET(request("mailboxId=mine"))).json();+ assert.deepEqual(manual.messages.map((row) => row.fromContactName), ["Ashby Recruiting", "Ashby Recruiting"]);+});+test("empty pages preserve total and skip unnecessary thread and scheduled reads", async (t) => {const f = await fixture(t);schedule(f);diff --git a/tests/recipient-display.test.mjs b/tests/recipient-display.test.mjsindex 727ee85..8742e4f 100644--- a/tests/recipient-display.test.mjs+++ b/tests/recipient-display.test.mjs@@ -30,6 +30,7 @@ async function bundle(entry, outfile) {const display = await bundle("src/lib/email/recipient-display.ts", "display.mjs");const thread = await bundle("src/components/messages/conversation-thread-utils.ts", "thread.mjs");+const contacts = await bundle("src/lib/contacts/utils.ts", "contacts.mjs");const parties = await bundle("src/app/(dashboard)/inbox/[messageId]/utils.ts", "parties.mjs");const validators = await bundle("src/lib/validators.ts", "validators.mjs");@@ -93,6 +94,30 @@ test("outbound To still prefers the contact name", () => {assert.equal(header.toName, "Ada Lovelace");});+test("a message's own From name beats a shared contact's learned name", () => {+ const shared = { displayName: "LiveKit Hiring Team", source: "inbound" };+ assert.equal(contacts.getSenderDisplayName('"PostHog Team" <[email protected]>', shared), "PostHog Team");+ assert.equal(+ contacts.getSenderDisplayName('"LiveKit Hiring Team" <[email protected]>', { displayName: "PostHog Team", source: "outbound" }),+ "LiveKit Hiring Team",+ );+});++test("a manually named contact overrides the message's From name", () => {+ assert.equal(+ contacts.getSenderDisplayName('"PostHog Team" <[email protected]>', { displayName: "Ashby Recruiting", source: "manual" }),+ "Ashby Recruiting",+ );+});++test("the learned contact name fills in when the message has no From name", () => {+ assert.equal(+ contacts.getSenderDisplayName("[email protected]", { displayName: "PostHog Team", source: "inbound" }),+ "PostHog Team",+ );+ assert.equal(contacts.getSenderDisplayName("[email protected]", null), null);+});+test("the setting accepts only a boolean", () => {assert.equal(validators.updateRecipientAddressSettingsSchema.parse({ enabled: true }).enabled, true);assert.equal(validators.updateRecipientAddressSettingsSchema.parse({ enabled: false }).enabled, false);