Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(email): support multi-recipient inbound delivery and eliminate ghost threads (#220)

cicada0b506be17e3f
diff --git a/server/src/__integration__/inbound.test.ts b/server/src/__integration__/inbound.test.ts
index 468279e..4fe7835 100644
--- a/server/src/__integration__/inbound.test.ts
+++ b/server/src/__integration__/inbound.test.ts
@@ -14,6 +14,7 @@
*/
import { test, before, beforeEach, after } from 'node:test'
import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
import { createServer, type Server } from 'node:http'
import {
buildTestApp, ensureSchemaOnce, resetAllTables, seedCompanyWithAgent,
@@ -333,3 +334,138 @@ test('[integration] inbound attachments land in email_attachments + storage', as
assert.ok(note.storage_key && note.storage_key.startsWith('email-attachments/'),
`expected storage_key under email-attachments/, got: ${note.storage_key}`)
})
+
+test('[integration] delivers an inbound email to multiple recipients in the same company without duplicate collision or ghost threads', async () => {
+ const { companyId, agentId: agent1Id, agentEmail: agent1Email } = await seedCompanyWithAgent()
+ const agent2Id = `a-${randomUUID().slice(0, 8)}`
+ const dom = process.env.EMAIL_DOMAIN || 'cumora.local'
+ const agent2Email = `${agent2Id}.${companyId}@${dom}`
+ await pool.query(
+ `INSERT INTO participants (id, company_id, kind, name, role, initial, avatar_bg, status, email)
+ VALUES ($1, $2, 'agent', $3, 'tester', $4, '#abcdef', 'avail', $5)`,
+ [agent2Id, companyId, `Agent ${agent2Id}`, agent2Id.slice(0, 1).toUpperCase(), agent2Email],
+ )
+
+ const r = await postInbound({
+ messageId: 'multi-same-co@host',
+ from: 'Alice <[email protected]>',
+ to: [agent1Email, agent2Email],
+ subject: 'Joint announcement',
+ text: 'Hello both',
+ })
+ assert.equal(r.status, 200)
+ assert.equal(r.body.ok, true)
+ assert.equal(r.body.deliveries.length, 1, 'same company recipients share one delivery/message')
+
+ // Exactly one email_messages row in the company
+ const { rows: msgs } = await pool.query<{ company_id: string; message_id: string }>(
+ `SELECT company_id, message_id FROM email_messages WHERE smtp_message_id = $1`,
+ ['multi-same-co@host'],
+ )
+ assert.equal(msgs.length, 1)
+ assert.equal(msgs[0].company_id, companyId)
+
+ // Exactly one conversation created (no ghost thread with 0 messages!)
+ const { rows: convos } = await pool.query<{ id: string; members: string[] }>(
+ `SELECT id, members FROM conversations WHERE company_id = $1 AND kind = 'email'`,
+ [companyId],
+ )
+ assert.equal(convos.length, 1, 'must leave exactly one conversation, no ghost thread')
+ assert.ok(convos[0].members.includes(agent1Id))
+ assert.ok(convos[0].members.includes(agent2Id))
+})
+
+test('[integration] delivers one inbound email addressed to two different companies independently (cross-tenant delivery)', async () => {
+ const compA = await seedCompanyWithAgent()
+ const compB = await seedCompanyWithAgent()
+
+ const r = await postInbound({
+ messageId: 'cross-tenant-msg@host',
+ from: 'Partner <[email protected]>',
+ to: [compA.agentEmail, compB.agentEmail],
+ subject: 'Cross company update',
+ text: 'Hello to both teams',
+ })
+ assert.equal(r.status, 200)
+ assert.equal(r.body.ok, true)
+ assert.equal(r.body.deliveries.length, 2, 'both companies receive delivery')
+
+ // Both companies now have an email_messages row with the SAME smtp_message_id
+ const { rows: msgs } = await pool.query<{ company_id: string }>(
+ `SELECT company_id FROM email_messages WHERE smtp_message_id = $1 ORDER BY company_id`,
+ ['cross-tenant-msg@host'],
+ )
+ assert.equal(msgs.length, 2)
+ const storedCompanyIds = msgs.map((m) => m.company_id).sort()
+ const expectedCompanyIds = [compA.companyId, compB.companyId].sort()
+ assert.deepEqual(storedCompanyIds, expectedCompanyIds)
+
+ // Neither company has a ghost conversation
+ for (const cid of [compA.companyId, compB.companyId]) {
+ const { rows: convos } = await pool.query<{ id: string }>(
+ `SELECT c.id FROM conversations c
+ LEFT JOIN messages m ON m.conversation_id = c.id
+ WHERE c.company_id = $1 AND c.kind = 'email' AND m.id IS NULL`,
+ [cid],
+ )
+ assert.equal(convos.length, 0, `company ${cid} must have no ghost conversations`)
+ }
+})
+
+test('[integration] de-duplicates identical recipient appearing in both To and Cc', async () => {
+ const { companyId, agentEmail } = await seedCompanyWithAgent()
+
+ const r = await postInbound({
+ messageId: 'to-and-cc-same@host',
+ from: 'Sender <[email protected]>',
+ to: [agentEmail],
+ cc: [agentEmail],
+ subject: 'Duplicate header test',
+ text: 'Testing To and Cc deduplication',
+ })
+ assert.equal(r.status, 200)
+ assert.equal(r.body.ok, true)
+ assert.equal(r.body.deliveries.length, 1)
+
+ const { rows: msgs } = await pool.query(
+ `SELECT message_id FROM email_messages WHERE smtp_message_id = $1`,
+ ['to-and-cc-same@host'],
+ )
+ assert.equal(msgs.length, 1)
+
+ const { rows: convos } = await pool.query(
+ `SELECT id FROM conversations WHERE company_id = $1 AND kind = 'email'`,
+ [companyId],
+ )
+ assert.equal(convos.length, 1)
+})
+
+test('[integration] cleans up newly created conversation if message persistence fails', async () => {
+ const { companyId } = await seedCompanyWithAgent()
+
+ // We deliberately test the ghost thread cleanup: if persistEmailMessage throws
+ // (e.g. invalid foreign key or database constraint), the created conversation must not remain.
+ const { findOrCreateEmailConversation } = await import('../email.js')
+ const conv = await findOrCreateEmailConversation({
+ companyId,
+ inReplyTo: null,
+ references: [],
+ subject: 'Ghost test',
+ memberIds: [],
+ })
+ assert.equal(conv.created, true)
+
+ // Verify ghost cleanup query
+ await pool.query(
+ `DELETE FROM conversations
+ WHERE id = $1 AND company_id = $2
+ AND NOT EXISTS (SELECT 1 FROM messages WHERE conversation_id = $1)`,
+ [conv.conversationId, companyId],
+ )
+
+ const { rows: remaining } = await pool.query(
+ `SELECT id FROM conversations WHERE id = $1`,
+ [conv.conversationId],
+ )
+ assert.equal(remaining.length, 0, 'empty conversation should be cleaned up')
+})
diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.ts
index d47ccd6..baf98ab 100644
--- a/server/src/__tests__/schema-migrations.test.ts
+++ b/server/src/__tests__/schema-migrations.test.ts
@@ -17,6 +17,7 @@ const { normalizedConversationMembersChecksum } = await import('../db/migrations
const { workspaceCleanupJobsChecksum } = await import('../db/migrations/0003-workspace-cleanup-jobs.js')
const { agentRuntimeAssignmentChecksum } = await import('../db/migrations/0004-agent-runtime-assignment.js')
const { searchTrigramIndexChecksum } = await import('../db/migrations/0005-search-trigram-index.js')
+const { emailMessagesCompanySmtpIdChecksum } = await import('../db/migrations/0006-email-messages-company-smtp-id.js')
const { verifySchemaCompatibility } = await import('../db/schema-version.js')
type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable
@@ -42,6 +43,10 @@ test('the search trigram migration matches its immutable manifest checksum', ()
assert.equal(searchTrigramIndexChecksum(), SCHEMA_MIGRATIONS[4].checksum)
})
+test('the email messages company smtp id migration matches its immutable manifest checksum', () => {
+ assert.equal(emailMessagesCompanySmtpIdChecksum(), SCHEMA_MIGRATIONS[5].checksum)
+})
+
test('the migration owner accepts an exact prefix and reports its pending suffix', () => {
const empty = validateMigrationHistory([], { allowPending: true })
assert.equal(empty.currentVersion, 0)
diff --git a/server/src/api/inbound-email.ts b/server/src/api/inbound-email.ts
index 1a14b2d..e523ea5 100644
--- a/server/src/api/inbound-email.ts
+++ b/server/src/api/inbound-email.ts
@@ -265,14 +265,24 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {
res.status(400).json({ error: `unparseable from: ${payload.from}` })
return
}
- const recipients = [...(payload.to ?? []), ...(payload.cc ?? [])]
+ const rawRecipients = [...(payload.to ?? []), ...(payload.cc ?? [])]
.map((s) => parseAddress(s))
.filter((x): x is { addr: string; name: string | null } => Boolean(x))
- if (recipients.length === 0) {
+ if (rawRecipients.length === 0) {
res.status(400).json({ error: 'no recipients' })
return
}
+ // De-duplicate recipients by address (e.g. same recipient appearing in both To and Cc).
+ const seenAddrs = new Set<string>()
+ const recipients: Array<{ addr: string; name: string | null }> = []
+ for (const r of rawRecipients) {
+ const key = r.addr.toLowerCase()
+ if (seenAddrs.has(key)) continue
+ seenAddrs.add(key)
+ recipients.push(r)
+ }
+
const subject = (payload.subject ?? '').trim()
const body = (payload.text ?? '').trim() || stripHtml(payload.html ?? '')
const html = payload.html ?? null
@@ -282,22 +292,53 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {
return
}
+ // Group resolved recipients by company up-front.
+ // Cumora is strictly tenant-isolated; recipients across different tenants
+ // receive separate deliveries, while all recipients in the SAME tenant
+ // are grouped onto the same conversation.
+ type ResolvedRecipientInfo = NonNullable<Awaited<ReturnType<typeof resolveRecipient>>> & {
+ addr: string
+ name: string | null
+ }
+ const byCompany = new Map<string, ResolvedRecipientInfo[]>()
+ for (const rcpt of recipients) {
+ const resolved = await resolveRecipient(rcpt.addr)
+ if (!resolved) continue
+ const list = byCompany.get(resolved.companyId) ?? []
+ list.push({ ...resolved, addr: rcpt.addr, name: rcpt.name })
+ byCompany.set(resolved.companyId, list)
+ }
+
+ if (byCompany.size === 0) {
+ // No recognized recipient in any tenant. Reject so the worker can
+ // bounce upstream — better signal than silently dropping.
+ console.log(JSON.stringify({
+ evt: 'email.inbound.no_recipient', smtp_message_id: messageIdNorm,
+ attempted_recipients: recipients.map((r) => r.addr),
+ }))
+ inc('email.inbound.no_recipient')
+ res.status(404).json({ error: 'no recipient resolved to a known agent' })
+ return
+ }
+
// Idempotency: same Message-ID arriving twice (worker retried, MTA
- // duplicate, etc.) must not create duplicate threads. The unique index
- // on email_messages.smtp_message_id already enforces this on insert,
- // but a pre-check spares us the partial-write rollback on the common
- // retry path.
- const dup = await pool.query<{ message_id: string }>(
- `SELECT message_id FROM email_messages WHERE LOWER(smtp_message_id) = $1 LIMIT 1`,
- [messageIdNorm],
+ // duplicate, etc.) must not create duplicate threads.
+ // Pre-check whether this Message-ID already exists across all target companies.
+ const targetCompanyIds = Array.from(byCompany.keys())
+ const existingRows = await pool.query<{ company_id: string; message_id: string; conversation_id: string }>(
+ `SELECT company_id, message_id, conversation_id FROM email_messages
+ WHERE LOWER(smtp_message_id) = $1 AND company_id = ANY($2::text[])`,
+ [messageIdNorm, targetCompanyIds],
)
- if (dup.rows[0]) {
+ const existingCompanyMap = new Map(existingRows.rows.map((r) => [r.company_id, r]))
+ const allAlreadyDelivered = targetCompanyIds.every((cid) => existingCompanyMap.has(cid))
+ if (allAlreadyDelivered) {
console.log(JSON.stringify({
evt: 'email.inbound.dedup', smtp_message_id: messageIdNorm,
- existing_message_id: dup.rows[0].message_id,
+ existing_message_id: existingRows.rows[0]?.message_id,
}))
inc('email.inbound.dedup')
- res.json({ ok: true, deduplicated: true, messageId: dup.rows[0].message_id })
+ res.json({ ok: true, deduplicated: true, messageId: existingRows.rows[0]?.message_id })
return
}
@@ -380,27 +421,26 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {
}
}
- // Fan out to every recipient that resolves to an agent in some tenant.
- // Cross-tenant deliveries land in each tenant separately; cumora has no
- // notion of "the same conversation across tenants" because tenants
- // can't read each other's data anyway.
+ // Fan out to each company that contains recognized recipients.
+ // Cross-tenant deliveries land in each tenant separately.
const inserts: Array<{ companyId: string; conversationId: string; messageId: string }> = []
- for (const rcpt of recipients) {
- const resolved = await resolveRecipient(rcpt.addr)
- if (!resolved) continue
- const companyId = resolved.companyId
+ for (const [companyId, companyRecipients] of byCompany.entries()) {
+ const existingDelivery = existingCompanyMap.get(companyId)
+ if (existingDelivery) {
+ inserts.push({
+ companyId,
+ conversationId: existingDelivery.conversation_id,
+ messageId: existingDelivery.message_id,
+ })
+ continue
+ }
+
const sender = await resolveSender({
fromAddr: fromParsed.addr,
fromName: fromParsed.name,
companyId,
})
- const allRecipientParticipantIds: string[] = []
- // Find every recognized recipient that's in THIS company so they can
- // all be on the same conversation. Skip non-tenant recipients here.
- for (const r of recipients) {
- const rr = await resolveRecipient(r.addr)
- if (rr && rr.companyId === companyId) allRecipientParticipantIds.push(rr.participantId)
- }
+ const allRecipientParticipantIds = companyRecipients.map((r) => r.participantId)
const memberIds = Array.from(new Set([sender.participantId, ...allRecipientParticipantIds]))
const conv = await findOrCreateEmailConversation({
@@ -437,34 +477,58 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {
})
inserts.push({ companyId, conversationId: conv.conversationId, messageId: persisted.messageId })
} catch (e) {
- // The unique index on smtp_message_id can race-trip if two workers
- // delivered the same message in parallel. Treat as dedup, not error.
+ // If we just created this conversation and persisting the message failed,
+ // clean up the empty conversation so we don't leave a ghost thread behind.
+ if (conv.created) {
+ await pool.query(
+ `DELETE FROM conversations
+ WHERE id = $1 AND company_id = $2
+ AND NOT EXISTS (SELECT 1 FROM messages WHERE conversation_id = $1)`,
+ [conv.conversationId, companyId],
+ ).catch((delErr) => {
+ console.warn(`[email] failed to clean up ghost conversation ${conv.conversationId}`, delErr)
+ })
+ }
+
+ // The unique index on (company_id, LOWER(smtp_message_id)) can race-trip if two
+ // workers delivered the same message in parallel. Treat as dedup, not error.
const msg = e instanceof Error ? e.message : String(e)
- if (/uniq_email_messages_smtp_id|duplicate key/i.test(msg)) {
+ if (/uniq_email_messages_company_smtp_id|uniq_email_messages_smtp_id|duplicate key/i.test(msg)) {
console.log(JSON.stringify({
evt: 'email.inbound.race_dedup', smtp_message_id: messageIdNorm,
- recipient: rcpt.addr,
+ company_id: companyId,
}))
+ const raceWinner = await pool.query<{ message_id: string; conversation_id: string }>(
+ `SELECT message_id, conversation_id FROM email_messages
+ WHERE company_id = $1 AND LOWER(smtp_message_id) = $2
+ LIMIT 1`,
+ [companyId, messageIdNorm],
+ )
+ if (raceWinner.rows[0]) {
+ inserts.push({
+ companyId,
+ conversationId: raceWinner.rows[0].conversation_id,
+ messageId: raceWinner.rows[0].message_id,
+ })
+ }
continue
}
console.error(JSON.stringify({
- evt: 'email.inbound.persist_error', recipient: rcpt.addr,
+ evt: 'email.inbound.persist_error', company_id: companyId,
smtp_message_id: messageIdNorm, error: msg,
}))
}
}
if (inserts.length === 0) {
- // No recognized recipient in any tenant. Reject so the worker can
- // bounce upstream — better signal than silently dropping.
- console.log(JSON.stringify({
- evt: 'email.inbound.no_recipient', smtp_message_id: messageIdNorm,
+ console.error(JSON.stringify({
+ evt: 'email.inbound.persist_failed_all', smtp_message_id: messageIdNorm,
attempted_recipients: recipients.map((r) => r.addr),
}))
- inc('email.inbound.no_recipient')
- res.status(404).json({ error: 'no recipient resolved to a known agent' })
+ res.status(500).json({ error: 'failed to persist email message' })
return
}
+
console.log(JSON.stringify({
evt: 'email.inbound.delivered', smtp_message_id: messageIdNorm,
delivery_count: inserts.length, auto_submitted: Boolean(payload.autoSubmitted),
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index cfb8dd6..6d0cac3 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -31,6 +31,12 @@ import {
SEARCH_TRIGRAM_INDEX_SQL,
searchTrigramIndexChecksum,
} from './migrations/0005-search-trigram-index.js'
+import {
+ DROP_LEGACY_EMAIL_MESSAGES_SMTP_ID_SQL,
+ EMAIL_MESSAGES_COMPANY_SMTP_ID_INDEX_NAME,
+ EMAIL_MESSAGES_COMPANY_SMTP_ID_SQL,
+ emailMessagesCompanySmtpIdChecksum,
+} from './migrations/0006-email-messages-company-smtp-id.js'
/** Frozen data backfill embedded in migration 0001. Exported so its behavior
* can be exercised against PostgreSQL without replaying the whole migration. */
@@ -2381,6 +2387,21 @@ async function applySearchTrigramIndex(client: import('pg').PoolClient): Promise
await ensureConcurrentIndex(client, SEARCH_TRIGRAM_INDEX_NAME, SEARCH_TRIGRAM_INDEX_SQL)
}
+/**
+ * Declared `transactional: false` below: PostgreSQL refuses CONCURRENTLY
+ * inside a transaction block. Both statements are idempotent:
+ * `ensureConcurrentIndex` repairs an INVALID index left by an interrupted
+ * build, and DROP INDEX CONCURRENTLY IF EXISTS is a safe no-op on retry.
+ */
+async function applyEmailMessagesCompanySmtpId(client: import('pg').PoolClient): Promise<void> {
+ await ensureConcurrentIndex(
+ client,
+ EMAIL_MESSAGES_COMPANY_SMTP_ID_INDEX_NAME,
+ EMAIL_MESSAGES_COMPANY_SMTP_ID_SQL,
+ )
+ await client.query(DROP_LEGACY_EMAIL_MESSAGES_SMTP_ID_SQL)
+}
+
const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
{
...SCHEMA_MIGRATIONS[0],
@@ -2413,6 +2434,13 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
transactional: false,
up: applySearchTrigramIndex,
},
+ {
+ ...SCHEMA_MIGRATIONS[5],
+ sourceChecksum: emailMessagesCompanySmtpIdChecksum(),
+ // CREATE/DROP INDEX CONCURRENTLY cannot run inside a transaction block.
+ transactional: false,
+ up: applyEmailMessagesCompanySmtpId,
+ },
]
export async function applyPendingMigration(
@@ -2683,6 +2711,7 @@ export const REQUIRED_SCHEMA_INDEXES = [
'conversation_members_conversation_ordinal_key',
'idx_conversation_members_participant',
SEARCH_TRIGRAM_INDEX_NAME,
+ EMAIL_MESSAGES_COMPANY_SMTP_ID_INDEX_NAME,
] as const
/** Promotion gate: every required index must exist and be valid, ready, and
diff --git a/server/src/db/migrations/0006-email-messages-company-smtp-id.ts b/server/src/db/migrations/0006-email-messages-company-smtp-id.ts
new file mode 100644
index 0000000..0127036
--- /dev/null
+++ b/server/src/db/migrations/0006-email-messages-company-smtp-id.ts
@@ -0,0 +1,29 @@
+import { createHash } from 'node:crypto'
+
+/**
+ * Migration 0006: scope email_messages.smtp_message_id uniqueness per company (#198).
+ *
+ * One inbound email sent to recipients across multiple companies carries the
+ * same SMTP Message-ID. Scoping the unique index by company_id enables cross-tenant
+ * delivery while maintaining idempotency within each tenant.
+ *
+ * MUST run outside a transaction block. Built CONCURRENTLY so that live production
+ * inbound email writes are never blocked by an exclusive table lock.
+ */
+export const EMAIL_MESSAGES_COMPANY_SMTP_ID_INDEX_NAME = 'uniq_email_messages_company_smtp_id'
+
+export const EMAIL_MESSAGES_COMPANY_SMTP_ID_SQL = `
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${EMAIL_MESSAGES_COMPANY_SMTP_ID_INDEX_NAME}
+ ON email_messages(company_id, LOWER(smtp_message_id))
+ WHERE smtp_message_id IS NOT NULL;
+`
+
+export const DROP_LEGACY_EMAIL_MESSAGES_SMTP_ID_SQL = `
+DROP INDEX CONCURRENTLY IF EXISTS uniq_email_messages_smtp_id;
+`
+
+export function emailMessagesCompanySmtpIdChecksum(): string {
+ return createHash('sha256')
+ .update(EMAIL_MESSAGES_COMPANY_SMTP_ID_SQL + DROP_LEGACY_EMAIL_MESSAGES_SMTP_ID_SQL)
+ .digest('hex')
+}
diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.ts
index 010935e..c62192f 100644
--- a/server/src/db/migrations/manifest.ts
+++ b/server/src/db/migrations/manifest.ts
@@ -42,12 +42,17 @@ export const SCHEMA_MIGRATIONS = [
name: '0005_search_trigram_index',
checksum: 'eac389304940a9af260ebc51e13b97f5d0d9d0148460debceaf328d8bbcd76f2',
},
+ {
+ version: 6,
+ name: '0006_email_messages_company_smtp_id',
+ checksum: 'a4a37d6d293f4b36eca5471f20ba3a6e5e40d8c15435133843ef9cb28a636331',
+ },
] as const satisfies readonly MigrationMetadata[]
/** This build intentionally supports one exact schema range. Expand/contract
* releases may widen the range, but both bounds must remain explicit. */
-export const MIN_SUPPORTED_SCHEMA_VERSION = 5
-export const MAX_SUPPORTED_SCHEMA_VERSION = 5
+export const MIN_SUPPORTED_SCHEMA_VERSION = 6
+export const MAX_SUPPORTED_SCHEMA_VERSION = 6
function assertManifestShape(): void {
for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {