Skip to content

📧✨ Beautiful email. For everyone.

fix: deduplicate Gmail messages across IMAP folders (#33)

Paul Koeck9c184bbaaef8
diff --git a/apps/desktop/src/main/imap-index/sqlite-index.ts b/apps/desktop/src/main/imap-index/sqlite-index.ts
index 4e8a396..fe30750 100644
--- a/apps/desktop/src/main/imap-index/sqlite-index.ts
+++ b/apps/desktop/src/main/imap-index/sqlite-index.ts
@@ -49,7 +49,7 @@ const methodTable: Record<keyof MetadataIndex, true> = {
}
export const indexMethods = Object.keys(methodTable) as (keyof MetadataIndex)[]
-export const SCHEMA_VERSION = 1
+export const SCHEMA_VERSION = 2
const MAX_REFERENCES = 50
const migrations = [
@@ -137,6 +137,10 @@ const migrations = [
value TEXT NOT NULL,
PRIMARY KEY (account_id, key)
) WITHOUT ROWID;`,
+ `ALTER TABLE messages ADD COLUMN email_id TEXT;
+ CREATE INDEX messages_email_id ON messages (account_id, email_id) WHERE email_id IS NOT NULL;
+ -- Refresh metadata for existing locations without discarding their stable IDs or threads.
+ UPDATE mailboxes SET uid_next = NULL, highest_modseq = NULL, indexed_from = NULL, complete = 0;`,
]
interface MailboxRow {
@@ -165,6 +169,7 @@ interface MessageRow {
uid: number
modseq: string | null
message_id: string | null
+ email_id: string | null
in_reply_to: string
refs: string
thread_id: string
@@ -247,13 +252,14 @@ function toMessage(row: MessageRow): IndexedMessage {
preview: row.preview,
}
if (row.modseq !== null) message.modseq = row.modseq
+ if (row.email_id !== null) message.emailId = row.email_id
if (row.sent_at !== null) message.sentAt = row.sent_at
if (row.body_structure !== null) message.bodyStructure = JSON.parse(row.body_structure)
if (row.unsubscribe !== null) message.unsubscribe = JSON.parse(row.unsubscribe)
return message
}
-const MESSAGE_COLUMNS = `seq, id, mailbox_id, uid_validity, uid, modseq, message_id, in_reply_to, refs,
+const MESSAGE_COLUMNS = `seq, id, mailbox_id, uid_validity, uid, modseq, message_id, email_id, in_reply_to, refs,
thread_id, subject, from_addr, to_addr, cc_addr, bcc_addr, reply_to, received_at, sent_at, size,
flags, has_attachment, preview, body_structure, unsubscribe`
@@ -531,17 +537,25 @@ export class SqliteMetadataIndex implements SyncMetadataIndex {
}
/**
- * Finds every thread already known for the message's own ID or its parents. Several threads
- * mean the message links them, so they merge into the oldest; the others become aliases.
+ * Finds every thread already known for the server identity, Message-ID or parents. Several
+ * threads mean the message links them, so they merge into the oldest; others become aliases.
*/
- private assignThread(accountId: string, keys: string[]) {
- if (!keys.length) return this.newThread(accountId)
+ private assignThread(accountId: string, keys: string[], emailId?: string) {
+ if (!keys.length && !emailId) return this.newThread(accountId)
+ // UNION's ordering can make SQLite prefer a scan of the account's thread index. Force
+ // the server-identity lookup to stay bounded as the mailbox grows.
const found = this.all<{ id: string; seq: number | null }>(
- `SELECT DISTINCT r.thread_id AS id, t.seq AS seq FROM json_each(?) j
- CROSS JOIN thread_refs r ON r.account_id = ? AND r.message_id = j.value
- LEFT JOIN threads t ON t.account_id = r.account_id AND t.id = r.thread_id`,
+ `SELECT DISTINCT r.thread_id AS id, t.seq AS seq FROM (
+ SELECT r.thread_id FROM json_each(?) j
+ CROSS JOIN thread_refs r ON r.account_id = ? AND r.message_id = j.value
+ UNION SELECT thread_id FROM messages INDEXED BY messages_email_id
+ WHERE account_id = ? AND email_id = ?
+ ) r LEFT JOIN threads t ON t.account_id = ? AND t.id = r.thread_id`,
list(keys),
accountId,
+ accountId,
+ emailId ?? null,
+ accountId,
)
found.sort((a, b) => (a.seq ?? Infinity) - (b.seq ?? Infinity) || (a.id < b.id ? -1 : 1))
const thread = found[0]?.id ?? this.newThread(accountId)
@@ -601,15 +615,28 @@ export class SqliteMetadataIndex implements SyncMetadataIndex {
if (existing) {
this.run(
`UPDATE messages SET flags = ?, seen = ?, flagged = ?, modseq = coalesce(?, modseq),
+ email_id = coalesce(?, email_id),
preview = CASE WHEN ? <> '' THEN ? ELSE preview END WHERE id = ?`,
list(message.flags),
seen,
flagged,
message.modseq ?? null,
+ message.emailId ?? null,
message.preview,
message.preview,
existing.id,
)
+ // Backfilling the server identity can join locations whose headers lacked Message-ID.
+ if (message.emailId)
+ this.assignThread(
+ accountId,
+ messageIds([
+ message.messageId,
+ ...message.inReplyTo,
+ ...message.references.slice(-MAX_REFERENCES),
+ ]),
+ message.emailId,
+ )
return existing.id
}
const [messageId = null] = messageIds([message.messageId])
@@ -617,14 +644,18 @@ export class SqliteMetadataIndex implements SyncMetadataIndex {
const parents = messageIds([...message.inReplyTo, ...references]).filter(
(id) => id !== messageId,
)
- const threadId = this.assignThread(accountId, messageId ? [messageId, ...parents] : parents)
+ const threadId = this.assignThread(
+ accountId,
+ messageId ? [messageId, ...parents] : parents,
+ message.emailId,
+ )
const id = randomUUID()
this.run(
`INSERT INTO messages (id, account_id, mailbox_id, uid_validity, uid, modseq, message_id,
in_reply_to, refs, thread_id, subject, from_addr, to_addr, cc_addr, bcc_addr, reply_to,
received_at, received_ms, sent_at, size, flags, seen, flagged, has_attachment, preview,
- body_structure, unsubscribe)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ body_structure, unsubscribe, email_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
id,
accountId,
message.mailboxId,
@@ -652,6 +683,7 @@ export class SqliteMetadataIndex implements SyncMetadataIndex {
message.preview,
message.bodyStructure ? json(message.bodyStructure) : null,
message.unsubscribe ? json(message.unsubscribe) : null,
+ message.emailId ?? null,
)
return id
})
@@ -899,7 +931,8 @@ export class SqliteMetadataIndex implements SyncMetadataIndex {
)
const counts = new Map(
this.all<{ thread_id: string; n: number }>(
- `SELECT thread_id, count(*) AS n FROM messages WHERE account_id = ?
+ `SELECT thread_id, count(DISTINCT email_id) + sum(email_id IS NULL) AS n
+ FROM messages WHERE account_id = ?
AND thread_id IN (SELECT value FROM json_each(?)) GROUP BY thread_id`,
accountId,
list(picked.map(([thread]) => thread)),
diff --git a/packages/imap/src/convert.ts b/packages/imap/src/convert.ts
index a9adabc..9f4f6aa 100644
--- a/packages/imap/src/convert.ts
+++ b/packages/imap/src/convert.ts
@@ -173,6 +173,7 @@ export function toNewMessage(
return {
...location,
uid: fetched.uid,
+ emailId: fetched.emailId,
modseq: fetched.modseq,
messageId: messageIds(env.messageId)[0] ?? null,
inReplyTo,
diff --git a/packages/imap/src/imapflow-port.ts b/packages/imap/src/imapflow-port.ts
index 261f87f..bfb7c3a 100644
--- a/packages/imap/src/imapflow-port.ts
+++ b/packages/imap/src/imapflow-port.ts
@@ -276,6 +276,7 @@ export class ImapFlowPort implements ImapPort {
: undefined
result.push({
uid: m.uid,
+ emailId: m.emailId,
modseq: m.modseq?.toString(),
flags: m.flags ? [...m.flags] : undefined,
envelope,
diff --git a/packages/imap/src/metadata-index.ts b/packages/imap/src/metadata-index.ts
index 750a974..2f83e90 100644
--- a/packages/imap/src/metadata-index.ts
+++ b/packages/imap/src/metadata-index.ts
@@ -31,7 +31,8 @@ export interface MetadataIndex {
/**
* Inserts or updates messages by location. A new location gets a new ID and a thread; an
- * existing location keeps its ID and only has flags, modseq and preview refreshed.
+ * existing location keeps its ID and has flags, modseq, preview and server identity refreshed.
+ * Server identity may join threads, but never replaces a location used for mutations.
* Returns the ID for each input, in order.
*/
upsertMessages(accountId: string, messages: NewMessage[]): Promise<string[]>
@@ -126,6 +127,8 @@ export interface MessageLocation {
export interface NewMessage extends MessageLocation {
modseq?: string
+ /** Account-wide server identity; unlike Message-ID, safe for display deduplication. */
+ emailId?: string
/** Without angle brackets. `null` when the header is missing or unusable. */
messageId: string | null
inReplyTo: string[]
@@ -191,6 +194,6 @@ export interface ConversationRow {
threadId: string
/** The newest message matching the filter, which represents the conversation in lists. */
latest: IndexedMessage
- /** Messages in the whole conversation, matching or not. */
+ /** Emails in the whole conversation, matching or not, counting each server identity once. */
count: number
}
diff --git a/packages/imap/src/port.ts b/packages/imap/src/port.ts
index 3910240..e1d973f 100644
--- a/packages/imap/src/port.ts
+++ b/packages/imap/src/port.ts
@@ -115,6 +115,8 @@ export interface Envelope {
export interface FetchedMessage {
uid: number
+ /** Account-wide server identity (OBJECTID EMAILID or Gmail X-GM-MSGID). */
+ emailId?: string
modseq?: string
flags?: string[]
envelope?: Envelope
diff --git a/packages/imap/src/provider.ts b/packages/imap/src/provider.ts
index b91d60c..dc6fe32 100644
--- a/packages/imap/src/provider.ts
+++ b/packages/imap/src/provider.ts
@@ -876,14 +876,19 @@ export class ImapProvider implements MailProvider {
const rows = await this.index.threadMessages(this.accountId, [threadId])
if (!rows.length)
throw new ProviderError('notFound', 'This conversation is no longer available.')
- const messages = await this.withBodies(account, rows)
+ const messages = await this.withBodies(account, rows, true)
if (!messages.length)
throw new ProviderError('notFound', 'This conversation is no longer available.')
return messages.sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))
}
- private async withBodies(account: Account, rows: IndexedMessage[]): Promise<Message[]> {
+ private async withBodies(
+ account: Account,
+ rows: IndexedMessage[],
+ deduplicate = false,
+ ): Promise<Message[]> {
const boxes = await this.index.listMailboxes(this.accountId)
const result: Message[] = []
+ const displayed = new Set<string>()
for (const [mailboxId, items] of byMailbox(rows)) {
const box = boxes.find((b) => b.id === mailboxId)
if (!box) continue
@@ -891,6 +896,9 @@ export class ImapProvider implements MailProvider {
const selected = await port.select(box.path)
for (const row of items) {
if (row.uidValidity !== selected.uidValidity) continue
+ // Gmail labels expose the same email at several UIDs. Keep every location for
+ // mutations, but read its body once. A missing/stale location allows another to load.
+ if (deduplicate && row.emailId && displayed.has(row.emailId)) continue
const body = await this.body(port, row)
if (!body) {
await this.index.removeMessages(this.accountId, [row.id])
@@ -904,6 +912,7 @@ export class ImapProvider implements MailProvider {
text: body.text,
attachments: attachmentsOf(row),
})
+ if (row.emailId) displayed.add(row.emailId)
}
})
}
diff --git a/tests/imap-index.test.ts b/tests/imap-index.test.ts
index 037789d..471548d 100644
--- a/tests/imap-index.test.ts
+++ b/tests/imap-index.test.ts
@@ -9,6 +9,7 @@ import {
SqliteMetadataIndex,
asyncIndex,
openInProcessIndex,
+ SCHEMA_VERSION,
} from '../apps/desktop/src/main/imap-index/sqlite-index'
import { WorkerMetadataIndex, type IndexPort } from '../apps/desktop/src/main/imap-index/client'
import type { FolderListing, IndexedMessage, MetadataIndex, NewMessage } from '@inlark/imap'
@@ -82,6 +83,7 @@ describe('SQLite metadata index', () => {
expect((await stat(join(directory, 'index'))).mode & 0o777).toBe(0o700)
const { INBOX } = await mailboxes()
const input = message(INBOX!, 5, {
+ emailId: '18446744073709551615',
modseq: '18446744073709551615',
inReplyTo: ['[email protected]'],
@@ -446,6 +448,59 @@ describe('SQLite metadata index', () => {
expect(await readFile(future)).toEqual(bytes)
})
+ it('refreshes a version 1 index and backfills email identity without losing location IDs', async () => {
+ const { INBOX, Archive } = await mailboxes()
+ const ids = await index.upsertMessages('a', [
+ message(INBOX!, 1, { messageId: null }),
+ message(Archive!, 2, { messageId: null }),
+ ])
+ await index.updateMailbox('a', INBOX!, { uidNext: 2, indexedFrom: 1, complete: true })
+ const oldThread = (await one('a', ids[1]!)).threadId
+ await index.close()
+ // Recreate the prior schema from the same stored locations.
+ const db = new DatabaseSync(path)
+ db.exec(
+ 'DROP INDEX messages_email_id; ALTER TABLE messages DROP COLUMN email_id; PRAGMA user_version = 1',
+ )
+ db.close()
+ index = openInProcessIndex(path)
+ expect((await index.listMailboxes('a')).find((b) => b.id === INBOX)).toMatchObject({
+ uidNext: null,
+ indexedFrom: null,
+ complete: false,
+ })
+ expect((await index.messages('a', ids)).map((m) => m.id).sort()).toEqual([...ids].sort())
+ expect(
+ await index.upsertMessages('a', [
+ message(INBOX!, 1, { messageId: null, emailId: '123' }),
+ message(Archive!, 2, { messageId: null, emailId: '123' }),
+ ]),
+ ).toEqual(ids)
+ const page = await index.conversations('a', {}, { limit: 10 })
+ expect(page.total).toBe(1)
+ expect(page.items[0].count).toBe(1)
+ expect(await index.threadMessages('a', [oldThread])).toHaveLength(2)
+ await index.close()
+ index = openInProcessIndex(path)
+ expect((await one('a', ids[0]!)).emailId).toBe('123')
+ const migrated = new DatabaseSync(path)
+ expect(migrated.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
+ migrated.close()
+ })
+
+ it('scopes server email identities and deduplicated counts to the account', async () => {
+ const a = await mailboxes('a')
+ const b = await mailboxes('b')
+ await index.upsertMessages('a', [message(a.INBOX!, 1, { emailId: '123' })])
+ await index.upsertMessages('b', [message(b.INBOX!, 1, { emailId: '123' })])
+ for (const accountId of ['a', 'b']) {
+ const page = await index.conversations(accountId, {}, { limit: 10 })
+ expect(page.total).toBe(1)
+ expect(page.items[0].count).toBe(1)
+ expect(await index.threadMessages(accountId, [page.items[0].threadId])).toHaveLength(1)
+ }
+ })
+
it('answers conversation pages quickly on a large mailbox', async () => {
const sync = new SqliteMetadataIndex(join(directory, 'large.sqlite'))
const [inbox, archive] = sync.syncMailboxes('a', [folder('INBOX'), folder('Archive')])
diff --git a/tests/imap-provider.test.ts b/tests/imap-provider.test.ts
index b9a75fb..b5ff6b2 100644
--- a/tests/imap-provider.test.ts
+++ b/tests/imap-provider.test.ts
@@ -109,6 +109,15 @@ describe('IMAP connection and folders', () => {
})
describe('IMAP TLS policy', () => {
+ it('preserves the account-wide email ID returned by ImapFlow', async () => {
+ const port = new ImapFlowPort({ ...config.incoming, password: 'x' }, 'command')
+ vi.spyOn((port as any).client, 'fetch').mockImplementation(async function* () {
+ yield { uid: 17, emailId: '18446744073709551615' }
+ })
+ expect(await port.fetch('17', { envelope: true })).toEqual([
+ expect.objectContaining({ uid: 17, emailId: '18446744073709551615' }),
+ ])
+ })
it('verifies certificates and never falls back to plaintext', () => {
const tls = imapFlowOptions({ ...config.incoming, password: 'x' }, 'command')
expect(tls).toMatchObject({
@@ -143,6 +152,96 @@ describe('IMAP TLS policy', () => {
})
describe('IMAP indexing and reading', () => {
+ it('shows and counts Gmail emails once across Inbox, All Mail and labels', async () => {
+ server.capabilities.add('X-GM-EXT-1')
+ server.addMailbox('[Gmail]/All Mail', '\\All')
+ server.addMailbox('Personal')
+ const input = {
+ emailId: '18446744073709551615',
+ messageId: 'root@x',
+ subject: 'Plans',
+ from: [alex],
+ date: at(1),
+ text: 'Shall we?',
+ attachments: [{ name: 'plans.txt', type: 'text/plain', content: 'Plan A' }],
+ }
+ for (const path of ['INBOX', '[Gmail]/All Mail', 'Personal']) server.deliver(path, input)
+ const reply = {
+ emailId: '18446744073709551614',
+ messageId: 'reply@x',
+ references: ['root@x'],
+ subject: 'Re: Plans',
+ date: at(2),
+ text: 'Yes.',
+ }
+ for (const path of ['Sent', '[Gmail]/All Mail']) server.deliver(path, reply)
+ const p = await connected()
+ await sync(p)
+ for (const query of [{ view: 'inbox' }, { view: 'all' }, { view: 'all', text: 'Plans' }]) {
+ const page = await p.query(account, query)
+ expect(page.total).toBe(1)
+ expect(page.items[0].count).toBe(2)
+ }
+ const [thread] = (await p.query(account, { view: 'inbox' })).items
+ const messages = await p.conversation(account, thread.id)
+ expect(messages.map((m) => m.text?.trim())).toEqual(['Shall we?', 'Yes.'])
+ expect(new TextDecoder().decode(await p.download(account, messages[0].attachments![0]))).toBe(
+ 'Plan A',
+ )
+ // Actions still receive all five verified mailbox + UID locations.
+ const locations = await p.conversationMetadata(account, [thread.id])
+ expect(locations).toHaveLength(5)
+ const updated = await p.update(
+ account,
+ Object.fromEntries(locations.map((m) => [m.id, { keywords: { $seen: true } }])),
+ )
+ expect(updated.failures).toEqual([])
+ expect(updated.updated).toHaveLength(5)
+ })
+ it('deduplicates by server identity when Message-ID is absent and preserves distinct emails', async () => {
+ const same = { emailId: '123', subject: 'No header ID', date: at(1), text: 'One email' }
+ server.deliver('INBOX', same)
+ server.deliver('Archive', same)
+ // Reused Message-ID headers are not proof that two emails are identical.
+ server.deliver('INBOX', { emailId: '124', messageId: 'shared@x', date: at(2), text: 'First' })
+ server.deliver('Archive', {
+ emailId: '125',
+ messageId: 'shared@x',
+ date: at(3),
+ text: 'Second',
+ })
+ server.deliver('INBOX', { messageId: 'plain@x', date: at(4), text: 'Plain first' })
+ server.deliver('Archive', { messageId: 'plain@x', date: at(5), text: 'Plain second' })
+ const p = await connected()
+ await sync(p)
+ const page = await p.query(account, { view: 'all' })
+ expect(page.total).toBe(3)
+ const noHeader = page.items.find((c) => c.subject === same.subject)!
+ expect(noHeader.count).toBe(1)
+ expect(await p.conversation(account, noHeader.id)).toHaveLength(1)
+ for (const thread of page.items.filter((c) => c.id !== noHeader.id)) {
+ expect(thread.count).toBe(2)
+ expect(await p.conversation(account, thread.id)).toHaveLength(2)
+ }
+ })
+ it('reads another location if the first Gmail location disappeared or became stale', async () => {
+ const input = { emailId: '123', messageId: 'same@x', date: at(1), text: 'Still here' }
+ const inboxUid = server.deliver('INBOX', input)
+ server.deliver('Archive', input)
+ const p = await connected()
+ await sync(p)
+ const [thread] = (await p.query(account, { view: 'inbox' })).items
+ server.remove('INBOX', inboxUid)
+ expect((await p.conversation(account, thread.id)).map((m) => m.text?.trim())).toEqual([
+ 'Still here',
+ ])
+ server.deliver('INBOX', input)
+ await sync(p)
+ server.resetUidValidity('INBOX')
+ expect((await p.conversation(account, thread.id)).map((m) => m.text?.trim())).toEqual([
+ 'Still here',
+ ])
+ })
it('bounds an empty preview on opening while preserving the full HTML body', async () => {
const html = ' '.repeat(4096) + '<p>Full message content</p>'
server.deliver('INBOX', { messageId: 'html@x', subject: 'HTML', date: at(1), html })
diff --git a/tests/support/fake-imap.ts b/tests/support/fake-imap.ts
index 36e1905..0848ec9 100644
--- a/tests/support/fake-imap.ts
+++ b/tests/support/fake-imap.ts
@@ -11,6 +11,7 @@ import type {
} from '../../packages/imap/src/port'
export interface FakeMessageInput {
+ emailId?: string
messageId?: string
inReplyTo?: string
references?: string[]
@@ -360,6 +361,7 @@ export class FakePort implements ImapPort {
const raw = (m.raw ??= rfc822(i))
return {
uid: m.uid,
+ emailId: i.emailId,
modseq: this.condstore ? String(m.modseq) : undefined,
...(query.flags ? { flags: [...m.flags] } : {}),
...(query.envelope