From b17e8f271561dd918334ffe6784e26d5b3a4e4de Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:28 +0900 Subject: [PATCH 1/3] =?UTF-8?q?=ED=97=A4=EB=8D=94=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EB=A9=94=EC=9D=BC=20=EC=9E=90=EB=8F=99=20=EB=B6=84=EB=A5=98?= =?UTF-8?q?=EC=99=80=20=EB=B6=84=EB=A5=98=20=ED=83=AD=20=EC=B6=94=EA=B0=80?= =?UTF-8?q?=20(#37=201=EB=8B=A8=EA=B3=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/core/i18n/language_controller.dart | 4 ++ .../accounts/account_mailbox_page.dart | 25 ++++++++++- apps/client/lib/services/mail_api_client.dart | 3 ++ apps/server/package.json | 2 +- apps/server/src/domain/types.ts | 1 + apps/server/src/mail/ImapReceiver.ts | 14 ++++-- apps/server/src/mail/classifyMessage.ts | 45 +++++++++++++++++++ apps/server/test/classifyMessage.test.ts | 27 +++++++++++ 8 files changed, 116 insertions(+), 5 deletions(-) create mode 100644 apps/server/src/mail/classifyMessage.ts create mode 100644 apps/server/test/classifyMessage.test.ts diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 443bb5f..88f7e85 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -125,6 +125,10 @@ class AppStrings { String get syncRange => _ko ? '동기화 범위' : 'Sync range'; String get comingSoon => _ko ? '준비 중' : 'Coming soon'; String get noAccountSelected => _ko ? '계정을 선택하세요' : 'Select an account'; + String get categoryAll => _ko ? '전체' : 'All'; + String get categoryPerson => _ko ? '사람' : 'People'; + String get categoryNotification => _ko ? '알림' : 'Notifications'; + String get categoryNewsletter => _ko ? '뉴스레터' : 'Newsletters'; String get noMessagesForAccount => _ko ? '이 계정에 표시할 메일이 없습니다' : 'No mail for this account yet'; String get loadingAccountMail => _ko ? '메일을 가져오는 중입니다' : 'Importing mail'; diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index ed0617e..62e29a1 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -63,6 +63,7 @@ class _MailboxContent extends ConsumerStatefulWidget { class _MailboxContentState extends ConsumerState<_MailboxContent> { Timer? _refreshTimer; bool _refreshing = false; + String? _category; bool get _isSyncing => const {'syncing', 'validating'}.contains(widget.account.syncStatus); @@ -189,9 +190,31 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ), ], ), + Wrap( + spacing: 8, + children: [ + for (final (value, label) in [ + (null, strings.categoryAll), + ('person', strings.categoryPerson), + ('notification', strings.categoryNotification), + ('newsletter', strings.categoryNewsletter), + ]) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6), + child: ChoiceChip( + label: Text(label), + selected: _category == value, + onSelected: (_) => setState(() => _category = value), + ), + ), + ], + ), Expanded( child: messages.when( - data: (items) { + data: (all) { + final items = _category == null + ? all + : all.where((m) => m.category == _category).toList(); if (items.isEmpty) { return Center( child: Column( diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..ee0378c 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -259,8 +259,10 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, + this.category = 'person', }); + final String category; final String id; final String sender; final String subject; @@ -276,6 +278,7 @@ class MailSummary { snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), unread: true, + category: json['category'] as String? ?? 'person', ); } } diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..d34a85f 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/classifyMessage.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index ad7152b..c53d5dd 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -75,6 +75,7 @@ export interface IncomingMessageSummary { snippet?: string; receivedAt: Date; hasAttachments: boolean; + category?: "person" | "notification" | "newsletter"; } export interface IncomingMessageContent { diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 4160d89..1847149 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -17,6 +17,11 @@ import { newestFirstUidBatches } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; +import { + classificationHeaderNames, + classifyMessage, + parseRawHeaders +} from "./classifyMessage.js"; import { extractMessageLinks } from "./messageLinks.js"; export class ImapReceiver implements MailReceiver { @@ -299,7 +304,8 @@ export class ImapReceiver implements MailReceiver { for await (const message of client.fetch(uids, { envelope: true, flags: true, - uid: true + uid: true, + headers: classificationHeaderNames }, { uid: true })) { const summary = toIncomingMessage(account, mailbox, message); if (summary) batch.push(summary); @@ -333,14 +339,16 @@ function toIncomingMessage( const envelope = message.envelope; if (!envelope) return null; + const from = envelope.from?.map((item) => item.address).filter(Boolean).join(", ") ?? ""; return { accountId: account.id, providerMessageId: String(message.uid), mailbox, - from: envelope.from?.map((item) => item.address).filter(Boolean).join(", ") ?? "", + from, subject: envelope.subject ?? "", receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), - hasAttachments: false + hasAttachments: false, + category: classifyMessage(parseRawHeaders(message.headers), from) }; } diff --git a/apps/server/src/mail/classifyMessage.ts b/apps/server/src/mail/classifyMessage.ts new file mode 100644 index 0000000..5b230f5 --- /dev/null +++ b/apps/server/src/mail/classifyMessage.ts @@ -0,0 +1,45 @@ +export type MessageCategory = "person" | "notification" | "newsletter"; + +export const classificationHeaderNames = [ + "list-unsubscribe", + "list-id", + "precedence", + "auto-submitted" +]; + +// Parses a raw RFC 5322 header block into lowercase-name -> value (folded lines joined). +export function parseRawHeaders(raw: Buffer | string | undefined): Record { + const headers: Record = {}; + if (!raw) return headers; + const unfolded = raw.toString("utf8").replace(/\r?\n[ \t]+/g, " "); + for (const line of unfolded.split(/\r?\n/)) { + const index = line.indexOf(":"); + if (index <= 0) continue; + headers[line.slice(0, index).trim().toLowerCase()] = line.slice(index + 1).trim(); + } + return headers; +} + +const automatedLocalPart = + /^(no[-_.]?reply|do[-_.]?not[-_.]?reply|notifications?|alerts?|mailer-daemon|postmaster|bounces?)([-_.+].*)?$/i; + +export function classifyMessage( + headers: Record, + from: string +): MessageCategory { + const autoSubmitted = headers["auto-submitted"]?.toLowerCase(); + if (autoSubmitted && autoSubmitted !== "no") return "notification"; + + const precedence = headers["precedence"]?.toLowerCase(); + if ( + headers["list-unsubscribe"] || + headers["list-id"] || + (precedence && ["bulk", "list", "junk"].includes(precedence)) + ) { + return "newsletter"; + } + + const localPart = from.split(",")[0]?.split("@")[0]?.trim() ?? ""; + if (automatedLocalPart.test(localPart)) return "notification"; + return "person"; +} diff --git a/apps/server/test/classifyMessage.test.ts b/apps/server/test/classifyMessage.test.ts new file mode 100644 index 0000000..b0e3438 --- /dev/null +++ b/apps/server/test/classifyMessage.test.ts @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { classifyMessage, parseRawHeaders } from "../src/mail/classifyMessage.js"; + +test("parses folded headers case-insensitively", () => { + const h = parseRawHeaders("List-ID: \r\nPrecedence:\r\n bulk\r\n\r\n"); + assert.equal(h["list-id"], ""); + assert.equal(h["precedence"], "bulk"); +}); + +test("newsletter by List-Unsubscribe, List-Id or bulk precedence", () => { + assert.equal(classifyMessage({ "list-unsubscribe": "" }, "news@example.test"), "newsletter"); + assert.equal(classifyMessage({ "list-id": "" }, "a@example.test"), "newsletter"); + assert.equal(classifyMessage({ precedence: "Bulk" }, "a@example.test"), "newsletter"); +}); + +test("notification by Auto-Submitted or automated sender", () => { + assert.equal(classifyMessage({ "auto-submitted": "auto-generated" }, "a@example.test"), "notification"); + assert.equal(classifyMessage({ "auto-submitted": "no" }, "a@example.test"), "person"); + assert.equal(classifyMessage({}, "noreply@example.test"), "notification"); + assert.equal(classifyMessage({}, "no-reply+x@example.test"), "notification"); +}); + +test("person otherwise", () => { + assert.equal(classifyMessage({}, "alice@example.test"), "person"); + assert.equal(classifyMessage({}, ""), "person"); +}); From 8958654dc7f9b67127ed82774ceaf6f3eb5ffb8d Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:13:02 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EB=B6=84=EB=A5=98=20=EC=97=86=EB=8A=94=20?= =?UTF-8?q?=EA=B8=B0=EC=A1=B4=20=EB=A9=94=EC=9D=BC=EC=9D=B4=20=EC=82=AC?= =?UTF-8?q?=EB=9E=8C=20=ED=83=AD=EC=97=90=20=EB=AA=B0=EB=A6=AC=EB=8A=94=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 클라이언트: category가 없는 메일은 전체 탭에만 표시 - 서버: IMAP 동기화 후 category 없는 저장 메일을 헤더만 다시 조회해 채움(50개씩, 동기화당 최대 500개, 처리된 메일은 사람이어도 값을 저장해 재조회하지 않음) --- .../accounts/account_mailbox_page.dart | 4 +- apps/client/lib/services/mail_api_client.dart | 13 +++-- apps/client/test/widget_test.dart | 16 ++++++ apps/server/src/mail/ImapReceiver.ts | 15 ++++++ apps/server/src/workers/MailSyncWorker.ts | 46 +++++++++++++++++ apps/server/test/mailSyncWorker.test.ts | 51 +++++++++++++++++++ 6 files changed, 139 insertions(+), 6 deletions(-) diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 62e29a1..9bf0933 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -212,9 +212,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { Expanded( child: messages.when( data: (all) { - final items = _category == null - ? all - : all.where((m) => m.category == _category).toList(); + final items = filterByCategory(all, _category); if (items.isEmpty) { return Center( child: Column( diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index ee0378c..8693f9f 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -259,10 +259,11 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, - this.category = 'person', + this.category, }); - final String category; + /// Null until the server has classified the message. + final String? category; final String id; final String sender; final String subject; @@ -278,11 +279,17 @@ class MailSummary { snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), unread: true, - category: json['category'] as String? ?? 'person', + category: json['category'] as String?, ); } } +/// Unclassified mail (null category) shows only under "All". +List filterByCategory(List items, String? category) => + category == null + ? items + : items.where((m) => m.category == category).toList(); + 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..a5d7d92 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -504,6 +504,22 @@ void main() { Rect.fromLTRB(0, 24, 36, 44), ]); }); + + test('unclassified mail appears only under All', () { + MailSummary mail(String id, String? category) => MailSummary( + id: id, + sender: '', + subject: '', + snippet: '', + receivedAtLabel: '', + unread: true, + category: category, + ); + final items = [mail('1', null), mail('2', 'person'), mail('3', 'newsletter')]; + + expect(filterByCategory(items, null).map((m) => m.id), ['1', '2', '3']); + expect(filterByCategory(items, 'person').map((m) => m.id), ['2']); + }); } class _CredentialRecordingApi extends MailApiClient { diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 1847149..5f4cd42 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -108,6 +108,21 @@ export class ImapReceiver implements MailReceiver { } } + /** Re-reads classification headers of 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..4cd5c74 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 = 500; + private static readonly backfillBatch = 50; private readonly stopHandlers = new Map Promise>(); private readonly pollingTimers = new Map(); private readonly syncPromises = new Map>(); @@ -122,6 +124,16 @@ export class MailSyncWorker { } } + if (account.incomingProtocol === "imap" && isCurrent()) { + // Best effort: a failed backfill must not fail the sync itself. + await this.backfillCategories(account).catch((error: unknown) => { + console.warn("imap:category-backfill-failed", { + accountId: account.id, + error: error instanceof Error ? error.message : String(error) + }); + }); + } + if (!isCurrent()) return; account.syncStatus = "idle"; account.lastSyncedAt = new Date(); @@ -264,6 +276,40 @@ export class MailSyncWorker { }); } + // Messages stored before classification existed have no category and the + // 25-message sync never revisits them. Every processed message gets one + // (even "person"), so it is not fetched again. + private async backfillCategories(account: MailAccount): Promise { + const pending = (await this.accounts.listInbox(account.userId)) + .filter((message) => + message.accountId === account.id && + message.category === undefined && + /^\d+$/.test(message.providerMessageId)) + .slice(0, MailSyncWorker.backfillLimit); + + 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.category]) + ); + for (const message of batch) { + await this.accounts.saveIncomingMessage({ + ...message, + // Gone from the server: default to "person" so it is tried once. + category: fetched.get(message.providerMessageId) ?? "person" + }); + } + } + } + } + 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..cbefada 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -219,3 +219,54 @@ test("a failing push does not disturb mail handling", async () => { await syncWorker.stop(); } }); + +test("backfills categories 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 <= 520; 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; even uids are newsletters. + return uids.filter((uid) => uid !== 1).map((uid) => ({ + ...stored(uid), + category: uid % 2 === 0 ? "newsletter" as const : "person" as const + })); + } + }; + const syncWorker = worker(repository, imap); + + await syncWorker.syncAccount(mailAccount); + assert.equal(requests.length, 10); + assert.ok(requests.every((r) => r.length === 50)); + const byUid = async () => new Map( + (await repository.listInbox(mailAccount.userId)).map((m) => [m.providerMessageId, m]) + ); + // Newest first: uids 21..520 are done, the oldest 20 wait for the next sync. + assert.equal((await byUid()).get("100")?.category, "newsletter"); + assert.equal((await byUid()).get("101")?.category, "person"); + assert.equal((await byUid()).get("2")?.category, undefined); + + // Next sync handles the remaining 20 once, then nothing is refetched. + await syncWorker.syncAccount(mailAccount); + assert.equal((await byUid()).get("2")?.category, "newsletter"); + assert.equal((await byUid()).get("1")?.category, "person"); + assert.equal(requests.length, 11); + assert.equal(requests[10].length, 20); + await syncWorker.syncAccount(mailAccount); + assert.equal(requests.length, 11); +}); From b5386f3f432a7d467928116438bf917c119e49e3 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:17:53 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=EB=B6=84=EB=A5=98=20=EB=B3=B4=EC=A0=95=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=EC=9D=84=20=EB=B0=B0=EC=B9=98=20=EB=8B=A8?= =?UTF-8?q?=EC=9C=84=EB=A1=9C=20=EB=AC=B6=EC=96=B4=20=EC=83=81=ED=83=9C=20?= =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=93=B0=EA=B8=B0=20=ED=9A=9F=EC=88=98=20?= =?UTF-8?q?=EC=B6=95=EC=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/server/src/workers/MailSyncWorker.ts | 8 ++--- apps/server/test/mailSyncWorker.test.ts | 41 ++++++++++++++++++++++- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index 4cd5c74..2bf2abd 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -299,13 +299,13 @@ export class MailSyncWorker { account, mailbox, batch.map((m) => Number(m.providerMessageId)) )).map((m) => [m.providerMessageId, m.category]) ); - for (const message of batch) { - await this.accounts.saveIncomingMessage({ + // Concurrent saves let the file repository coalesce them into one write. + await Promise.all(batch.map((message) => + this.accounts.saveIncomingMessage({ ...message, // Gone from the server: default to "person" so it is tried once. category: fetched.get(message.providerMessageId) ?? "person" - }); - } + }))); } } } diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index cbefada..f8863a3 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -1,11 +1,15 @@ 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 type { IncomingMessageSummary, MailAccount } from "../src/domain/types.js"; import type { ImapReceiver } from "../src/mail/ImapReceiver.js"; import type { Pop3Receiver } from "../src/mail/Pop3Receiver.js"; import type { PushNotifier } from "../src/notifications/PushNotifier.js"; import { authenticationFailure } from "../src/mail/authenticationFailure.js"; import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; +import { LocalFileAccountRepository } from "../src/workers/LocalFileAccountRepository.js"; import { MailSyncWorker } from "../src/workers/MailSyncWorker.js"; function account(): MailAccount { @@ -24,7 +28,7 @@ function account(): MailAccount { }; } -function worker(repository: InMemoryAccountRepository, imap: object) { +function worker(repository: InMemoryAccountRepository | LocalFileAccountRepository, imap: object) { return new MailSyncWorker( repository, imap as ImapReceiver, @@ -270,3 +274,38 @@ test("backfills categories for stored messages once, in bounded batches", async await syncWorker.syncAccount(mailAccount); assert.equal(requests.length, 11); }); + +test("category backfill writes the state file once per batch", async () => { + const dir = await mkdtemp(join(tmpdir(), "backfill-")); + const repository = new LocalFileAccountRepository(join(dir, "state.json")); + 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 <= 100; uid += 1) { + await repository.saveIncomingMessage(stored(uid)); + } + const internals = repository as unknown as { flush: () => Promise }; + const originalFlush = internals.flush.bind(repository); + let flushes = 0; + internals.flush = () => { + flushes += 1; + return originalFlush(); + }; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => + uids.map((uid) => ({ ...stored(uid), category: "newsletter" as const })) + }; + + await worker(repository, imap).syncAccount(mailAccount); + // 2 batches of 50, plus a few sync status writes; per-message saves gave 100+. + assert.ok(flushes <= 6, `flushes=${flushes}`); +});