diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index d9dfbdc..eae9d0e 100644 --- a/apps/client/lib/core/app_router.dart +++ b/apps/client/lib/core/app_router.dart @@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart'; import '../features/accounts/account_mailbox_page.dart'; import '../features/accounts/accounts_page.dart'; +import '../features/accounts/thread_page.dart'; import '../features/message/compose_page.dart'; import '../features/message/message_page.dart'; import '../features/message/reply_draft.dart'; @@ -34,6 +35,17 @@ final appRouterProvider = Provider((ref) { ), ), ), + GoRoute( + path: '/accounts/:accountId/threads/:threadId', + pageBuilder: (context, state) => _verticalPage( + state: state, + disableTransition: true, + child: ThreadPage( + accountId: state.pathParameters['accountId']!, + threadId: state.pathParameters['threadId']!, + ), + ), + ), GoRoute( path: '/accounts/:accountId/messages/:messageId', pageBuilder: (context, state) => _verticalPage( diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 2ac0626..52092d5 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -283,6 +283,12 @@ class AppStrings { 'password' => _ko ? '비밀번호' : 'Password', _ => mode, }; + String get threadView => _ko ? '대화 보기' : 'Conversation view'; + String get threadViewDescription => _ko + ? '같은 대화의 메일을 한 줄로 묶어 보여줍니다.' + : 'Group mail from the same conversation into one row.'; + String get thread => _ko ? '대화' : 'Conversation'; + String threadMessageCount(int count) => _ko ? '$count통' : '$count'; String get mailSending => _ko ? '메일을 보내는 중입니다.' : 'Sending mail...'; String get undoSend => _ko ? '보내기 취소' : 'Undo send'; String get sendCancelled => diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 268460b..b03329e 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -62,8 +62,11 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { final _searchController = TextEditingController(); Future>? _search; - bool get _isSyncing => - const {'syncing', 'validating'}.contains(widget.account.syncStatus); + static bool _busy(MailAccountSummary account) => + account.threadBackfilling || + const {'syncing', 'validating'}.contains(account.syncStatus); + + bool get _isSyncing => _busy(widget.account); @override void initState() { @@ -80,10 +83,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { _searchController.clear(); _search = null; } - final wasSyncing = const { - 'syncing', - 'validating', - }.contains(oldWidget.account.syncStatus); + final wasSyncing = _busy(oldWidget.account); if (oldWidget.account.id == widget.account.id && wasSyncing && !_isSyncing) { @@ -94,7 +94,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { }); } if (oldWidget.account.id != widget.account.id || - oldWidget.account.syncStatus != widget.account.syncStatus) { + _busy(oldWidget.account) != _isSyncing) { _configureRefreshTimer(); } } @@ -158,8 +158,9 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { if (mounted && _refreshTimer == null) _scheduleRefresh(); } - Widget _messageList(List items) { + Widget _messageList(List items, {bool threaded = false}) { final account = widget.account; + final strings = ref.read(appStringsProvider); return ListView.separated( itemCount: items.length, separatorBuilder: (context, index) => const Divider(height: 1), @@ -189,11 +190,18 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { const Icon(Icons.star, size: 18, color: Colors.amber), const SizedBox(width: 6), ], - Text(message.receivedAtLabel), + Text( + threaded && message.threadCount > 1 + ? '${strings.threadMessageCount(message.threadCount)}\n${message.receivedAtLabel}' + : message.receivedAtLabel, + textAlign: TextAlign.end, + ), ], ), onTap: () => context.go( - '/accounts/${account.id}/messages/${Uri.encodeComponent(message.id)}', + threaded && message.threadCount > 1 + ? '/accounts/${account.id}/threads/${Uri.encodeComponent(message.threadId!)}' + : '/accounts/${account.id}/messages/${Uri.encodeComponent(message.id)}', extra: const {'disableTransition': true}, ), ); @@ -205,6 +213,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { Widget build(BuildContext context) { final account = widget.account; final messages = ref.watch(accountMessagesProvider(account.id)); + final threaded = ref.watch(threadViewProvider); final strings = ref.watch(appStringsProvider); return Column( @@ -298,7 +307,8 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { }, ) : messages.when( - data: (items) { + data: (all) { + final items = threaded ? groupByThread(all) : all; if (items.isEmpty) { return Center( child: Column( @@ -337,7 +347,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ); } - return _messageList(items); + return _messageList(items, threaded: threaded); }, loading: () => const Center(child: CircularProgressIndicator()), diff --git a/apps/client/lib/features/accounts/account_providers.dart b/apps/client/lib/features/accounts/account_providers.dart index 8b9b875..77c9e7c 100644 --- a/apps/client/lib/features/accounts/account_providers.dart +++ b/apps/client/lib/features/accounts/account_providers.dart @@ -10,3 +10,21 @@ final accountMessagesProvider = FutureProvider.family, String>((ref, accountId) { return ref.watch(mailApiClientProvider).fetchAccountMessages(accountId); }); + +final threadMessagesProvider = FutureProvider.autoDispose + .family, ({String accountId, String threadId})>( + (ref, key) { + return ref + .watch(mailApiClientProvider) + .fetchThread(key.accountId, key.threadId); +}); + +class ThreadViewController extends Notifier { + @override + bool build() => true; + + void set(bool value) => state = value; +} + +final threadViewProvider = + NotifierProvider(ThreadViewController.new); diff --git a/apps/client/lib/features/accounts/thread_page.dart b/apps/client/lib/features/accounts/thread_page.dart new file mode 100644 index 0000000..84b5603 --- /dev/null +++ b/apps/client/lib/features/accounts/thread_page.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../widgets/app_shell.dart'; +import 'account_providers.dart'; + +class ThreadPage extends ConsumerWidget { + const ThreadPage({ + super.key, + required this.accountId, + required this.threadId, + }); + + final String accountId; + final String threadId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final strings = ref.watch(appStringsProvider); + final messages = ref.watch( + threadMessagesProvider((accountId: accountId, threadId: threadId)), + ); + + return AppShell( + selectedDestinationId: AppShell.accountDestinationId(accountId), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AppBar( + leading: BackButton( + onPressed: () => context.go('/accounts/$accountId/mail'), + ), + title: Text(strings.thread), + ), + Expanded( + child: messages.when( + data: (items) => ListView.separated( + itemCount: items.length, + separatorBuilder: (context, index) => const Divider(height: 1), + itemBuilder: (context, index) { + final message = items[index]; + return ListTile( + title: Text( + message.subject, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + '${message.sender}\n${message.snippet}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + trailing: Text(message.receivedAtLabel), + onTap: () => context.go( + '/accounts/$accountId/messages/${Uri.encodeComponent(message.id)}', + extra: const {'disableTransition': true}, + ), + ); + }, + ), + loading: () => const Center(child: CircularProgressIndicator()), + error: (error, stackTrace) => + Center(child: Text(strings.mailLoadFailedTitle)), + ), + ), + ], + ), + ); + } +} diff --git a/apps/client/lib/features/settings/settings_page.dart b/apps/client/lib/features/settings/settings_page.dart index aca683d..d683a58 100644 --- a/apps/client/lib/features/settings/settings_page.dart +++ b/apps/client/lib/features/settings/settings_page.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; import '../../services/push_service.dart'; +import '../accounts/account_providers.dart'; import '../accounts/accounts_page.dart' show friendlyError; import '../../widgets/app_shell.dart'; @@ -46,6 +47,12 @@ class SettingsPage extends ConsumerWidget { }, ), ), + SwitchListTile( + value: ref.watch(threadViewProvider), + onChanged: ref.read(threadViewProvider.notifier).set, + title: Text(strings.threadView), + subtitle: Text(strings.threadViewDescription), + ), ListTile( leading: const Icon(Icons.undo), title: Text(strings.undoSendSetting), diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index dc38469..cb40966 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -90,6 +90,19 @@ class MailApiClient { .toList(); } + Future> fetchThread( + String accountId, + String threadId, + ) async { + final response = await _dio.get>( + '/accounts/$accountId/threads/${Uri.encodeComponent(threadId)}', + ); + final data = response.data ?? []; + return data + .map((item) => MailSummary.fromJson(item as Map)) + .toList(); + } + Future> searchAccountMessages( String accountId, String query, @@ -395,6 +408,8 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, + this.threadId, + this.threadCount = 1, this.flagged = false, }); @@ -404,6 +419,8 @@ class MailSummary { final String snippet; final String receivedAtLabel; final bool unread; + final String? threadId; + final int threadCount; final bool flagged; factory MailSummary.fromJson(Map json) { @@ -413,12 +430,24 @@ class MailSummary { subject: json['subject'] as String? ?? '', snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), + threadId: json['threadId'] as String?, + threadCount: json['threadCount'] as int? ?? 1, unread: !(json['seen'] as bool? ?? false), flagged: json['flagged'] as bool? ?? false, ); } } +/// Keeps the first (newest) message of each thread. Mail without a thread id +/// stays as its own row. +List groupByThread(List items) { + final seen = {}; + return [ + for (final item in items) + if (item.threadId == null || seen.add(item.threadId!)) item, + ]; +} + class MessageDetail { const MessageDetail({ required this.id, @@ -549,6 +578,7 @@ class MailAccountSummary { this.syncErrorCode, required this.initialSync, required this.lastSyncedAtLabel, + this.threadBackfilling = false, this.idleSupported, this.capabilitiesCheckedAtLabel = '', this.notificationsEnabled = true, @@ -564,6 +594,8 @@ class MailAccountSummary { final String? syncErrorCode; final InitialSyncOption? initialSync; final String lastSyncedAtLabel; + // Server is still filling thread metadata for older messages. + final bool threadBackfilling; final bool notificationsEnabled; /// Null until the server has logged in and read the IMAP capabilities. @@ -588,6 +620,7 @@ class MailAccountSummary { json['initialSync'] as Map) : null, lastSyncedAtLabel: _formatReceivedAt(json['lastSyncedAt'] as String?), + threadBackfilling: json['threadBackfill'] == 'running', idleSupported: capabilities?['idle'] as bool?, capabilitiesCheckedAtLabel: _formatReceivedAt(capabilities?['checkedAt'] as String?), diff --git a/apps/client/test/message_reply_test.dart b/apps/client/test/message_reply_test.dart index 1690cd9..3c876b4 100644 --- a/apps/client/test/message_reply_test.dart +++ b/apps/client/test/message_reply_test.dart @@ -70,6 +70,7 @@ void main() { container.read(appRouterProvider).go('/settings'); await tester.pumpAndSettle(); - expect(find.byType(SwitchListTile), findsNothing); + // Only the working conversation-view toggle; the dead push switch is gone. + expect(find.byType(SwitchListTile), findsOneWidget); }); } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 67733a0..dc57d3f 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -495,6 +495,72 @@ void main() { await tester.pumpWidget(const SizedBox()); }); + testWidgets('keeps polling and reloads mail when thread backfill finishes', + (WidgetTester tester) async { + const syncing = MailAccountSummary( + id: 'syncing-account', + providerId: 'naver', + emailAddress: 'syncing@example.com', + incomingProtocol: 'imap', + authMode: 'app-password', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'never', + threadBackfilling: true, + ); + const idle = MailAccountSummary( + id: 'syncing-account', + providerId: 'naver', + emailAddress: 'syncing@example.com', + incomingProtocol: 'imap', + authMode: 'app-password', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + var accountLoads = 0; + var messageLoads = 0; + await tester.binding.setSurfaceSize(const Size(1200, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + accountsProvider.overrideWith((ref) async { + accountLoads += 1; + return accountLoads == 1 ? const [syncing] : const [idle]; + }), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, accountId) async { + messageLoads += 1; + return const []; + }), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(syncing.emailAddress).first); + await tester.pump(); + final loadsBeforePoll = messageLoads; + await tester.pump(const Duration(seconds: 4)); + await tester.pump(); + await tester.pump(); + + // One poll plus one reload after the status leaves syncing. + expect(messageLoads, loadsBeforePoll + 2); + expect(find.text('이 계정에 표시할 메일이 없습니다'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.pump(const Duration(seconds: 4)); + expect(messageLoads, loadsBeforePoll + 2); + + await tester.pumpWidget(const SizedBox()); + }); + testWidgets('explains an authentication failure in the mailbox', ( WidgetTester tester, ) async { @@ -780,6 +846,24 @@ void main() { ]); }); + test('groups mail by thread id and keeps unthreaded mail', () { + MailSummary mail(String id, String? thread) => MailSummary( + id: id, + sender: '', + subject: '', + snippet: '', + receivedAtLabel: '', + unread: true, + threadId: thread, + ); + + final grouped = groupByThread( + [mail('1', 'a'), mail('2', 'b'), mail('3', 'a'), mail('4', null)], + ); + + expect(grouped.map((item) => item.id), ['1', '2', '4']); + }); + testWidgets('does not offer the unimplemented POP3 protocol', (WidgetTester tester) async { const daum = MailProviderSummary( diff --git a/apps/server/package.json b/apps/server/package.json index ae37be8..61558ef 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/sendQueue.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/sendQueue.test.ts test/threading.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 674fcdc..398a76d 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { SearchObject } from "imapflow"; import type { MailSender } from "../mail/MailSender.js"; +import { withThreadInfo } from "../mail/threading.js"; import { SendQueue, SendQueueFullError, @@ -364,8 +365,31 @@ export async function registerRoutes( } const messages = await deps.accounts.listInbox(demoUserId); - return messages - .filter((message) => message.accountId === params.id) + return withThreadInfo( + messages.filter((message) => message.accountId === params.id) + ).map((message) => ({ + ...message, + id: message.providerMessageId, + receivedAt: message.receivedAt.toISOString(), + ...flagState(message) + })); + }); + + app.get("/accounts/:id/threads/:threadId", async (request, reply) => { + const params = z.object({ id: z.string(), threadId: z.string() }) + .parse(request.params); + const account = await deps.accounts.getAccount(params.id); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + + const messages = await deps.accounts.listInbox(demoUserId); + return withThreadInfo( + messages.filter((message) => message.accountId === params.id) + ) + .filter((message) => message.threadId === params.threadId) + .sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime()) .map((message) => ({ ...message, id: message.providerMessageId, diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index 67e8f5a..be727ba 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -51,6 +51,8 @@ export interface MailAccount { incomingProtocol: MailProtocol; encryptedSecretRef: string; syncStatus?: "idle" | "validating" | "syncing" | "error"; + /** Set while the background thread-metadata backfill runs; clients keep refreshing. */ + threadBackfill?: "running"; syncError?: string; syncErrorCode?: "authentication"; initialSync?: { @@ -96,6 +98,10 @@ export interface IncomingMessageSummary { // receivedAt, which is the sender-set Date header. arrivedAt?: Date; hasAttachments: boolean; + messageId?: string; + inReplyTo?: string; + references?: string[]; + gmailThreadId?: string; seen?: boolean; flagged?: boolean; } diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 5452483..a009694 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -37,6 +37,7 @@ import { rawAttachmentFetch } from "./attachments.js"; import { extractMessageLinks } from "./messageLinks.js"; +import { MAX_HEADER_BYTES, boundMessageId, parseMessageIds } from "./threading.js"; import { detectImapCapabilities } from "./imapCapabilities.js"; import { createExistsQueue } from "./existsQueue.js"; @@ -154,6 +155,24 @@ export class ImapReceiver implements MailReceiver { return initial.result; } + /** Re-reads headers of already stored messages (one connection, one mailbox). */ + async fetchSummariesByUid( + account: MailAccount, + mailbox: string, + uids: number[] + ): Promise<{ uidValidity: string; messages: IncomingMessageSummary[] }> { + return this.withConnectionRetry(() => + this.withConnectedClient(account, async (client) => { + const openedMailbox = await client.mailboxOpen(mailbox, { readOnly: true }); + return { + // Callers compare this across batches: a changed UIDVALIDITY means the UIDs name other messages. + uidValidity: String(openedMailbox.uidValidity), + messages: uids.length === 0 ? [] : await this.fetchUids(client, account, mailbox, uids) + }; + }) + ); + } + // Searches the server, so messages that were never imported are found too. async search( account: MailAccount, @@ -491,7 +510,9 @@ export class ImapReceiver implements MailReceiver { envelope: true, flags: true, internalDate: true, - uid: true + uid: true, + threadId: true, + headers: ["references"] }, { uid: true })) { const summary = toIncomingMessage(account, mailbox, message); if (summary) batch.push(summary); @@ -534,6 +555,12 @@ function toIncomingMessage( receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), arrivedAt: message.internalDate instanceof Date ? message.internalDate : undefined, hasAttachments: false, + messageId: boundMessageId(envelope.messageId), + inReplyTo: boundMessageId(envelope.inReplyTo), + references: parseMessageIds( + message.headers?.subarray(0, MAX_HEADER_BYTES).toString("utf8") + ), + gmailThreadId: message.threadId, seen: message.flags?.has("\\Seen") ?? false, flagged: message.flags?.has("\\Flagged") ?? false }; @@ -543,11 +570,12 @@ function toThreadHeaders(message: FetchMessageObject): MessageThreadHeaders { const envelope = message.envelope; const addresses = (list?: Array<{ address?: string }>) => list?.map((item) => item.address).filter((a): a is string => Boolean(a)) ?? []; - // Unfold continuation lines, then collect every in the header. - const raw = message.headers?.toString("utf8").replace(/\r?\n[ \t]+/g, " ") ?? ""; + // Same bounded parsing as the stored summary fields (threading.ts). return { - messageId: envelope?.messageId, - references: raw.match(/<[^<>\s]+>/g) ?? [], + messageId: boundMessageId(envelope?.messageId), + references: parseMessageIds( + message.headers?.subarray(0, MAX_HEADER_BYTES).toString("utf8") + ), replyTo: addresses(envelope?.replyTo), to: addresses(envelope?.to), cc: addresses(envelope?.cc) diff --git a/apps/server/src/mail/threading.ts b/apps/server/src/mail/threading.ts new file mode 100644 index 0000000..0cbdf44 --- /dev/null +++ b/apps/server/src/mail/threading.ts @@ -0,0 +1,102 @@ +import { createHash } from "node:crypto"; +import type { IncomingMessageSummary } from "../domain/types.js"; + +// Gmail thread id wins; otherwise the first Reference (the conversation root), +// then In-Reply-To, then the message's own id. Subject is never used so that +// unrelated mail with the same subject is not merged. +export function computeThreadId( + message: Pick< + IncomingMessageSummary, + "gmailThreadId" | "messageId" | "inReplyTo" | "references" + > +): string | undefined { + if (message.gmailThreadId) return `gm:${message.gmailThreadId}`; + const root = message.references?.[0] ?? message.inReplyTo ?? message.messageId; + return root ? midThreadId(root) : undefined; +} + +// Hashed so the id stays short enough for a URL path segment (Fastify limits +// params to 100 chars) whatever the Message-ID length. +function midThreadId(root: string): string { + return `mid:${createHash("sha256").update(root).digest("hex").slice(0, 32)}`; +} + +type Linked = Pick; + +// Without References, follows In-Reply-To through the supplied messages to the +// chain's root so A <- B <- C land in one thread. `memo` caches the root per +// Message-ID (path compression), so resolving every message is O(n) overall. +function resolveRoot( + message: Linked, + byId: Map, + memo: Map +): string | undefined { + const ownRoot = (m: Linked) => m.references?.[0] ?? m.inReplyTo ?? m.messageId; + const path: string[] = []; + const seen = new Set(); + let current = message; + let root = ownRoot(current); + while (true) { + if (current.messageId) { + if (memo.has(current.messageId)) { root = memo.get(current.messageId); break; } + path.push(current.messageId); + } + if (current.references?.length || !current.inReplyTo || seen.has(current.inReplyTo)) { + root = ownRoot(current); + break; + } + seen.add(current.inReplyTo); + const parent = byId.get(current.inReplyTo); + if (!parent) { root = ownRoot(current); break; } + current = parent; + } + for (const id of path) memo.set(id, root); + return root; +} + +// Bounds on untrusted header input: raw bytes parsed, one id's length (RFC 5322 +// line limit) and ids kept. Threading needs only the root (first) and the +// nearest ancestors (last), so the middle of a huge chain is dropped. +export const MAX_HEADER_BYTES = 16 * 1024; +export const MAX_MESSAGE_ID_LENGTH = 998; +export const MAX_REFERENCES = 20; + +export function parseMessageIds(value: string | undefined): string[] { + const ids = + value?.slice(0, MAX_HEADER_BYTES).match(/<[^<>\s]{1,996}>/g) ?? []; + return ids.length > MAX_REFERENCES + ? [ids[0]!, ...ids.slice(ids.length - (MAX_REFERENCES - 1))] + : ids; +} + +// Single Message-ID / In-Reply-To value; over-long ones are dropped. +export function boundMessageId(value: string | undefined): string | undefined { + return value && value.length <= MAX_MESSAGE_ID_LENGTH ? value : undefined; +} + +// Adds threadId and a per-thread message count to each summary. +export function withThreadInfo( + messages: T[] +): Array { + const byId = new Map(); + for (const message of messages) { + if (message.messageId) byId.set(message.messageId, message); + } + const memo = new Map(); + const withIds = messages.map((message) => { + let threadId = computeThreadId(message); + if (!message.gmailThreadId) { + const root = resolveRoot(message, byId, memo); + threadId = root ? midThreadId(root) : undefined; + } + return { ...message, threadId }; + }); + const counts = new Map(); + for (const { threadId } of withIds) { + if (threadId) counts.set(threadId, (counts.get(threadId) ?? 0) + 1); + } + return withIds.map((message) => ({ + ...message, + threadCount: message.threadId ? counts.get(message.threadId)! : 1 + })); +} diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index 9eed397..b675996 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -18,11 +18,16 @@ export interface MailSyncWorkerOptions { mailbox: string; imapReconnectBaseDelayMs: number; imapReconnectMaxDelayMs: number; + /** Pause between thread-metadata backfill batches (default 250). */ + backfillYieldMs?: number; } export class MailSyncWorker { + private static readonly backfillBatch = 50; private readonly stopHandlers = new Map Promise>(); private readonly pollingTimers = new Map(); + // accountId -> running backfill; stopAccount/stop drop the token to cancel it. + private readonly backfills = new Map; saving?: Promise }>(); private readonly syncPromises = new Map>(); // stopAccount drops the token so a sync still running with replaced // credentials cannot overwrite the status of the restarted sync. @@ -171,6 +176,10 @@ export class MailSyncWorker { ); } + if (account.incomingProtocol === "imap" && isCurrent()) { + this.startBackfill(account); + } + if (!isCurrent()) return; // Advanced only here: mail the IDLE watcher saved meanwhile must not // move the cursor past messages this sync has not checked. @@ -190,6 +199,9 @@ export class MailSyncWorker { } async stop(): Promise { + const saving = [...this.backfills.values()].map((b) => b.saving); + this.backfills.clear(); + await Promise.all(saving); for (const timer of this.pollingTimers.values()) clearInterval(timer); this.pollingTimers.clear(); @@ -203,6 +215,10 @@ export class MailSyncWorker { this.pendingStarts.delete(accountId); this.syncPromises.delete(accountId); this.syncTokens.delete(accountId); + const backfill = this.backfills.get(accountId); + this.backfills.delete(accountId); + // Wait for the batch save already issued so nothing is written after the caller deletes the account. + await backfill?.saving?.catch(() => undefined); const timer = this.pollingTimers.get(accountId); if (timer) { @@ -344,6 +360,107 @@ export class MailSyncWorker { }); } + /** Resolves when the account's background backfill (if any) has ended. */ + async backfillSettled(accountId: string): Promise { + await this.backfills.get(accountId)?.done; + } + + // Messages stored before threading existed have no header metadata and the + // 25-message sync never revisits them. Backfill runs in the background in + // 50-message batches until none is left. Progress is the stored metadata + // itself (a message the server no longer has gets `references: []`), so a + // restart or the next sync simply continues with what is still missing. + private startBackfill(account: MailAccount): void { + if (this.backfills.has(account.id)) return; + const token = {}; + const entry: { token: object; done: Promise; saving?: Promise } = { + token, + done: Promise.resolve() + }; + this.backfills.set(account.id, entry); + entry.done = this.backfillThreadMetadata(account, token, entry) + .catch((error) => { + console.warn("imap:backfill-stopped", { + accountId: account.id, + error: error instanceof Error ? error.message : String(error) + }); + }) + .then(async () => { + if (this.backfills.get(account.id)?.token !== token || !account.threadBackfill) return; + // Tell clients the backfill ended so they reload the list once more. + account.threadBackfill = undefined; + await this.accounts.updateAccount(account).catch(() => undefined); + }) + .finally(() => { + if (this.backfills.get(account.id)?.token === token) { + this.backfills.delete(account.id); + } + }); + } + + private async backfillThreadMetadata( + account: MailAccount, + token: object, + entry: { saving?: Promise } + ): Promise { + const active = () => this.backfills.get(account.id)?.token === token; + const pending = (await this.accounts.listInbox(account.userId)) + .filter((message) => + message.accountId === account.id && + message.messageId === undefined && + message.gmailThreadId === undefined && + message.references === undefined && + /^\d+$/.test(message.providerMessageId)); + + const byMailbox = new Map(); + for (const message of pending) { + const group = byMailbox.get(message.mailbox); + if (group) group.push(message); + else byMailbox.set(message.mailbox, [message]); + } + if (pending.length === 0 || !active()) return; + account.threadBackfill = "running"; + await this.accounts.updateAccount(account); + for (const [mailbox, stored] of byMailbox) { + // The synced mailbox is checked against the UIDVALIDITY the sync recorded. + let expectedUidValidity = mailbox === this.options.mailbox ? account.uidValidity : undefined; + const tracked = expectedUidValidity !== undefined; + for (let i = 0; i < stored.length; i += MailSyncWorker.backfillBatch) { + // Yield first so sync and other accounts are not starved. + await new Promise((resolve) => setTimeout(resolve, this.options.backfillYieldMs ?? 250)); + if (!active()) return; + const batch = stored.slice(i, i + MailSyncWorker.backfillBatch); + const { uidValidity, messages } = await this.imap.fetchSummariesByUid( + account, mailbox, batch.map((m) => Number(m.providerMessageId)) + ); + expectedUidValidity ??= uidValidity; + // Same UIDs under a new UIDVALIDITY are other messages; never copy their headers. + if (uidValidity !== expectedUidValidity) { + throw new Error("Mailbox UIDVALIDITY changed during thread backfill"); + } + const fetched = new Map(messages.map((m) => [m.providerMessageId, m])); + if (!active()) return; + // A sync that saw a new UIDVALIDITY meanwhile dropped this mail; saving would restore it. + if (tracked && account.uidValidity !== expectedUidValidity) return; + // Concurrent saves share one coalesced file write instead of one per message. + entry.saving = Promise.all(batch.map((message) => { + const found = fetched.get(message.providerMessageId); + return this.accounts.saveIncomingMessage({ + ...message, + messageId: found?.messageId, + inReplyTo: found?.inReplyTo, + references: found?.references ?? [], + gmailThreadId: found?.gmailThreadId, + // The snapshot predates this batch; the server's flags are newer. + seen: found?.seen ?? message.seen, + flagged: found?.flagged ?? message.flagged + }); + })); + await entry.saving; + } + } + } + // Saved UIDs point at other messages once the mailbox's UIDVALIDITY // changes, so the account's mail is dropped to be imported again. // Returns true when it dropped the mail. diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index 539dffd..d40adce 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -1,5 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { LocalFileAccountRepository } from "../src/workers/LocalFileAccountRepository.js"; import type { IncomingMessageSummary, MailAccount } from "../src/domain/types.js"; import type { ImapReceiver } from "../src/mail/ImapReceiver.js"; import type { Pop3Receiver } from "../src/mail/Pop3Receiver.js"; @@ -34,7 +38,8 @@ function worker(repository: InMemoryAccountRepository, imap: object) { mailbox: "INBOX", pop3PollIntervalMs: 60_000, imapReconnectBaseDelayMs: 1, - imapReconnectMaxDelayMs: 1 + imapReconnectMaxDelayMs: 1, + backfillYieldMs: 0 } ); } @@ -220,6 +225,350 @@ test("a failing push does not disturb mail handling", async () => { } }); +test("backfills thread metadata for stored messages once, in bounded batches", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + const stored = (uid: number): IncomingMessageSummary => ({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false + }); + for (let uid = 1; uid <= 120; uid += 1) { + await repository.saveIncomingMessage(stored(uid)); + } + const requests: number[][] = []; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + requests.push(uids); + // uid 1 is gone from the server; the rest carry a Message-ID. + return { uidValidity: "1", messages: uids.filter((uid) => uid !== 1).map((uid) => ({ + ...stored(uid), + messageId: ``, + references: [""], + seen: uid === 2 + })) }; + } + }; + const syncWorker = worker(repository, imap); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.deepEqual(requests.map((r) => r.length), [50, 50, 20]); + const inbox = await repository.listInbox(mailAccount.userId); + assert.equal(inbox.find((m) => m.providerMessageId === "2")?.messageId, ""); + // A read flag set on the server during the backfill is not reverted. + assert.equal(inbox.find((m) => m.providerMessageId === "2")?.seen, true); + assert.deepEqual(inbox.find((m) => m.providerMessageId === "1")?.references, []); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(requests.length, 3); +}); + +test("backfill rejects a batch after the mailbox UIDVALIDITY changes", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + for (let uid = 1; uid <= 100; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), hasAttachments: false + }); + } + let calls = 0; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + calls += 1; + // The second batch opens a recreated mailbox whose UIDs name other messages. + return { uidValidity: calls === 1 ? "1" : "2", messages: uids.map((uid) => ({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "other", receivedAt: new Date(uid), + hasAttachments: false, messageId: ``, references: [] + })) }; + } + }; + const syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + + const inbox = await repository.listInbox(mailAccount.userId); + assert.equal(calls, 2); + assert.equal(inbox.filter((m) => m.messageId?.startsWith(" m.messageId?.startsWith(" m.references === undefined).length, 50, "rejected batch must stay pending, not marked backfilled"); + assert.equal((await repository.getAccount(mailAccount.id))?.threadBackfill, undefined); +}); + +test("backfill saves nothing once a sync records a new UIDVALIDITY", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + for (let uid = 1; uid <= 10; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), hasAttachments: false + }); + } + const imap = { + fetchLatestBatches: async () => { + mailAccount.uidValidity = "1"; + return undefined; + }, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + // A concurrent sync saw a recreated mailbox and dropped the stored mail. + mailAccount.uidValidity = "2"; + return { uidValidity: "1", messages: uids.map((uid) => ({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), + hasAttachments: false, messageId: ``, references: [] + })) }; + } + }; + const syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + + const inbox = await repository.listInbox(mailAccount.userId); + assert.ok(!inbox.some((m) => m.messageId !== undefined), "stale headers must not be saved"); +}); + +test("backfill drains 4,000 stored messages across batches without refetching", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + const total = 4000; + for (let uid = 1; uid <= total; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false + }); + } + const seen: number[] = []; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + assert.ok(uids.length <= 50); + seen.push(...uids); + return { uidValidity: "1", messages: uids.map((uid) => ({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false, + messageId: ``, + references: [] + })) }; + } + }; + const syncWorker = worker(repository, imap); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(seen.length, total); + assert.equal(new Set(seen).size, total); + const inbox = await repository.listInbox(mailAccount.userId); + assert.ok(inbox.every((m) => m.references !== undefined)); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(seen.length, total); +}); + +test("backfill stops when the account is removed", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + for (let uid = 1; uid <= 200; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false + }); + } + let calls = 0; + let syncWorker: MailSyncWorker; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async () => { + calls += 1; + await syncWorker.stopAccount(mailAccount.id); + return { uidValidity: "1", messages: [] }; + } + }; + syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(calls, 1); +}); + +test("backfill persists each 50-message batch with bounded file writes", async () => { + const repository = new LocalFileAccountRepository(join(await mkdtemp(join(tmpdir(), "backfill-")), "state.json")); + const mailAccount = account(); + await repository.addAccount(mailAccount); + const total = 200; + for (let uid = 1; uid <= total; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false + }); + } + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => ({ + uidValidity: "1", + messages: uids.map((uid) => ({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false, + messageId: ``, + references: [] + })) + }) + }; + const internals = repository as unknown as { flush: () => Promise }; + const originalFlush = internals.flush.bind(repository); + let flushes = 0; + internals.flush = () => { + flushes += 1; + return originalFlush(); + }; + + const syncWorker = worker(repository as unknown as InMemoryAccountRepository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + + const inbox = await repository.listInbox(mailAccount.userId); + assert.ok(inbox.every((m) => m.messageId !== undefined)); + // 4 batches of 50; per-message writes would be 200. + assert.ok(flushes <= 8, `expected bounded writes, got ${flushes}`); +}); + +test("stopAccount waits for the in-flight backfill batch save and nothing is written after", async () => { + const mailAccount = account(); + const inner = new InMemoryAccountRepository(); + await inner.addAccount(mailAccount); + for (let uid = 1; uid <= 3; uid += 1) { + await inner.saveIncomingMessage({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), hasAttachments: false + }); + } + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + let saveStarted!: () => void; + const started = new Promise((resolve) => { saveStarted = resolve; }); + let saves = 0; + const repository = Object.create(inner) as InMemoryAccountRepository; + repository.saveIncomingMessage = async (message) => { + if (message.messageId !== undefined) { + saves += 1; + saveStarted(); + await gate; + } + return inner.saveIncomingMessage(message); + }; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => ({ + uidValidity: "1", + messages: uids.map((uid) => ({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), + hasAttachments: false, messageId: ``, references: [] + })) + }) + }; + const syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await started; + + let stopped = false; + const stopping = syncWorker.stopAccount(mailAccount.id).then(() => { stopped = true; }); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(stopped, false, "stopAccount must wait for the pending save"); + release(); + await stopping; + await inner.deleteAccount(mailAccount.id); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(saves, 3); + assert.equal((await inner.listInbox(mailAccount.userId)).length, 0); +}); + +test("backfill exposes threadBackfill while running and clears it on completion", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + await repository.saveIncomingMessage({ + accountId: mailAccount.id, providerMessageId: "1", mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(1), hasAttachments: false + }); + let during: string | undefined; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + during = (await repository.getAccount(mailAccount.id))?.threadBackfill; + return { uidValidity: "1", messages: uids.map((uid) => ({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), + hasAttachments: false, messageId: ``, references: [] + })) }; + } + }; + const syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(during, "running"); + assert.equal((await repository.getAccount(mailAccount.id))?.threadBackfill, undefined); +}); + +test("backfill target grouping stays linear for 60,000 stored messages", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + for (let uid = 1; uid <= 60_000; uid += 1) { + await repository.saveIncomingMessage({ + accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", + from: "a@example.com", subject: "old", receivedAt: new Date(uid), hasAttachments: false + }); + } + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async () => { throw new Error("stop"); } + }; + const syncWorker = worker(repository, imap); + const startedAt = Date.now(); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.ok(Date.now() - startedAt < 3000, "grouping 60,000 targets should be fast"); +}); + test("skips push but still stores mail when account notifications are off", async () => { const repository = new InMemoryAccountRepository(); const mailAccount = account(); diff --git a/apps/server/test/threading.test.ts b/apps/server/test/threading.test.ts new file mode 100644 index 0000000..406a988 --- /dev/null +++ b/apps/server/test/threading.test.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { IncomingMessageSummary } from "../src/domain/types.js"; +import { + MAX_REFERENCES, + boundMessageId, + computeThreadId, + parseMessageIds, + withThreadInfo +} from "../src/mail/threading.js"; + +function summary( + id: string, + extra: Partial +): IncomingMessageSummary { + return { + accountId: "a", + providerMessageId: id, + mailbox: "INBOX", + from: "x@example.com", + subject: "Hello", + receivedAt: new Date(), + hasAttachments: false, + ...extra + }; +} + +test("prefers the Gmail thread id", () => { + assert.equal( + computeThreadId({ gmailThreadId: "99", messageId: "" }), + "gm:99" + ); +}); + +test("uses the References root for replies and the message id for the root", () => { + const root = computeThreadId({ messageId: "" }); + const reply = computeThreadId({ + messageId: "", + inReplyTo: "", + references: ["", ""] + }); + assert.equal(root, reply); + assert.equal(computeThreadId({ inReplyTo: "" }), root); + assert.equal(computeThreadId({}), undefined); +}); + +test("does not group mail that only shares a subject", () => { + const list = withThreadInfo([ + summary("1", { messageId: "" }), + summary("2", { messageId: "" }), + summary("3", { messageId: "", references: [""] }), + summary("4", {}) + ]); + assert.deepEqual(list.map((item) => item.threadCount), [2, 1, 2, 1]); + assert.equal(list[3].threadId, undefined); +}); + +test("parses message ids from a References header", () => { + assert.deepEqual(parseMessageIds("\r\n "), ["", ""]); + assert.deepEqual(parseMessageIds(undefined), []); +}); + +test("resolves In-Reply-To ancestry to a common root without References", () => { + const list = withThreadInfo([ + summary("1", { messageId: "" }), + summary("2", { messageId: "", inReplyTo: "" }), + summary("3", { messageId: "", inReplyTo: "" }) + ]); + assert.deepEqual(list.map((item) => item.threadCount), [3, 3, 3]); +}); + +test("keeps the thread id short for very long message ids", () => { + const id = computeThreadId({ messageId: `<${"a".repeat(300)}@x>` })!; + assert.ok(id.length <= 100); +}); + +test("bounds a 4 MiB References header", () => { + const huge = "".repeat((4 * 1024 * 1024) / 3); + const ids = parseMessageIds(huge); + assert.ok(ids.length <= MAX_REFERENCES); + assert.ok(JSON.stringify(ids).length < 4096); +}); + +test("keeps root and latest ids of a long chain, drops over-long ids", () => { + const chain = Array.from({ length: 100 }, (_, i) => ``).join(" "); + const ids = parseMessageIds(chain); + assert.equal(ids.length, MAX_REFERENCES); + assert.equal(ids[0], ""); + assert.equal(ids.at(-1), ""); + assert.deepEqual(parseMessageIds(`<${"a".repeat(2000)}> `), [""]); +}); + +test("boundMessageId drops over-long values", () => { + assert.equal(boundMessageId(""), ""); + assert.equal(boundMessageId(`<${"a".repeat(5000)}>`), undefined); +}); + +test("resolves a 10,000-message reply chain in linear time", () => { + const n = 10_000; + const messages = Array.from({ length: n }, (_, i) => ({ + accountId: "a", + providerMessageId: String(i + 1), + mailbox: "INBOX", + from: "a@example.com", + subject: "s", + receivedAt: new Date(i * 1000), + hasAttachments: false, + messageId: ``, + inReplyTo: i === 0 ? undefined : `` + })); + // Worst case order: deepest message first, then the rest. + messages.reverse(); + const started = Date.now(); + const out = withThreadInfo(messages); + assert.ok(Date.now() - started < 1000); + assert.equal(new Set(out.map((m) => m.threadId)).size, 1); + assert.equal(out[0]!.threadCount, n); +});