From c34172b9448140e5ce3821ad380586ef811c467d Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:22 +0900 Subject: [PATCH 1/7] =?UTF-8?q?=EA=B0=99=EC=9D=80=20=EB=8C=80=ED=99=94?= =?UTF-8?q?=EC=9D=98=20=EB=A9=94=EC=9D=BC=EC=9D=84=20=ED=95=9C=20=EC=8A=A4?= =?UTF-8?q?=EB=A0=88=EB=93=9C=EB=A1=9C=20=EB=AC=B6=EC=96=B4=20=EB=B3=B4?= =?UTF-8?q?=EA=B8=B0=20(1=EB=8B=A8=EA=B3=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Message-ID·In-Reply-To·References와 Gmail 스레드 ID를 요약에 저장하고, 목록을 스레드 ID로 묶어 통 수를 표시한다. 대화를 열면 시간순으로 보여주며 설정에서 대화 보기를 끌 수 있다. --- apps/client/lib/core/app_router.dart | 12 ++++ .../lib/core/i18n/language_controller.dart | 6 ++ .../accounts/account_mailbox_page.dart | 15 +++- .../features/accounts/account_providers.dart | 17 +++++ .../lib/features/accounts/thread_page.dart | 72 +++++++++++++++++++ .../lib/features/settings/settings_page.dart | 7 ++ apps/client/lib/services/mail_api_client.dart | 29 ++++++++ apps/client/test/widget_test.dart | 18 +++++ apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 27 ++++++- apps/server/src/domain/types.ts | 4 ++ apps/server/src/mail/ImapReceiver.ts | 11 ++- apps/server/src/mail/threading.ts | 37 ++++++++++ apps/server/test/threading.test.ts | 59 +++++++++++++++ 14 files changed, 308 insertions(+), 8 deletions(-) create mode 100644 apps/client/lib/features/accounts/thread_page.dart create mode 100644 apps/server/src/mail/threading.ts create mode 100644 apps/server/test/threading.test.ts diff --git a/apps/client/lib/core/app_router.dart b/apps/client/lib/core/app_router.dart index 7851c6a..e020bfd 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/settings/settings_page.dart'; @@ -32,6 +33,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 443bb5f..1ac288f 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -208,6 +208,12 @@ class AppStrings { String get pushNotificationsDescription => _ko ? '새 IMAP 메일은 서버 푸시를 통해 즉시 전달됩니다.' : 'New IMAP messages are delivered immediately through server push.'; + 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 registerThisDevice => _ko ? '이 기기 등록' : 'Register this device'; String get registerThisDeviceDescription => _ko ? '플랫폼 푸시 토큰을 메일 서버에 등록합니다.' diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index ed0617e..7123574 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -138,6 +138,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( @@ -191,7 +192,8 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ), Expanded( child: messages.when( - data: (items) { + data: (all) { + final items = threaded ? groupByThread(all) : all; if (items.isEmpty) { return Center( child: Column( @@ -250,9 +252,16 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { maxLines: 2, overflow: TextOverflow.ellipsis, ), - trailing: Text(message.receivedAtLabel), + trailing: 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}, ), ); diff --git a/apps/client/lib/features/accounts/account_providers.dart b/apps/client/lib/features/accounts/account_providers.dart index 8b9b875..d2f5c77 100644 --- a/apps/client/lib/features/accounts/account_providers.dart +++ b/apps/client/lib/features/accounts/account_providers.dart @@ -10,3 +10,20 @@ final accountMessagesProvider = FutureProvider.family, String>((ref, accountId) { return ref.watch(mailApiClientProvider).fetchAccountMessages(accountId); }); + +final threadMessagesProvider = FutureProvider.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 2fe1823..77cef0d 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), + ), SwitchListTile( value: true, onChanged: (_) {}, diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..ac957b7 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -59,6 +59,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> fetchAccounts() async { final response = await _dio.get>('/accounts'); final data = response.data ?? []; @@ -259,6 +272,8 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, + this.threadId, + this.threadCount = 1, }); final String id; @@ -267,6 +282,8 @@ class MailSummary { final String snippet; final String receivedAtLabel; final bool unread; + final String? threadId; + final int threadCount; factory MailSummary.fromJson(Map json) { return MailSummary( @@ -276,10 +293,22 @@ class MailSummary { snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), unread: true, + threadId: json['threadId'] as String?, + threadCount: json['threadCount'] as int? ?? 1, ); } } +/// 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, diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 52f8487..1f46fa5 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -504,6 +504,24 @@ void main() { Rect.fromLTRB(0, 24, 36, 44), ]); }); + + 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']); + }); } class _CredentialRecordingApi extends MailApiClient { diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..2c7bb4e 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/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/threading.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 6e2ebd1..9f09313 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -2,6 +2,7 @@ import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { MailSender } from "../mail/MailSender.js"; +import { withThreadInfo } from "../mail/threading.js"; import type { AuthMode, IncomingMessageContent, @@ -265,8 +266,30 @@ 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() + })); + }); + + 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 ad7152b..079fb41 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -75,6 +75,10 @@ export interface IncomingMessageSummary { snippet?: string; receivedAt: Date; hasAttachments: boolean; + messageId?: string; + inReplyTo?: string; + references?: string[]; + gmailThreadId?: string; } export interface IncomingMessageContent { diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 4160d89..3a0623f 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -18,6 +18,7 @@ import { } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; import { extractMessageLinks } from "./messageLinks.js"; +import { parseMessageIds } from "./threading.js"; export class ImapReceiver implements MailReceiver { private static readonly maxBodyBytes = 2 * 1024 * 1024; @@ -299,7 +300,9 @@ export class ImapReceiver implements MailReceiver { for await (const message of client.fetch(uids, { envelope: true, flags: true, - uid: true + uid: true, + threadId: true, + headers: ["references"] }, { uid: true })) { const summary = toIncomingMessage(account, mailbox, message); if (summary) batch.push(summary); @@ -340,7 +343,11 @@ function toIncomingMessage( from: envelope.from?.map((item) => item.address).filter(Boolean).join(", ") ?? "", subject: envelope.subject ?? "", receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), - hasAttachments: false + hasAttachments: false, + messageId: envelope.messageId, + inReplyTo: envelope.inReplyTo, + references: parseMessageIds(message.headers?.toString("utf8")), + gmailThreadId: message.threadId }; } diff --git a/apps/server/src/mail/threading.ts b/apps/server/src/mail/threading.ts new file mode 100644 index 0000000..4613577 --- /dev/null +++ b/apps/server/src/mail/threading.ts @@ -0,0 +1,37 @@ +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 ? `mid:${root}` : undefined; +} + +export function parseMessageIds(value: string | undefined): string[] { + return value?.match(/<[^<>\s]+>/g) ?? []; +} + +// Adds threadId and a per-thread message count to each summary. +export function withThreadInfo( + messages: T[] +): Array { + const withIds = messages.map((message) => ({ + ...message, + threadId: computeThreadId(message) + })); + 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/test/threading.test.ts b/apps/server/test/threading.test.ts new file mode 100644 index 0000000..c7b6059 --- /dev/null +++ b/apps/server/test/threading.test.ts @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { IncomingMessageSummary } from "../src/domain/types.js"; +import { + 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), []); +}); From fd070173a13463c5acaf9c55a2fdf8b6e735ea31 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:51:51 +0900 Subject: [PATCH 2/7] =?UTF-8?q?=EC=8A=A4=EB=A0=88=EB=93=9C=20=EB=AC=B6?= =?UTF-8?q?=EA=B8=B0=20=EB=B3=B4=EC=99=84:=20=EB=8B=B5=EC=9E=A5=20?= =?UTF-8?q?=EC=B2=B4=EC=9D=B8=20=EB=A3=A8=ED=8A=B8=20=ED=95=B4=EC=84=9D,?= =?UTF-8?q?=20=EC=8A=A4=EB=A0=88=EB=93=9C=20id=20=ED=95=B4=EC=8B=9C,=20?= =?UTF-8?q?=EC=8A=A4=EB=A0=88=EB=93=9C=20=EC=BA=90=EC=8B=9C=20autoDispose?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../features/accounts/account_providers.dart | 5 ++- apps/server/src/mail/threading.ts | 44 ++++++++++++++++--- apps/server/test/threading.test.ts | 14 ++++++ 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/apps/client/lib/features/accounts/account_providers.dart b/apps/client/lib/features/accounts/account_providers.dart index d2f5c77..77c9e7c 100644 --- a/apps/client/lib/features/accounts/account_providers.dart +++ b/apps/client/lib/features/accounts/account_providers.dart @@ -11,8 +11,9 @@ final accountMessagesProvider = return ref.watch(mailApiClientProvider).fetchAccountMessages(accountId); }); -final threadMessagesProvider = FutureProvider.family, - ({String accountId, String threadId})>((ref, key) { +final threadMessagesProvider = FutureProvider.autoDispose + .family, ({String accountId, String threadId})>( + (ref, key) { return ref .watch(mailApiClientProvider) .fetchThread(key.accountId, key.threadId); diff --git a/apps/server/src/mail/threading.ts b/apps/server/src/mail/threading.ts index 4613577..7c66347 100644 --- a/apps/server/src/mail/threading.ts +++ b/apps/server/src/mail/threading.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import type { IncomingMessageSummary } from "../domain/types.js"; // Gmail thread id wins; otherwise the first Reference (the conversation root), @@ -11,7 +12,32 @@ export function computeThreadId( ): string | undefined { if (message.gmailThreadId) return `gm:${message.gmailThreadId}`; const root = message.references?.[0] ?? message.inReplyTo ?? message.messageId; - return root ? `mid:${root}` : undefined; + 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)}`; +} + +// Without References, follows In-Reply-To through the supplied messages to the +// chain's root so A <- B <- C land in one thread. +function resolveRoot( + message: Pick, + byId: Map> +): string | undefined { + const seen = new Set(); + let current = message; + let root = current.references?.[0] ?? current.inReplyTo ?? current.messageId; + while (!current.references?.length && current.inReplyTo && !seen.has(current.inReplyTo)) { + seen.add(current.inReplyTo); + const parent = byId.get(current.inReplyTo); + if (!parent) break; + current = parent; + root = current.references?.[0] ?? current.inReplyTo ?? current.messageId; + } + return root; } export function parseMessageIds(value: string | undefined): string[] { @@ -22,10 +48,18 @@ export function parseMessageIds(value: string | undefined): string[] { export function withThreadInfo( messages: T[] ): Array { - const withIds = messages.map((message) => ({ - ...message, - threadId: computeThreadId(message) - })); + const byId = new Map(); + for (const message of messages) { + if (message.messageId) byId.set(message.messageId, message); + } + const withIds = messages.map((message) => { + let threadId = computeThreadId(message); + if (!message.gmailThreadId) { + const root = resolveRoot(message, byId); + 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); diff --git a/apps/server/test/threading.test.ts b/apps/server/test/threading.test.ts index c7b6059..75ef87c 100644 --- a/apps/server/test/threading.test.ts +++ b/apps/server/test/threading.test.ts @@ -57,3 +57,17 @@ 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); +}); From 3d6bdadbb3b10c5f8a079699552d64d586d2a850 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:55:44 +0900 Subject: [PATCH 3/7] =?UTF-8?q?=EA=B8=B0=EC=A1=B4=20=EC=A0=80=EC=9E=A5=20?= =?UTF-8?q?=EB=A9=94=EC=9D=BC=EC=9D=98=20=EC=8A=A4=EB=A0=88=EB=93=9C=20?= =?UTF-8?q?=EB=A9=94=ED=83=80=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EC=9D=BC?= =?UTF-8?q?=ED=9A=8C=EC=84=B1=20=EB=B3=B4=EC=B6=A9:=20=ED=97=A4=EB=8D=94?= =?UTF-8?q?=20=EC=97=86=EB=8A=94=20=EB=A9=94=EC=9D=BC=EC=9D=84=20=EB=8F=99?= =?UTF-8?q?=EA=B8=B0=ED=99=94=20=EB=95=8C=20=EC=B5=9C=EB=8C=80=20200?= =?UTF-8?q?=ED=86=B5=EC=94=A9=2050=ED=86=B5=20=EB=B0=B0=EC=B9=98=EB=A1=9C?= =?UTF-8?q?=20=EB=8B=A4=EC=8B=9C=20=EC=A1=B0=ED=9A=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/server/src/mail/ImapReceiver.ts | 15 ++++++++ apps/server/src/workers/MailSyncWorker.ts | 46 +++++++++++++++++++++++ apps/server/test/mailSyncWorker.test.ts | 41 ++++++++++++++++++++ 3 files changed, 102 insertions(+) diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 3a0623f..b0a220a 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -104,6 +104,21 @@ export class ImapReceiver implements MailReceiver { } } + /** Re-reads headers of already stored messages (one connection, one mailbox). */ + async fetchSummariesByUid( + account: MailAccount, + mailbox: string, + uids: number[] + ): Promise { + if (uids.length === 0) return []; + return this.withConnectionRetry(() => + this.withConnectedClient(account, async (client) => { + await client.mailboxOpen(mailbox, { readOnly: true }); + return this.fetchUids(client, account, mailbox, uids); + }) + ); + } + async fetchMessageContent( account: MailAccount, mailbox: string, diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index 06f543a..22048a1 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -16,6 +16,8 @@ export interface MailSyncWorkerOptions { } export class MailSyncWorker { + private static readonly backfillLimit = 200; + private static readonly backfillBatch = 50; private readonly stopHandlers = new Map Promise>(); private readonly pollingTimers = new Map(); private readonly syncPromises = new Map>(); @@ -122,6 +124,10 @@ export class MailSyncWorker { } } + if (account.incomingProtocol === "imap" && isCurrent()) { + await this.backfillThreadMetadata(account); + } + if (!isCurrent()) return; account.syncStatus = "idle"; account.lastSyncedAt = new Date(); @@ -264,6 +270,46 @@ export class MailSyncWorker { }); } + // Messages stored before threading existed have no header metadata and the + // 25-message sync never revisits them. Fetch it in bounded batches; a + // message still lacking it afterwards gets `references: []` so it is tried once. + private async backfillThreadMetadata(account: MailAccount): Promise { + 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)) + .slice(0, MailSyncWorker.backfillLimit); + if (pending.length === 0) return; + + const byMailbox = new Map(); + for (const message of pending) { + byMailbox.set(message.mailbox, [...(byMailbox.get(message.mailbox) ?? []), message]); + } + for (const [mailbox, stored] of byMailbox) { + for (let i = 0; i < stored.length; i += MailSyncWorker.backfillBatch) { + const batch = stored.slice(i, i + MailSyncWorker.backfillBatch); + const fetched = new Map( + (await this.imap.fetchSummariesByUid( + account, mailbox, batch.map((m) => Number(m.providerMessageId)) + )).map((m) => [m.providerMessageId, m]) + ); + for (const message of batch) { + const found = fetched.get(message.providerMessageId); + await this.accounts.saveIncomingMessage({ + ...message, + messageId: found?.messageId, + inReplyTo: found?.inReplyTo, + references: found?.references ?? [], + gmailThreadId: found?.gmailThreadId + }); + } + } + } + } + private initialSyncLimit(account: MailAccount): number | "all" | 0 { if (account.lastSyncedAt) return 25; if (account.initialSync?.includePreviousMessages === false) return 0; diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index d5e1cb8..9ff0afc 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -219,3 +219,44 @@ test("a failing push does not disturb mail handling", async () => { await syncWorker.stop(); } }); + +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 uids.filter((uid) => uid !== 1).map((uid) => ({ + ...stored(uid), + messageId: ``, + references: [""] + })); + } + }; + const syncWorker = worker(repository, imap); + + await syncWorker.syncAccount(mailAccount); + 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, ""); + assert.deepEqual(inbox.find((m) => m.providerMessageId === "1")?.references, []); + + await syncWorker.syncAccount(mailAccount); + assert.equal(requests.length, 3); +}); From 3d71fdc998b0c7a9cb97b992c9d9125e37b7fe5c Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:04:24 +0900 Subject: [PATCH 4/7] =?UTF-8?q?References=C2=B7Message-ID=20=ED=97=A4?= =?UTF-8?q?=EB=8D=94=20=ED=81=AC=EA=B8=B0=20=EC=A0=9C=ED=95=9C:=20?= =?UTF-8?q?=ED=8C=8C=EC=8B=B1=20=EC=A0=84=2016KiB=EB=A1=9C=20=EC=9E=90?= =?UTF-8?q?=EB=A5=B4=EA=B3=A0=20ID=20=EA=B8=B8=EC=9D=B4=20998=EC=9E=90?= =?UTF-8?q?=C2=B7=EA=B0=9C=EC=88=98=2020=EA=B0=9C(=EB=A3=A8=ED=8A=B8=20+?= =?UTF-8?q?=20=EC=B5=9C=EA=B7=BC=2019=EA=B0=9C)=EB=A1=9C=20=EC=A0=9C?= =?UTF-8?q?=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/server/src/mail/ImapReceiver.ts | 10 ++++++---- apps/server/src/mail/threading.ts | 18 +++++++++++++++++- apps/server/test/threading.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index b0a220a..0cd7424 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -18,7 +18,7 @@ import { } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; import { extractMessageLinks } from "./messageLinks.js"; -import { parseMessageIds } from "./threading.js"; +import { MAX_HEADER_BYTES, boundMessageId, parseMessageIds } from "./threading.js"; export class ImapReceiver implements MailReceiver { private static readonly maxBodyBytes = 2 * 1024 * 1024; @@ -359,9 +359,11 @@ function toIncomingMessage( subject: envelope.subject ?? "", receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), hasAttachments: false, - messageId: envelope.messageId, - inReplyTo: envelope.inReplyTo, - references: parseMessageIds(message.headers?.toString("utf8")), + messageId: boundMessageId(envelope.messageId), + inReplyTo: boundMessageId(envelope.inReplyTo), + references: parseMessageIds( + message.headers?.subarray(0, MAX_HEADER_BYTES).toString("utf8") + ), gmailThreadId: message.threadId }; } diff --git a/apps/server/src/mail/threading.ts b/apps/server/src/mail/threading.ts index 7c66347..d96006a 100644 --- a/apps/server/src/mail/threading.ts +++ b/apps/server/src/mail/threading.ts @@ -40,8 +40,24 @@ function resolveRoot( 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[] { - return value?.match(/<[^<>\s]+>/g) ?? []; + 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. diff --git a/apps/server/test/threading.test.ts b/apps/server/test/threading.test.ts index 75ef87c..72ea3fb 100644 --- a/apps/server/test/threading.test.ts +++ b/apps/server/test/threading.test.ts @@ -2,6 +2,8 @@ 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 @@ -71,3 +73,24 @@ 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); +}); From bb1804d0f8af1afdff5ccc628fc83913004364a1 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:13:05 +0900 Subject: [PATCH 5/7] =?UTF-8?q?=EC=8A=A4=EB=A0=88=EB=93=9C=20=EB=A9=94?= =?UTF-8?q?=ED=83=80=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EB=B3=B4=EC=B6=A9?= =?UTF-8?q?=EC=9D=84=20=EB=B0=B1=EA=B7=B8=EB=9D=BC=EC=9A=B4=EB=93=9C=2050?= =?UTF-8?q?=ED=86=B5=20=EB=B0=B0=EC=B9=98=EB=A1=9C=20=EB=81=9D=EA=B9=8C?= =?UTF-8?q?=EC=A7=80=20=EC=A7=84=ED=96=89=ED=95=98=EA=B3=A0,=20=EB=8B=B5?= =?UTF-8?q?=EC=9E=A5=20=EB=A3=A8=ED=8A=B8=20=ED=95=B4=EC=84=9D=EC=9D=84=20?= =?UTF-8?q?O(n)=EC=9C=BC=EB=A1=9C=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 동기화 뒤 헤더 없는 메일이 남아 있지 않을 때까지 배치 사이에 양보하며 계속 보충(계정 삭제·중지 시 중단, 재시작 시 이어서 진행) - In-Reply-To 루트 해석을 Message-ID별로 메모이즈해 긴 체인의 O(n²) 제거 --- apps/server/src/mail/threading.ts | 31 ++++++--- apps/server/src/workers/MailSyncWorker.ts | 49 ++++++++++--- apps/server/test/mailSyncWorker.test.ts | 85 ++++++++++++++++++++++- apps/server/test/threading.test.ts | 22 ++++++ 4 files changed, 170 insertions(+), 17 deletions(-) diff --git a/apps/server/src/mail/threading.ts b/apps/server/src/mail/threading.ts index d96006a..0cbdf44 100644 --- a/apps/server/src/mail/threading.ts +++ b/apps/server/src/mail/threading.ts @@ -21,22 +21,36 @@ 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. +// 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: Pick, - byId: Map> + 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 = current.references?.[0] ?? current.inReplyTo ?? current.messageId; - while (!current.references?.length && current.inReplyTo && !seen.has(current.inReplyTo)) { + 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) break; + if (!parent) { root = ownRoot(current); break; } current = parent; - root = current.references?.[0] ?? current.inReplyTo ?? current.messageId; } + for (const id of path) memo.set(id, root); return root; } @@ -68,10 +82,11 @@ export function withThreadInfo( 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); + const root = resolveRoot(message, byId, memo); threadId = root ? midThreadId(root) : undefined; } return { ...message, threadId }; diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index 22048a1..b6f352e 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -13,13 +13,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 backfillLimit = 200; 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 }>(); 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. @@ -125,7 +128,7 @@ export class MailSyncWorker { } if (account.incomingProtocol === "imap" && isCurrent()) { - await this.backfillThreadMetadata(account); + this.startBackfill(account); } if (!isCurrent()) return; @@ -141,6 +144,7 @@ export class MailSyncWorker { } async stop(): Promise { + this.backfills.clear(); for (const timer of this.pollingTimers.values()) clearInterval(timer); this.pollingTimers.clear(); @@ -153,6 +157,7 @@ export class MailSyncWorker { async stopAccount(accountId: string): Promise { this.syncPromises.delete(accountId); this.syncTokens.delete(accountId); + this.backfills.delete(accountId); const timer = this.pollingTimers.get(accountId); if (timer) { @@ -270,19 +275,43 @@ 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. Fetch it in bounded batches; a - // message still lacking it afterwards gets `references: []` so it is tried once. - private async backfillThreadMetadata(account: MailAccount): Promise { + // 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 done = this.backfillThreadMetadata(account, token) + .catch((error) => { + console.warn("imap:backfill-stopped", { + accountId: account.id, + error: error instanceof Error ? error.message : String(error) + }); + }) + .finally(() => { + if (this.backfills.get(account.id)?.token === token) { + this.backfills.delete(account.id); + } + }); + this.backfills.set(account.id, { token, done }); + } + + private async backfillThreadMetadata(account: MailAccount, token: object): 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)) - .slice(0, MailSyncWorker.backfillLimit); - if (pending.length === 0) return; + /^\d+$/.test(message.providerMessageId)); const byMailbox = new Map(); for (const message of pending) { @@ -290,12 +319,16 @@ export class MailSyncWorker { } for (const [mailbox, stored] of byMailbox) { 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 fetched = new Map( (await this.imap.fetchSummariesByUid( account, mailbox, batch.map((m) => Number(m.providerMessageId)) )).map((m) => [m.providerMessageId, m]) ); + if (!active()) return; for (const message of batch) { const found = fetched.get(message.providerMessageId); await this.accounts.saveIncomingMessage({ diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index 9ff0afc..5bb7de9 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -34,7 +34,8 @@ function worker(repository: InMemoryAccountRepository, imap: object) { mailbox: "INBOX", pop3PollIntervalMs: 60_000, imapReconnectBaseDelayMs: 1, - imapReconnectMaxDelayMs: 1 + imapReconnectMaxDelayMs: 1, + backfillYieldMs: 0 } ); } @@ -252,11 +253,93 @@ test("backfills thread metadata for stored messages once, in bounded batches", a 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, ""); 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 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 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 []; + } + }; + syncWorker = worker(repository, imap); + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(calls, 1); +}); diff --git a/apps/server/test/threading.test.ts b/apps/server/test/threading.test.ts index 72ea3fb..406a988 100644 --- a/apps/server/test/threading.test.ts +++ b/apps/server/test/threading.test.ts @@ -94,3 +94,25 @@ 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); +}); From 3e0a1b46cec38b2e89d5a8f8ddb31866abf9bdd1 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:19:03 +0900 Subject: [PATCH 6/7] =?UTF-8?q?=EB=B0=B1=ED=95=84=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=9D=84=20=EB=B0=B0=EC=B9=98=20=EB=8B=A8=EC=9C=84=EB=A1=9C=20?= =?UTF-8?q?=EB=AC=B6=EA=B3=A0,=20=EA=B3=84=EC=A0=95=20=EC=A4=91=EC=A7=80?= =?UTF-8?q?=C2=B7=EC=99=84=EB=A3=8C=20=EC=B2=98=EB=A6=AC=EC=99=80=20?= =?UTF-8?q?=EB=B6=84=EB=A5=98=20=EB=B9=84=EC=9A=A9=EC=9D=84=20=EA=B0=9C?= =?UTF-8?q?=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 50통 배치를 Promise.all로 저장해 LocalFile 저장소의 쓰기 병합을 활용 - stopAccount가 진행 중인 배치 저장을 기다려 삭제 후 쓰기를 막음 - threadBackfill 상태를 노출하고 메일함이 백필 중 폴링, 완료 시 목록 재조회 - 메일함별 분류를 push로 선형화 --- .../accounts/account_mailbox_page.dart | 12 +- apps/client/lib/services/mail_api_client.dart | 4 + apps/client/test/widget_test.dart | 66 ++++++++ apps/server/src/domain/types.ts | 2 + apps/server/src/workers/MailSyncWorker.ts | 42 ++++- apps/server/test/mailSyncWorker.test.ts | 150 ++++++++++++++++++ 6 files changed, 263 insertions(+), 13 deletions(-) diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 7123574..f48c2e6 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -64,8 +64,11 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { Timer? _refreshTimer; bool _refreshing = false; - 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() { @@ -76,8 +79,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { @override void didUpdateWidget(covariant _MailboxContent oldWidget) { super.didUpdateWidget(oldWidget); - final wasSyncing = - const {'syncing', 'validating'}.contains(oldWidget.account.syncStatus); + final wasSyncing = _busy(oldWidget.account); if (oldWidget.account.id == widget.account.id && wasSyncing && !_isSyncing) { @@ -88,7 +90,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { }); } if (oldWidget.account.id != widget.account.id || - oldWidget.account.syncStatus != widget.account.syncStatus) { + _busy(oldWidget.account) != _isSyncing) { _configureRefreshTimer(); } } diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index ac957b7..806d7e7 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -367,6 +367,7 @@ class MailAccountSummary { this.syncErrorCode, required this.initialSync, required this.lastSyncedAtLabel, + this.threadBackfilling = false, }); final String id; @@ -379,6 +380,8 @@ class MailAccountSummary { final String? syncErrorCode; final InitialSyncOption? initialSync; final String lastSyncedAtLabel; + // Server is still filling thread metadata for older messages. + final bool threadBackfilling; factory MailAccountSummary.fromJson(Map json) { return MailAccountSummary( @@ -395,6 +398,7 @@ class MailAccountSummary { json['initialSync'] as Map) : null, lastSyncedAtLabel: _formatReceivedAt(json['lastSyncedAt'] as String?), + threadBackfilling: json['threadBackfill'] == 'running', ); } } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 1f46fa5..b14030f 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -247,6 +247,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 { const account = MailAccountSummary( diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index 079fb41..4fe7d86 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -42,6 +42,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?: { diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index b6f352e..79d683d 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -22,7 +22,7 @@ export class MailSyncWorker { 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 }>(); + 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. @@ -144,7 +144,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(); @@ -157,7 +159,10 @@ export class MailSyncWorker { async stopAccount(accountId: string): Promise { 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) { @@ -288,22 +293,36 @@ export class MailSyncWorker { private startBackfill(account: MailAccount): void { if (this.backfills.has(account.id)) return; const token = {}; - const done = this.backfillThreadMetadata(account, 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); } }); - this.backfills.set(account.id, { token, done }); } - private async backfillThreadMetadata(account: MailAccount, token: object): Promise { + 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) => @@ -315,8 +334,13 @@ export class MailSyncWorker { const byMailbox = new Map(); for (const message of pending) { - byMailbox.set(message.mailbox, [...(byMailbox.get(message.mailbox) ?? []), message]); + 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) { for (let i = 0; i < stored.length; i += MailSyncWorker.backfillBatch) { // Yield first so sync and other accounts are not starved. @@ -329,16 +353,18 @@ export class MailSyncWorker { )).map((m) => [m.providerMessageId, m]) ); if (!active()) return; - for (const message of batch) { + // 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); - await this.accounts.saveIncomingMessage({ + return this.accounts.saveIncomingMessage({ ...message, messageId: found?.messageId, inReplyTo: found?.inReplyTo, references: found?.references ?? [], gmailThreadId: found?.gmailThreadId }); - } + })); + await entry.saving; } } } diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index 5bb7de9..aa6b91c 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"; @@ -343,3 +347,149 @@ test("backfill stops when the account is removed", async () => { 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[]) => + 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[]) => + 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 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"); +}); From 2ce553163400948b01e44a4c64318b19e18bf8a1 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:08:34 +0900 Subject: [PATCH 7/7] =?UTF-8?q?=EC=8A=A4=EB=A0=88=EB=93=9C=20backfill=20?= =?UTF-8?q?=EC=A4=91=20UIDVALIDITY=EA=B0=80=20=EB=B0=94=EB=80=90=20?= =?UTF-8?q?=EB=B0=B0=EC=B9=98=EB=A5=BC=20=EA=B1=B0=EB=B6=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit backfill 배치마다 메일함 open 결과의 UIDVALIDITY를 받아 첫 배치 값과 비교한다. 값이 다르면 같은 UID가 다른 메일을 가리키므로 헤더를 병합하거나 backfilled로 표시하지 않고 중단한다. --- apps/server/src/mail/ImapReceiver.ts | 11 ++-- apps/server/src/workers/MailSyncWorker.ts | 13 +++-- apps/server/test/mailSyncWorker.test.ts | 61 +++++++++++++++++++---- 3 files changed, 66 insertions(+), 19 deletions(-) diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 2a1e0bd..21f697b 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -139,12 +139,15 @@ export class ImapReceiver implements MailReceiver { account: MailAccount, mailbox: string, uids: number[] - ): Promise { - if (uids.length === 0) return []; + ): Promise<{ uidValidity: string; messages: IncomingMessageSummary[] }> { return this.withConnectionRetry(() => this.withConnectedClient(account, async (client) => { - await client.mailboxOpen(mailbox, { readOnly: true }); - return this.fetchUids(client, account, mailbox, uids); + 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) + }; }) ); } diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index f6e63b7..234fef5 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -404,16 +404,21 @@ export class MailSyncWorker { account.threadBackfill = "running"; await this.accounts.updateAccount(account); for (const [mailbox, stored] of byMailbox) { + let expectedUidValidity: string | 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 fetched = new Map( - (await this.imap.fetchSummariesByUid( - account, mailbox, batch.map((m) => Number(m.providerMessageId)) - )).map((m) => [m.providerMessageId, m]) + 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; // Concurrent saves share one coalesced file write instead of one per message. entry.saving = Promise.all(batch.map((message) => { diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index d2f3159..c7ce9a9 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -247,11 +247,11 @@ test("backfills thread metadata for stored messages once, in bounded batches", a 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 uids.filter((uid) => uid !== 1).map((uid) => ({ + return { uidValidity: "1", messages: uids.filter((uid) => uid !== 1).map((uid) => ({ ...stored(uid), messageId: ``, references: [""] - })); + })) }; } }; const syncWorker = worker(repository, imap); @@ -268,6 +268,41 @@ test("backfills thread metadata for stored messages once, in bounded batches", a 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 drains 4,000 stored messages across batches without refetching", async () => { const repository = new InMemoryAccountRepository(); const mailAccount = account(); @@ -290,7 +325,7 @@ test("backfill drains 4,000 stored messages across batches without refetching", fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { assert.ok(uids.length <= 50); seen.push(...uids); - return uids.map((uid) => ({ + return { uidValidity: "1", messages: uids.map((uid) => ({ accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", @@ -300,7 +335,7 @@ test("backfill drains 4,000 stored messages across batches without refetching", hasAttachments: false, messageId: ``, references: [] - })); + })) }; } }; const syncWorker = worker(repository, imap); @@ -339,7 +374,7 @@ test("backfill stops when the account is removed", async () => { fetchSummariesByUid: async () => { calls += 1; await syncWorker.stopAccount(mailAccount.id); - return []; + return { uidValidity: "1", messages: [] }; } }; syncWorker = worker(repository, imap); @@ -366,8 +401,9 @@ test("backfill persists each 50-message batch with bounded file writes", async ( } const imap = { fetchLatestBatches: async () => undefined, - fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => - uids.map((uid) => ({ + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => ({ + uidValidity: "1", + messages: uids.map((uid) => ({ accountId: mailAccount.id, providerMessageId: String(uid), mailbox: "INBOX", @@ -378,6 +414,7 @@ test("backfill persists each 50-message batch with bounded file writes", async ( messageId: ``, references: [] })) + }) }; const internals = repository as unknown as { flush: () => Promise }; const originalFlush = internals.flush.bind(repository); @@ -423,12 +460,14 @@ test("stopAccount waits for the in-flight backfill batch save and nothing is wri }; const imap = { fetchLatestBatches: async () => undefined, - fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => - uids.map((uid) => ({ + 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); @@ -459,11 +498,11 @@ test("backfill exposes threadBackfill while running and clears it on completion" fetchLatestBatches: async () => undefined, fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { during = (await repository.getAccount(mailAccount.id))?.threadBackfill; - return uids.map((uid) => ({ + 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);