diff --git a/README.md b/README.md index 978f2c2..3637650 100644 --- a/README.md +++ b/README.md @@ -126,8 +126,9 @@ OpenAI-совместимого API (например, `http://localhost:11434/v ### Проверка только новых писем -Агент проверяет папки раз в минуту, получая только сообщения с UID после -сохранённого курсора. Если UIDNEXT не изменился, заголовки писем не запрашиваются. +При обнаружении новых UID агент сразу запускает анализ через общую очередь, +с коротким объединением событий за 100 мс. Минутная проверка получает только +сообщения с UID после сохранённого курсора и повторяет неудачные попытки. Если UIDNEXT не изменился, заголовки писем не запрашиваются. Тела загружаются только для новых писем без сохранённого решения. Курсор сохраняется между запусками и не продвигается за письмо с неудавшимся анализом. Успешные соседние результаты сохраняются и не требуют повторного запроса к ИИ. @@ -244,3 +245,37 @@ id; неполная или некорректная порция будет п но не увеличивает счётчик классифицированных писем. Вложения модели не передаются. Проверка редактора и подписи: `npm run test:compose`. + + +## Новая почта через IMAP IDLE + +Для каждого подключённого аккаунта открывается отдельное IMAP-соединение, +которое постоянно держит «Входящие» выбранными в режиме чтения. Оно не используется +для открытия писем, поиска, отправки или переключения папок. При поддержке IDLE +сервер сообщает о новых письмах без ожидания минутного таймера. Наблюдатель +выгружает все новые UID порциями по 100 заголовков, включая первое письмо пустого +ящика и письма, уже прочитанные другим клиентом. Получение заголовков не меняет +флаги прочитанности. + +После события обновляются список писем и счётчик непрочитанных, а при включённом +ИИ письмо сразу ставится в очередь анализа. Размер порции к модели и параллельность +берутся из настроек агента. Очередь общая для событий и периодического обхода: +анализы не запускаются параллельно сверх настройки, повторные события не создают +повторных решений и уведомлений. Событие во время проверки сохраняется до +освобождения очереди; во время полного обхода очередь новых писем проверяется +между страницами. + +После обрыва наблюдатель переподключается с паузами 1, 5, 30 и 60 секунд и +догружает UID после последнего полученного. После сна соединение перезапускается. +Смена UIDVALIDITY задаёт новую начальную границу, чтобы не уведомлять обо всём +пересозданном ящике. При удалении аккаунта, изменении подключения и выходе из +приложения старое наблюдение останавливается. + +Резервная проверка в основном процессе выполняется раз в минуту независимо от +открытой вкладки; она охватывает и другие папки, куда серверные правила могут +сразу переместить входящие письма. При отсутствии IDLE наблюдатель также проверяет +входящие раз в минуту. Общий фильтр повторов объединяет результаты IDLE и опроса. +Для ИИ недоступность модели сохраняет обычные уведомления; повторные попытки +в этом случае идут по минутному таймеру, а не на каждое новое событие. + +Проверка наблюдателя и фильтра повторов: `npm run test:realtime`. diff --git a/package.json b/package.json index 6a203f7..3b6d055 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "build:linux": "npm run build && electron-builder --linux", "build:win": "npm run build && electron-builder --win", "build:mac": "npm run build && electron-builder --mac", + "test:realtime": "node --experimental-strip-types --test tests/inbox-watcher.test.ts tests/new-mail-deduplicator.test.ts tests/imap-message.test.ts", "test:compose": "node --experimental-strip-types --test tests/compose*.test.ts", "test:navigation": "node --experimental-strip-types tests/message-navigation.test.ts", "test:agent": "node --experimental-strip-types --test tests/mail-agent*.test.ts", diff --git a/src/main/index.ts b/src/main/index.ts index ce92f01..6bc14e7 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,3 +1,8 @@ +import { NewMailDeduplicator } from './services/new-mail-deduplicator' +import { ImapInboxWatcher } from './services/inbox-watcher' +import { ImapInboxClientAdapter } from './providers/imap-inbox-client' +import { createImapClient } from './providers/imap-client' +import { watcherScheduler } from './services/watcher-scheduler' import type { ComposeSettings } from '@shared/types/compose' import { ComposeSettingsService } from './services/compose-settings-service' import { registerComposeSettingsHandlers } from './ipc/compose-settings.handler' @@ -31,7 +36,10 @@ import { updater } from './services/updater' import type { ComposeSession } from '@shared/types/message' import type { CalendarEvent } from '@shared/types/calendar' -const accountManager = new AccountManager() +const accountManager = new AccountManager((config, publish) => new ImapInboxWatcher( + () => new ImapInboxClientAdapter(createImapClient(config)), publish, + (error: Error): void => console.warn('[InboxWatcher] %s:', config.email, error.message), watcherScheduler +), new NewMailDeduplicator((): number => Date.now())) const retentionService = new RetentionService(accountManager) let mainWindowRef: BrowserWindow | null = null @@ -55,7 +63,8 @@ const mailAgent = new MailAgentService(accountManager, new JsonAgentHistoryRepository(mailAgentStore) ) accountManager.setMailNotificationFilter((event): boolean => mailAgent.filterNotification(event)) -app.on('before-quit', (): void => mailAgent.stop()) +accountManager.setNewMailObserver((event): void => mailAgent.enqueueNewMail(event)) +app.on('before-quit', (): void => { mailAgent.stop(); accountManager.disposeWatchers() }) /** «Открыть» в напоминании: выводим главное окно и показываем событие в календаре. */ function openEventInMainWindow(event: CalendarEvent): void { diff --git a/src/main/lib/imap-message.ts b/src/main/lib/imap-message.ts new file mode 100644 index 0000000..114175e --- /dev/null +++ b/src/main/lib/imap-message.ts @@ -0,0 +1,54 @@ +import type { Address, MessageEnvelope } from '@shared/types/message' + +export interface ImapBodyPart { + disposition?: string + childNodes?: ImapBodyPart[] +} + +interface ImapAddress { + name?: string + address?: string +} + +interface ImapEnvelopeMessage { + uid: number + internalDate?: Date | string + envelope?: { + subject?: string + from?: ImapAddress[] + to?: ImapAddress[] + cc?: ImapAddress[] + date?: Date + messageId?: string + inReplyTo?: string + } + flags?: Set + bodyStructure?: ImapBodyPart +} + +function mapAddresses(addresses: ImapAddress[] | undefined): Address[] { + return (addresses ?? []).map((address: ImapAddress): Address => ({ name: address.name ?? '', email: address.address ?? '' })) +} + +function hasAttachments(part: ImapBodyPart | undefined): boolean { + return Boolean(part && (part.disposition === 'attachment' || part.childNodes?.some(hasAttachments))) +} + +function getMessageDate(headerDate: Date | undefined, internalDate: Date | string | undefined): string { + if (headerDate && Number.isFinite(headerDate.getTime())) return headerDate.toISOString() + const received: Date = internalDate instanceof Date ? internalDate : new Date(internalDate ?? 0) + return Number.isFinite(received.getTime()) ? received.toISOString() : new Date(0).toISOString() +} + +export function convertImapMessage(message: ImapEnvelopeMessage, folderId: string): MessageEnvelope { + const flags: Set = message.flags ?? new Set() + return { + id: String(message.uid), folderId, subject: message.envelope?.subject ?? '(без темы)', + from: mapAddresses(message.envelope?.from)[0] ?? { name: '', email: '' }, + to: mapAddresses(message.envelope?.to), cc: mapAddresses(message.envelope?.cc), + date: getMessageDate(message.envelope?.date, message.internalDate), + flags: { seen: flags.has('\\Seen'), flagged: flags.has('\\Flagged'), answered: flags.has('\\Answered'), deleted: flags.has('\\Deleted') }, + hasAttachments: hasAttachments(message.bodyStructure), snippet: '', + messageId: message.envelope?.messageId, inReplyTo: message.envelope?.inReplyTo + } +} diff --git a/src/main/providers/imap-client.ts b/src/main/providers/imap-client.ts new file mode 100644 index 0000000..0b53da3 --- /dev/null +++ b/src/main/providers/imap-client.ts @@ -0,0 +1,14 @@ +import { ImapFlow } from 'imapflow' +import type { AccountConfig, ImapCredentials } from '@shared/types/account' + +export function createImapClient(config: AccountConfig): ImapFlow { + const credentials: ImapCredentials = config.credentials + return new ImapFlow({ + host: credentials.host, port: credentials.port, secure: credentials.secure, + auth: { user: credentials.username, pass: credentials.password }, + connectionTimeout: 10_000, greetingTimeout: 10_000, + maxIdleTime: 240_000, socketTimeout: 600_000, + disableAutoIdle: false, + logger: false + }) +} diff --git a/src/main/providers/imap-inbox-client.ts b/src/main/providers/imap-inbox-client.ts new file mode 100644 index 0000000..e8b7ac1 --- /dev/null +++ b/src/main/providers/imap-inbox-client.ts @@ -0,0 +1,44 @@ +import type { ImapFlow } from 'imapflow' +import type { InboxClient } from '../services/inbox-watcher' +import type { MessageEnvelope } from '@shared/types/message' +import type { MailCursor } from '@shared/types/mail-cursor' +import { convertImapMessage } from '../lib/imap-message' + +export class ImapInboxClientAdapter implements InboxClient { + private folderId: string = 'INBOX' + + constructor(private readonly client: ImapFlow) {} + + async connect(): Promise { await this.client.connect() } + + async selectInbox(): Promise { + const mailbox = await this.client.mailboxOpen('INBOX', { readOnly: true }) + this.folderId = mailbox.path + if (!this.client.capabilities.has('IDLE')) console.info('[InboxWatcher] Сервер не поддерживает IDLE, используется резервная проверка') + return { uidValidity: mailbox.uidValidity.toString(), nextUid: mailbox.uidNext } + } + + async fetchAfter(uid: number, limit: number): Promise { + const lock = await this.client.getMailboxLock(this.folderId, { readOnly: true }) + try { + const found = await this.client.search({ uid: `${uid + 1}:*` }, { uid: true }) + const page: number[] = (found || []).filter((value: number): boolean => value > uid) + .sort((first, second) => first - second).slice(0, limit) + if (!page.length) return [] + const messages: MessageEnvelope[] = [] + for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) { + messages.push(convertImapMessage(message, this.folderId)) + } + return messages + } finally { lock.release() } + } + + onChange(callback: () => void): void { this.client.on('exists', callback) } + + onDisconnect(callback: (error: Error) => void): void { + this.client.on('error', callback) + this.client.on('close', (): void => callback(new Error('Соединение наблюдения за входящими закрыто'))) + } + + close(): void { this.client.close() } +} diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index b02ebb6..4849c43 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -1,11 +1,14 @@ +import { createImapClient } from './imap-client' +import { convertImapMessage } from '../lib/imap-message' +import type { MailCursor } from '@shared/types/mail-cursor' import { getAccountEmail } from '@shared/utils/account-email' import { SmtpSendError } from '../lib/smtp-error' import { buildComposeAttachments } from '../lib/compose-attachments' -import { ImapFlow } from 'imapflow' +import type { ImapFlow } from 'imapflow' import { simpleParser } from 'mailparser' import nodemailer from 'nodemailer' import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider' -import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, InlineImage, Attachment } from '@shared/types/message' +import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message' import { SpecialFolderRole } from '@shared/types/folder' import type { Folder } from '@shared/types/folder' import type { AccountConfig, ImapCredentials } from '@shared/types/account' @@ -21,43 +24,18 @@ interface ImapMailbox { folders?: ImapMailbox[] } -// imapflow BodyStructure type -interface BodyPart { - part?: string - type?: string - subtype?: string - disposition?: string - parameters?: Record - id?: string - encoding?: string - childNodes?: BodyPart[] -} - export class ImapProvider implements IEmailProvider { private client: ImapFlow private connected = false private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null private closeCallback: (() => void) | null = null - // folderId → last known unseen count for polling - private lastUnseenCount = new Map() - // uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message - private notifiedUids = new Map() - private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes + private mailCursors: Map = new Map() + private readonly pollingFolders: Map> = new Map>() // Промис с именем отправителя из Sent-папки; await-ится в sendMessage() private senderNamePromise: Promise = Promise.resolve(null) constructor(private config: AccountConfig) { - const creds = config.credentials as ImapCredentials - this.client = new ImapFlow({ - host: creds.host, - port: creds.port, - secure: creds.secure, - auth: { - user: creds.username, - pass: creds.password - }, - logger: false - }) + this.client = createImapClient(config) // Без слушателя 'error' обрыв сокета превращается в uncaught exception в main this.client.on('error', (err: Error) => { console.warn('[IMAP] connection error:', err.message) @@ -73,14 +51,12 @@ export class ImapProvider implements IEmailProvider { this.closeCallback = callback } - getUnseenCounts(): Map { - return new Map(this.lastUnseenCount) + getMailCursors(): Map { + return new Map(this.mailCursors) } - seedUnseenCounts(counts: Map): void { - for (const [path, count] of counts) { - if (!this.lastUnseenCount.has(path)) this.lastUnseenCount.set(path, count) - } + seedMailCursors(cursors: Map): void { + this.mailCursors = new Map(cursors) } async connect(): Promise { @@ -178,11 +154,11 @@ export class ImapProvider implements IEmailProvider { for await (const msg of this.client.fetch(`${start}:${end}`, { uid: true, - envelope: true, + envelope: true, internalDate: true, flags: true, bodyStructure: true })) { - messages.push(this.convertMessage(msg, options.folderId)) + messages.push(convertImapMessage(msg, options.folderId)) } // Newest first @@ -209,11 +185,11 @@ export class ImapProvider implements IEmailProvider { const messages: MessageEnvelope[] = [] for await (const msg of this.client.fetch(uidSet, { uid: true, - envelope: true, + envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) { - messages.push(this.convertMessage(msg, options.folderId)) + messages.push(convertImapMessage(msg, options.folderId)) } // Fetch returns ascending order → reverse to newest first messages.sort((a, b) => Number(b.id) - Number(a.id)) @@ -229,8 +205,8 @@ export class ImapProvider implements IEmailProvider { const page: number[] = uids.slice(0, limit) if (!page.length) return { messages: [], total: 0, unseen: 0 } const messages: MessageEnvelope[] = [] - for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) { - messages.push(this.convertMessage(message, folderId)) + for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) { + messages.push(convertImapMessage(message, folderId)) } messages.sort((first: MessageEnvelope, second: MessageEnvelope): number => Number(first.id) - Number(second.id)) return { messages, total: uids.length, unseen: messages.filter((message: MessageEnvelope): boolean => !message.flags.seen).length } @@ -534,8 +510,8 @@ export class ImapProvider implements IEmailProvider { onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void { this.newMailCallback = callback this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => { - // Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо) - if (data.prevCount > 0 && data.count > data.prevCount) { + // Первый STATUS задаёт границу, события после неё проверяются по UID. + if (data.count > data.prevCount) { // Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения this.pollSingleFolder(data.path).catch(() => {}) } @@ -597,9 +573,9 @@ export class ImapProvider implements IEmailProvider { const remaining = limit - results.length const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining) for await (const msg of this.client.fetch(sorted.join(','), { - uid: true, envelope: true, flags: true, bodyStructure: true + uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) { - results.push(this.convertMessage(msg, folder.path)) + results.push(convertImapMessage(msg, folder.path)) } } } catch (e) { @@ -628,71 +604,48 @@ export class ImapProvider implements IEmailProvider { if (!this.newMailCallback) return try { await this.pollFolderTree([{ name: folderPath, path: folderPath }]) - } catch { /* ignore */ } + } catch (error: unknown) { console.warn('[IMAP] Ошибка проверки после EXISTS:', error) } } private async pollFolderTree(folders: ImapMailbox[]): Promise { for (const folder of folders) { - try { - const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null - // Если STATUS вернул null или упал — не трогаем сохранённый счётчик - if (status) { - const unseen = status.unseen ?? 0 - const prev = this.lastUnseenCount.get(folder.path) - this.lastUnseenCount.set(folder.path, unseen) - - if (prev !== undefined && unseen > prev && this.newMailCallback) { - // Получаем последнее непрочитанное письмо для уведомления - const lock = await this.client.getMailboxLock(folder.path) - try { - const uids = await this.client.search({ seen: false }, { uid: true }) as number[] - if (uids?.length) { - const latestUid = Math.max(...uids).toString() - const dedupKey = `${folder.path}:${latestUid}` - if (!this.isRecentlyNotified(dedupKey)) { - for await (const msg of this.client.fetch(latestUid, { - uid: true, envelope: true, flags: true - }, { uid: true })) { - this.markNotified(dedupKey) - this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) - break - } - } - } - } finally { - lock.release() - } - } - } - } catch (err) { - // Соединение умерло — не перебираем остальные папки с той же ошибкой - if (!this.connected) throw err - console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message) - } - - if (folder.folders?.length) { - await this.pollFolderTree(folder.folders) + try { await this.pollMailbox(folder.path) } catch (error: unknown) { + if (!this.connected) throw error + console.warn('[IMAP] Ошибка проверки папки %s:', folder.path, error) } + if (folder.folders?.length) await this.pollFolderTree(folder.folders) } } - private isRecentlyNotified(key: string): boolean { - const expiry = this.notifiedUids.get(key) - if (expiry === undefined) return false - if (Date.now() < expiry) return true - this.notifiedUids.delete(key) - return false + private pollMailbox(folderPath: string): Promise { + const pending: Promise | undefined = this.pollingFolders.get(folderPath) + if (pending) return pending + const task: Promise = this.checkMailbox(folderPath).finally(() => this.pollingFolders.delete(folderPath)) + this.pollingFolders.set(folderPath, task) + return task } - private markNotified(key: string): void { - // Чистим старые записи при росте кэша - if (this.notifiedUids.size > 200) { - const now = Date.now() - for (const [k, exp] of this.notifiedUids) { - if (now >= exp) this.notifiedUids.delete(k) + private async checkMailbox(folderPath: string): Promise { + const status = await this.client.status(folderPath, { uidNext: true, uidValidity: true }) + if (!status || !status.uidNext || status.uidValidity === undefined) return + const snapshot: MailCursor = { nextUid: status.uidNext, uidValidity: status.uidValidity.toString() } + const previous: MailCursor | undefined = this.mailCursors.get(folderPath) + if (!previous || previous.uidValidity !== snapshot.uidValidity) { + this.mailCursors.set(folderPath, snapshot) + return + } + let afterUid: number = previous.nextUid - 1 + while (afterUid + 1 < snapshot.nextUid && this.newMailCallback) { + const page = await this.listMessagesAfterUid(folderPath, afterUid, 100) + const messages: MessageEnvelope[] = page.messages.filter((message: MessageEnvelope): boolean => Number(message.id) < snapshot.nextUid) + if (!messages.length) break + for (const message of messages) { + this.newMailCallback?.(folderPath, message) + afterUid = Math.max(afterUid, Number(message.id)) + this.mailCursors.set(folderPath, { ...snapshot, nextUid: afterUid + 1 }) } } - this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS) + this.mailCursors.set(folderPath, snapshot) } // ---- Private helpers ---- @@ -732,48 +685,6 @@ export class ImapProvider implements IEmailProvider { return SpecialFolderRole.None } - private convertMessage(msg: unknown, folderId: string): MessageEnvelope { - const m = msg as { - uid: number - envelope: { - subject?: string - from?: Array<{ name?: string; address?: string }> - to?: Array<{ name?: string; address?: string }> - cc?: Array<{ name?: string; address?: string }> - date?: Date - messageId?: string - inReplyTo?: string - } - flags: Set - bodyStructure?: BodyPart - } - - const addr = (list?: Array<{ name?: string; address?: string }>): Address[] => - (list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' })) - - const flags = m.flags ?? new Set() - - return { - id: String(m.uid), - folderId, - subject: m.envelope?.subject ?? '(no subject)', - from: addr(m.envelope?.from)[0] ?? { name: '', email: '' }, - to: addr(m.envelope?.to), - cc: addr(m.envelope?.cc), - date: m.envelope?.date?.toISOString() ?? new Date().toISOString(), - flags: { - seen: flags.has('\\Seen'), - flagged: flags.has('\\Flagged'), - answered: flags.has('\\Answered'), - deleted: flags.has('\\Deleted') - }, - hasAttachments: this.hasAttachments(m.bodyStructure), - snippet: '', - messageId: m.envelope?.messageId ?? undefined, - inReplyTo: m.envelope?.inReplyTo ?? undefined, - } - } - private static buildComposeHtml(compose: ComposeData): string | undefined { if (!compose.contentHtml && !compose.htmlBody) return undefined const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '') @@ -852,10 +763,5 @@ export class ImapProvider implements IEmailProvider { .trim() } - private hasAttachments(node?: BodyPart): boolean { - if (!node) return false - if (node.disposition === 'attachment') return true - if (node.childNodes) return node.childNodes.some((c) => this.hasAttachments(c)) - return false - } + } diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index 3a1199d..834da8f 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -1,3 +1,5 @@ +import type { InboxWatcher } from './inbox-watcher' +import type { MailDeduplicator } from './new-mail-deduplicator' import type { IncomingMail } from './mail-agent-notifications' import { BrowserWindow, powerMonitor } from 'electron' import type { AccountConfig, ImapCredentials } from '@shared/types/account' @@ -25,13 +27,20 @@ export class AccountManager { private calendarProviders = new Map() private store: Store private credentialStore: CredentialStore + private fallbackTimer: ReturnType | null = null + private readonly pollingAccounts: Map> = new Map>() + private readonly inboxWatchers: Map = new Map() + private onNewMail: (event: IncomingMail) => void = (): void => {} private mainWindow: BrowserWindow | null = null private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false // Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис private reconnecting = new Map>() private reconnectTimers = new Map>() - constructor() { + constructor( + private readonly createInboxWatcher: (config: AccountConfig, publish: (messages: MessageEnvelope[]) => void) => InboxWatcher, + private readonly newMailDeduplicator: MailDeduplicator + ) { this.store = new Store({ name: 'accounts', defaults: { accounts: [] } @@ -39,10 +48,47 @@ export class AccountManager { this.credentialStore = new CredentialStore('credentials.json') // После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса powerMonitor.on('resume', () => { + for (const watcher of this.inboxWatchers.values()) watcher.restart() for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId) }) } + setNewMailObserver(observer: (event: IncomingMail) => void): void { + this.onNewMail = observer + } + + disposeWatchers(): void { + if (this.fallbackTimer) clearInterval(this.fallbackTimer) + this.fallbackTimer = null + for (const watcher of this.inboxWatchers.values()) watcher.stop() + this.inboxWatchers.clear() + } + + private stopInboxWatcher(accountId: string): void { + this.inboxWatchers.get(accountId)?.stop() + this.inboxWatchers.delete(accountId) + } + + private ensureInboxWatcher(config: AccountConfig): void { + if (this.inboxWatchers.has(config.id)) return + const watcher: InboxWatcher = this.createInboxWatcher(config, (messages: MessageEnvelope[]): void => { + for (const envelope of messages) this.handleNewMail({ accountId: config.id, folderId: envelope.folderId, envelope }) + }) + this.inboxWatchers.set(config.id, watcher) + watcher.start() + } + + private handleNewMail(event: IncomingMail): void { + if (!this.newMailDeduplicator.accept(event)) return + let agentEnabled: boolean = false + try { agentEnabled = this.filterMailNotification(event) } catch (error: unknown) { + console.error('[AccountManager] Не удалось применить фильтр ИИ:', error) + if (this.mainWindow && !this.mainWindow.isDestroyed()) this.mainWindow.webContents.send('agent:error', { message: error instanceof Error ? error.message : String(error) }) + } + if (this.mainWindow && !this.mainWindow.isDestroyed()) this.mainWindow.webContents.send('mail:new', { ...event, agentEnabled }) + try { this.onNewMail(event) } catch (error: unknown) { console.error('[AccountManager] Не удалось поставить письмо в очередь ИИ:', error) } + } + setMailNotificationFilter(provider: (event: IncomingMail) => boolean): void { this.filterMailNotification = provider } @@ -53,6 +99,9 @@ export class AccountManager { async initialize(): Promise { await this.credentialStore.load() + if (!this.fallbackTimer) this.fallbackTimer = setInterval((): void => { + for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId) + }, 60_000) } getAccounts(): AccountConfig[] { @@ -81,7 +130,7 @@ export class AccountManager { this.store.set('accounts', accounts) this.providers.set(config.id, provider) - this.setupNewMailListener(config.id, provider) + this.setupNewMailListener(config.id, provider, config) return { success: true } } catch (error) { @@ -90,6 +139,7 @@ export class AccountManager { } async removeAccount(accountId: string): Promise { + this.stopInboxWatcher(accountId) this.cancelScheduledReconnect(accountId) const provider = this.providers.get(accountId) if (provider) { @@ -140,7 +190,7 @@ export class AccountManager { const provider = this.createProvider(config) await provider.connect() this.providers.set(accountId, provider) - this.setupNewMailListener(accountId, provider) + this.setupNewMailListener(accountId, provider, config) return { success: true } } catch (error) { @@ -156,11 +206,13 @@ export class AccountManager { async pollNewMessages(accountId: string): Promise { if (!this.providers.has(accountId)) return - try { - await this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages()) - } catch (err) { - console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message) - } + const pending: Promise | undefined = this.pollingAccounts.get(accountId) + if (pending) return pending + const task: Promise = this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages()) + .catch((error: unknown): void => { console.warn('[AccountManager] Ошибка резервной проверки %s:', accountId, error) }) + .finally(() => this.pollingAccounts.delete(accountId)) + this.pollingAccounts.set(accountId, task) + return task } async sendMessage(accountId: string, compose: ComposeData): Promise { @@ -364,9 +416,9 @@ export class AccountManager { private async doReconnect(accountId: string): Promise { this.cancelScheduledReconnect(accountId) - // Убиваем старый провайдер, забирая его счётчики непрочитанных + // Убиваем старый провайдер, забирая его курсоры UID const old = this.providers.get(accountId) - const unseenCounts = old?.getUnseenCounts() + const mailCursors = old?.getMailCursors() if (old) { old.offNewMail() try { await old.disconnect() } catch { /* уже отвалился */ } @@ -391,9 +443,9 @@ export class AccountManager { const provider = this.createProvider(config) await provider.connect() // Без этого первое письмо после реконнекта не даст уведомления - if (unseenCounts) provider.seedUnseenCounts(unseenCounts) + if (mailCursors) provider.seedMailCursors(mailCursors) this.providers.set(accountId, provider) - this.setupNewMailListener(accountId, provider) + this.setupNewMailListener(accountId, provider, config) } // Фоновый реконнект после обрыва, с нарастающей паузой @@ -467,6 +519,7 @@ export class AccountManager { this.store.set('accounts', accounts) // Reconnect if currently connected + this.stopInboxWatcher(config.id) this.cancelScheduledReconnect(config.id) const existingProvider = this.providers.get(config.id) if (existingProvider) { @@ -477,7 +530,7 @@ export class AccountManager { const newProvider = this.createProvider(configWithCreds) await newProvider.connect() this.providers.set(config.id, newProvider) - this.setupNewMailListener(config.id, newProvider) + this.setupNewMailListener(config.id, newProvider, configWithCreds) } return { success: true } @@ -486,12 +539,9 @@ export class AccountManager { } } - private setupNewMailListener(accountId: string, provider: IEmailProvider): void { - provider.onNewMail((folderId, envelope) => { - if (this.mainWindow && !this.mainWindow.isDestroyed()) { - this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope, agentEnabled: this.filterMailNotification({ accountId, folderId, envelope }) }) - } - }) + private setupNewMailListener(accountId: string, provider: IEmailProvider, config: AccountConfig): void { + this.ensureInboxWatcher(config) + provider.onNewMail((folderId, envelope) => this.handleNewMail({ accountId, folderId, envelope })) provider.onClose(() => { // Игнорируем close устаревшего провайдера (его уже заменили) if (this.providers.get(accountId) !== provider) return diff --git a/src/main/services/inbox-watcher.ts b/src/main/services/inbox-watcher.ts new file mode 100644 index 0000000..50b5b3a --- /dev/null +++ b/src/main/services/inbox-watcher.ts @@ -0,0 +1,160 @@ +import type { MessageEnvelope } from '@shared/types/message' +import type { MailCursor } from '@shared/types/mail-cursor' + +export interface InboxClient { + connect(): Promise + selectInbox(): Promise + fetchAfter(uid: number, limit: number): Promise + onChange(callback: () => void): void + onDisconnect(callback: (error: Error) => void): void + close(): void +} + +export interface WatcherScheduler { + after(milliseconds: number, callback: () => void): () => void + every(milliseconds: number, callback: () => void): () => void +} + +export interface InboxWatcher { + start(): void + stop(): void + restart(): void +} + +const RETRY_DELAYS: number[] = [1_000, 5_000, 30_000, 60_000] + +export class ImapInboxWatcher implements InboxWatcher { + private client: InboxClient | null = null + private cursor: { uidValidity: string; lastUid: number } | null = null + private stopped: boolean = true + private ready: boolean = false + private generation: number = 0 + private retries: number = 0 + private checking: Promise | null = null + private checkAgain: boolean = false + private cancelRetry: (() => void) | null = null + private cancelPoll: (() => void) | null = null + + private readonly createClient: () => InboxClient + private readonly publish: (messages: MessageEnvelope[]) => void + private readonly reportError: (error: Error) => void + private readonly scheduler: WatcherScheduler + + constructor( + createClient: () => InboxClient, + publish: (messages: MessageEnvelope[]) => void, + reportError: (error: Error) => void, + scheduler: WatcherScheduler + ) { + this.createClient = createClient + this.publish = publish + this.reportError = reportError + this.scheduler = scheduler + } + + start(): void { + if (!this.stopped) return + this.stopped = false + void this.connect() + } + + stop(): void { + this.stopped = true + this.generation++ + this.ready = false + this.checkAgain = false + this.cancelRetry?.() + this.cancelPoll?.() + this.cancelRetry = null + this.cancelPoll = null + const client: InboxClient | null = this.client + this.client = null + client?.close() + } + + restart(): void { + this.stop() + this.start() + } + + private isCurrent(client: InboxClient, generation: number): boolean { + return !this.stopped && this.client === client && this.generation === generation + } + + private async connect(): Promise { + const generation: number = ++this.generation + let client: InboxClient + try { client = this.createClient() } catch (error: unknown) { + this.retry(error instanceof Error ? error : new Error(String(error))) + return + } + this.client = client + client.onChange((): void => { if (this.isCurrent(client, generation)) void this.check(client, generation) }) + client.onDisconnect((error: Error): void => { if (this.isCurrent(client, generation)) this.fail(client, generation, error) }) + try { + await client.connect() + if (!this.isCurrent(client, generation)) return + const mailbox: MailCursor = await client.selectInbox() + if (!this.isCurrent(client, generation)) return + if (this.cursor?.uidValidity !== mailbox.uidValidity) this.cursor = { uidValidity: mailbox.uidValidity, lastUid: mailbox.nextUid - 1 } + this.ready = true + this.retries = 0 + this.cancelPoll = this.scheduler.every(60_000, (): void => { void this.check(client, generation) }) + await this.check(client, generation) + } catch (error: unknown) { + this.fail(client, generation, error instanceof Error ? error : new Error(String(error))) + } + } + + private check(client: InboxClient, generation: number): Promise { + if (!this.isCurrent(client, generation)) return Promise.resolve() + this.checkAgain = true + if (!this.ready) return Promise.resolve() + if (this.checking) return this.checking + const pending: Promise = this.drain(client, generation).catch((error: unknown): void => { + this.fail(client, generation, error instanceof Error ? error : new Error(String(error))) + }).finally((): void => { + if (this.checking === pending) this.checking = null + if (this.client && this.ready && this.checkAgain) void this.check(this.client, this.generation) + }) + this.checking = pending + return pending + } + + private async drain(client: InboxClient, generation: number): Promise { + while (this.isCurrent(client, generation) && this.cursor && this.checkAgain) { + this.checkAgain = false + while (this.isCurrent(client, generation) && this.cursor) { + const afterUid: number = this.cursor.lastUid + const messages: MessageEnvelope[] = await client.fetchAfter(afterUid, 100) + if (!this.isCurrent(client, generation)) return + const fresh: MessageEnvelope[] = messages.filter((message) => Number(message.id) > afterUid) + .sort((first, second) => Number(first.id) - Number(second.id)) + if (!fresh.length) break + this.publish(fresh) + this.cursor = { ...this.cursor, lastUid: Number(fresh[fresh.length - 1].id) } + } + } + } + + private fail(client: InboxClient, generation: number, error: Error): void { + if (!this.isCurrent(client, generation)) return + this.generation++ + this.client = null + this.ready = false + this.cancelPoll?.() + this.cancelPoll = null + client.close() + this.retry(error) + } + + private retry(error: Error): void { + this.reportError(error) + if (this.stopped) return + const delay: number = RETRY_DELAYS[Math.min(this.retries++, RETRY_DELAYS.length - 1)] + this.cancelRetry = this.scheduler.after(delay, (): void => { + this.cancelRetry = null + if (!this.stopped) void this.connect() + }) + } +} diff --git a/src/main/services/mail-agent-service.ts b/src/main/services/mail-agent-service.ts index d1e0705..3faec56 100644 --- a/src/main/services/mail-agent-service.ts +++ b/src/main/services/mail-agent-service.ts @@ -53,7 +53,14 @@ function validateAgentUrl(value: string): URL { return url } +interface QueuedAgentFolder { + accountId: string + folderId: string + firstUid: number +} + interface AccountScanContext { + firstUid?: number observed: Set historical: Set mode: 'incremental' | 'maintenance' @@ -72,6 +79,11 @@ function snapshotSignature(folders: Folder[]): string { type AgentEvent = IpcEventMap['agent:notification'] export class MailAgentService { + private readonly queuedFolders: Map = new Map() + private eventTimer: ReturnType | null = null + private drainingEvents: boolean = false + private realtimeRetryBlocked: boolean = false + private stopped: boolean = false private timer: ReturnType | null = null private running: boolean = false private revision: number = 0 @@ -93,22 +105,122 @@ export class MailAgentService { filterNotification(event: IncomingMail): boolean { if (!this.getSettings().enabled) return false + if (this.history.getDecision(getMailKey(event))) return true const baseline: FolderBaseline | undefined = this.getBaselines()[getFolderBaselineKey(event.accountId, event.folderId)] if (baseline && isExistingMessage(event.envelope.id, baseline)) return true return this.notifications.filter(event) } + enqueueNewMail(event: IncomingMail): void { + if (this.stopped || !this.getSettings().enabled || this.history.getDecision(getMailKey(event))) return + const uid: number = Number(event.envelope.id) + if (!Number.isSafeInteger(uid) || uid < 1) { this.recordError(new AgentSettingsError('Некорректный UID нового письма'), 'Очередь ИИ'); return } + const key: string = getFolderBaselineKey(event.accountId, event.folderId) + const baseline: FolderBaseline | undefined = this.getBaselines()[key] + if (baseline && isExistingMessage(event.envelope.id, baseline)) return + const previous: QueuedAgentFolder | undefined = this.queuedFolders.get(key) + this.queuedFolders.set(key, { accountId: event.accountId, folderId: event.folderId, firstUid: Math.min(previous?.firstUid ?? uid, uid) }) + this.scheduleNewMail() + } + + private scheduleNewMail(): void { + if (this.stopped || this.running || this.eventTimer || !this.queuedFolders.size || this.realtimeRetryBlocked || !this.notifications.isAvailable() || !this.getSettings().enabled) return + this.eventTimer = setTimeout((): void => { + this.eventTimer = null + void this.flushNewMail() + }, 100) + } + + async flushNewMail(): Promise { + if (this.stopped || this.running || !this.queuedFolders.size || this.realtimeRetryBlocked || !this.notifications.isAvailable() || !this.getSettings().enabled) return + if (this.eventTimer) clearTimeout(this.eventTimer) + this.eventTimer = null + const revision: number = this.beginRun() + try { await this.processQueuedFolders(revision) } + catch (error: unknown) { this.recordError(error, 'Немедленная проверка ИИ') } + finally { this.finishRun() } + } + + private captureBaselines(accountId: string, folders: Folder[], pending: QueuedAgentFolder[]): FolderBaselines { + const prepare = (items: Folder[]): Folder[] => items.map((folder: Folder): Folder => { + const target: QueuedAgentFolder | undefined = pending.find((item) => item.accountId === accountId && item.folderId === folder.id) + return { ...folder, uidNext: target && folder.uidNext !== undefined ? Math.min(folder.uidNext, target.firstUid) : folder.uidNext, children: prepare(folder.children) } + }) + const previous: FolderBaselines = this.getBaselines() + const next: FolderBaselines = captureFolderBaselines(accountId, prepare(folders), previous) + if (next !== previous) this.store.set('baselines', next) + return next + } + + private async processQueuedFolders(revision: number): Promise { + if (this.drainingEvents || !this.queuedFolders.size || this.stopped || this.realtimeRetryBlocked) return + const pending: QueuedAgentFolder[] = [...this.queuedFolders.values()] + this.queuedFolders.clear() + this.drainingEvents = true + try { + const accounts = this.manager.getAccounts() + for (const accountId of new Set(pending.map((item) => item.accountId))) { + if (revision !== this.revision || this.stopped || !this.getSettings().enabled) return + const account = accounts.find((item) => item.id === accountId) + if (!account) continue + const targets: QueuedAgentFolder[] = pending.filter((item) => item.accountId === accountId) + try { + const result = await this.manager.listFolders(accountId) + if (revision !== this.revision || this.stopped) return + this.captureBaselines(accountId, result.folders, targets) + const folders: Folder[] = flattenFolders(result.folders) + for (const target of targets) { + const folder: Folder | undefined = folders.find((item) => item.id === target.folderId) + if (!folder) throw new AgentSettingsError(`Папка ${target.folderId} нового письма не найдена`) + if (folder.statusError) throw new AgentSettingsError(folder.statusError) + this.progress = { ...this.progress, account: account.email, folder: folder.name } + const context: AccountScanContext = { observed: new Set(), historical: new Set(), mode: 'incremental', isInitialSnapshot: false, complete: true, firstUid: target.firstUid } + await this.scanFolder(account.id, account.email, account.label, folder, revision, context) + } + } catch (error: unknown) { + this.realtimeRetryBlocked = true + for (const target of targets) { + const key: string = getFolderBaselineKey(target.accountId, target.folderId) + const current: QueuedAgentFolder | undefined = this.queuedFolders.get(key) + this.queuedFolders.set(key, { ...target, firstUid: Math.min(target.firstUid, current?.firstUid ?? target.firstUid) }) + } + this.recordError(error, `Новые письма ${account.email}`) + } + } + } finally { this.drainingEvents = false } + } + + private beginRun(): number { + this.running = true + this.modelFailedInScan = false + this.realtimeRetryBlocked = false + this.pendingKeys.clear() + this.progress = { mode: 'incremental', running: true, startedAt: new Date().toISOString(), finishedAt: null, inspected: 0, total: 0, folder: '', account: '', pending: 0, errors: 0, estimatedSeconds: null } + return this.revision + } + + private finishRun(): void { + this.running = false + this.progress = { ...this.progress, running: false, finishedAt: new Date().toISOString() } + this.scheduleNewMail() + } + private getBaselines(): FolderBaselines { return this.store.get('baselines') ?? {} } async initialize(): Promise { + this.stopped = false await this.credentials.load() this.timer = setInterval((): void => { void this.scan() }, 60_000) void this.scan() } stop(): void { + this.stopped = true + this.queuedFolders.clear() + if (this.eventTimer) clearTimeout(this.eventTimer) + this.eventTimer = null this.revision++ if (this.timer) clearInterval(this.timer) this.timer = null @@ -140,7 +252,9 @@ export class MailAgentService { const decision: true | AgentDecision | undefined = this.history.getDecision(getMailKey({ accountId, folderId: envelope.folderId, envelope })) if (decision && decision !== true) return { ...envelope, agentDecision: decision } const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(accountId, envelope.folderId)] - return baseline && isExistingMessage(envelope.id, baseline) ? { ...envelope, agentDecision: this.getHistoricalDecision() } : envelope + if (baseline && isExistingMessage(envelope.id, baseline)) return { ...envelope, agentDecision: this.getHistoricalDecision() } + if (baseline) this.enqueueNewMail({ accountId, folderId: envelope.folderId, envelope }) + return envelope }) } @@ -231,17 +345,14 @@ export class MailAgentService { } async scan(): Promise { - if (this.running || !this.getSettings().enabled) return - this.running = true - this.modelFailedInScan = false - this.pendingKeys.clear() - this.progress = { mode: 'incremental', running: true, startedAt: new Date().toISOString(), finishedAt: null, inspected: 0, total: 0, folder: '', account: '', pending: 0, errors: 0, estimatedSeconds: null } - const revision: number = this.revision + if (this.stopped || this.running || !this.getSettings().enabled) return + const revision: number = this.beginRun() const plans: { id: string; email: string; name: string; folders: Folder[]; mode: 'incremental' | 'maintenance' }[] = [] try { const accounts = this.manager.getAccounts() const accountIds: Set = new Set(accounts.map((account) => account.id)) this.history.removeAccountsExcept(accountIds) + for (const [key, target] of this.queuedFolders) if (!accountIds.has(target.accountId)) this.queuedFolders.delete(key) const allObserved: Set = new Set() const completeAccounts: Set = new Set() const verifiedFolders: Map> = new Map>() @@ -251,9 +362,7 @@ export class MailAgentService { try { const { folders } = await this.manager.listFolders(account.id) if (revision !== this.revision || !this.getSettings().enabled) return - const previousBaselines: FolderBaselines = this.getBaselines() - const baselines: FolderBaselines = captureFolderBaselines(account.id, folders, previousBaselines) - if (baselines !== previousBaselines) this.store.set('baselines', baselines) + const baselines: FolderBaselines = this.captureBaselines(account.id, folders, [...this.queuedFolders.values()]) this.notifications.discardMatching((event: IncomingMail): boolean => { const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(event.accountId, event.folderId)] return Boolean(baseline && isExistingMessage(event.envelope.id, baseline)) @@ -297,8 +406,7 @@ export class MailAgentService { } } catch (error: unknown) { this.recordError(error, 'Обход почты') } finally { - this.running = false - this.progress = { ...this.progress, running: false, finishedAt: new Date().toISOString() } + this.finishRun() } } @@ -369,7 +477,8 @@ export class MailAgentService { const inspectedBeforePage: number = this.progress.inspected const checkpointKey: string = getFolderBaselineKey(accountId, folder.id) const checkpoint = this.store.get('checkpoints')?.[checkpointKey] - const savedUid: number = checkpoint?.uidValidity === baseline.uidValidity ? checkpoint.lastUid : baseline.nextUid - 1 + const checkpointUid: number = checkpoint?.uidValidity === baseline.uidValidity ? checkpoint.lastUid : baseline.nextUid - 1 + const savedUid: number = context.firstUid === undefined ? checkpointUid : Math.min(checkpointUid, context.firstUid - 1) const afterUid: number = offset > 0 && context.mode === 'incremental' ? offset : savedUid if (context.mode === 'incremental' && folder.uidNext !== undefined && folder.uidNext <= afterUid + 1) return const page = context.mode === 'maintenance' @@ -437,6 +546,7 @@ export class MailAgentService { } } this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length } + let hasNextPage: boolean if (context.mode === 'incremental') { const sorted: MessageEnvelope[] = [...page.messages].sort((first, second) => Number(first.id) - Number(second.id)) let lastUid: number = savedUid @@ -446,15 +556,19 @@ export class MailAgentService { if (!this.history.getDecision(key)) { checkpointBlocked = true; break } lastUid = Math.max(lastUid, Number(message.id)) } + const currentCheckpoint = this.store.get('checkpoints')?.[checkpointKey] + if (currentCheckpoint?.uidValidity === baseline.uidValidity) lastUid = Math.max(lastUid, currentCheckpoint.lastUid) if (!wasBlocked && lastUid > savedUid) this.store.set('checkpoints', { ...this.store.get('checkpoints'), [checkpointKey]: { accountId, folderId: folder.id, uidValidity: baseline.uidValidity, lastUid } }) - if (!sorted.length || sorted.length >= page.total) break - offset = Number(sorted[sorted.length - 1].id) + hasNextPage = sorted.length > 0 && sorted.length < page.total + if (sorted.length) offset = Number(sorted[sorted.length - 1].id) } else { offset += page.messages.length if (!page.messages.length && offset < page.total) context.complete = false if (offset < folder.totalCount && offset >= page.total) context.complete = false - if (!page.messages.length || offset >= page.total) break + hasNextPage = page.messages.length > 0 && offset < page.total } + if (!this.drainingEvents && this.queuedFolders.size) await this.processQueuedFolders(revision) + if (revision !== this.revision || !hasNextPage) break } } } diff --git a/src/main/services/new-mail-deduplicator.ts b/src/main/services/new-mail-deduplicator.ts new file mode 100644 index 0000000..4e8e38d --- /dev/null +++ b/src/main/services/new-mail-deduplicator.ts @@ -0,0 +1,27 @@ +import { createHash } from 'node:crypto' +import type { IncomingMail } from './mail-agent-notifications' + +export interface MailDeduplicator { + accept(event: IncomingMail): boolean +} + +export class NewMailDeduplicator implements MailDeduplicator { + private readonly received: Map = new Map() + + private readonly now: () => number + + constructor(now: () => number) { this.now = now } + + accept(event: IncomingMail): boolean { + const timestamp: number = this.now() + const key: string = createHash('sha256').update(JSON.stringify([event.accountId, event.folderId, event.envelope.id, event.envelope.messageId, event.envelope.subject, event.envelope.from.email])).digest('hex') + if ((this.received.get(key) ?? 0) > timestamp) return false + for (const [id, expires] of this.received) if (expires <= timestamp) this.received.delete(id) + if (this.received.size >= 10_000) { + const oldest: string | undefined = this.received.keys().next().value + if (oldest) this.received.delete(oldest) + } + this.received.set(key, timestamp + 10 * 60_000) + return true + } +} diff --git a/src/main/services/watcher-scheduler.ts b/src/main/services/watcher-scheduler.ts new file mode 100644 index 0000000..0bfc12d --- /dev/null +++ b/src/main/services/watcher-scheduler.ts @@ -0,0 +1,12 @@ +import type { WatcherScheduler } from './inbox-watcher' + +export const watcherScheduler: WatcherScheduler = { + after(milliseconds: number, callback: () => void): () => void { + const timer: ReturnType = setTimeout(callback, milliseconds) + return (): void => clearTimeout(timer) + }, + every(milliseconds: number, callback: () => void): () => void { + const timer: ReturnType = setInterval(callback, milliseconds) + return (): void => clearInterval(timer) + } +} diff --git a/src/renderer/src/stores/accounts.store.ts b/src/renderer/src/stores/accounts.store.ts index b0978cb..ca4669c 100644 --- a/src/renderer/src/stores/accounts.store.ts +++ b/src/renderer/src/stores/accounts.store.ts @@ -28,8 +28,8 @@ export const useAccountsStore = defineStore('accounts', () => { connected: result.success, error: result.error } - // Инициализируем lastUnseenCount сразу после подключения — - // иначе первый autoCheckTimer только заполняет карту, а второй уже шлёт уведомления. + // Инициализируем курсоры новых UID сразу после подключения — + // иначе первый autoCheckTimer только заполняет курсоры, а второй уже шлёт уведомления. if (result.success) { invoke('messages:poll', { accountId: acc.id }).catch(() => {}) } diff --git a/src/renderer/src/stores/messages.store.ts b/src/renderer/src/stores/messages.store.ts index af47ffa..60d8550 100644 --- a/src/renderer/src/stores/messages.store.ts +++ b/src/renderer/src/stores/messages.store.ts @@ -467,8 +467,10 @@ export const useMessagesStore = defineStore('messages', () => { data.accountId === accountsStore.activeAccountId && data.folderId === foldersStore.activeFolderId ) { - messages.value.unshift(data.envelope) - totalCount.value++ + if (!messages.value.some((message: MessageEnvelope): boolean => message.id === data.envelope.id)) { + messages.value.unshift(data.envelope) + totalCount.value++ + } } if (!data.envelope.flags.seen) { foldersStore.updateFolderUnread(data.accountId, data.folderId, 1) diff --git a/src/shared/types/mail-cursor.ts b/src/shared/types/mail-cursor.ts new file mode 100644 index 0000000..407dbcf --- /dev/null +++ b/src/shared/types/mail-cursor.ts @@ -0,0 +1,4 @@ +export interface MailCursor { + uidValidity: string + nextUid: number +} diff --git a/src/shared/types/provider.ts b/src/shared/types/provider.ts index 7f8dff4..98a8d32 100644 --- a/src/shared/types/provider.ts +++ b/src/shared/types/provider.ts @@ -1,3 +1,4 @@ +import type { MailCursor } from './mail-cursor' import type { Folder } from './folder' import type { MessageEnvelope, MessageBody, MessageFlags, ComposeData } from './message' import type { FolderRetentionRule, RetentionCleanupResult } from './retention' @@ -35,9 +36,8 @@ export interface IEmailProvider { offNewMail(): void /** Вызывается, когда соединение закрылось не по инициативе приложения. */ onClose(callback: () => void): void - /** Счётчики непрочитанных по папкам — переносятся в новый провайдер при реконнекте. */ - getUnseenCounts(): Map - seedUnseenCounts(counts: Map): void + getMailCursors(): Map + seedMailCursors(cursors: Map): void pollNewMessages(): Promise searchMessages(query: string, limit: number): Promise sendMessage(compose: ComposeData): Promise diff --git a/tests/imap-message.test.ts b/tests/imap-message.test.ts new file mode 100644 index 0000000..feaa589 --- /dev/null +++ b/tests/imap-message.test.ts @@ -0,0 +1,18 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { convertImapMessage } from '../src/main/lib/imap-message.ts' + +test('общий преобразователь сохраняет UID, прочитанность и вложения', (): void => { + const converted = convertImapMessage({ uid: 12, envelope: { from: [{ name: 'Автор', address: 'user@example.org' }], subject: 'Тема', messageId: '' }, flags: new Set(['\\Seen']), bodyStructure: { childNodes: [{ disposition: 'attachment' }] }, internalDate: new Date('2026-11-17T12:00:00Z') }, 'INBOX') + assert.equal(converted.id, '12') + assert.equal(converted.flags.seen, true) + assert.equal(converted.hasAttachments, true) + assert.equal(converted.date, '2026-11-17T12:00:00.000Z') +}) + +test('письмо без Date не меняет идентичность при повторном чтении', (): void => { + const first = convertImapMessage({ uid: 1 }, 'INBOX') + const second = convertImapMessage({ uid: 1 }, 'INBOX') + assert.equal(first.date, second.date) + assert.equal(first.date, '1970-01-01T00:00:00.000Z') +}) diff --git a/tests/inbox-watcher.test.ts b/tests/inbox-watcher.test.ts new file mode 100644 index 0000000..fa58428 --- /dev/null +++ b/tests/inbox-watcher.test.ts @@ -0,0 +1,164 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { ImapInboxWatcher } from '../src/main/services/inbox-watcher.ts' +import type { InboxClient, WatcherScheduler } from '../src/main/services/inbox-watcher.ts' +import type { MessageEnvelope } from '../src/shared/types/message.ts' +import type { MailCursor } from '../src/shared/types/mail-cursor.ts' + +function message(uid: number): MessageEnvelope { + return { id: String(uid), folderId: 'INBOX', subject: 'Новое', date: '2026-11-17', from: { name: 'Автор', email: 'sender@example.org' }, to: [], cc: [], flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' } +} + +class TestScheduler implements WatcherScheduler { + readonly tasks: { interval: number; callback: () => void; active: boolean; repeated: boolean }[] = [] + after(interval: number, callback: () => void): () => void { + const task = { interval, callback, active: true, repeated: false } + this.tasks.push(task) + return (): void => { task.active = false } + } + every(interval: number, callback: () => void): () => void { + const task = { interval, callback, active: true, repeated: true } + this.tasks.push(task) + return (): void => { task.active = false } + } + run(interval: number): void { + const task = this.tasks.find((item) => item.active && item.interval === interval) + assert.ok(task) + if (!task.repeated) task.active = false + task.callback() + } +} + +class TestInboxClient implements InboxClient { + messages: MessageEnvelope[] = [] + validity: string = '1' + nextUid: number = 1 + active: number = 0 + maximum: number = 0 + closed: boolean = false + failure: Error | null = null + private change: () => void = (): void => {} + private disconnected: (error: Error) => void = (): void => {} + async connect(): Promise { if (this.failure) throw this.failure } + async selectInbox(): Promise { return { uidValidity: this.validity, nextUid: this.nextUid } } + async fetchAfter(uid: number, limit: number): Promise { + this.active++ + this.maximum = Math.max(this.active, this.maximum) + await Promise.resolve() + this.active-- + return this.messages.filter((item) => Number(item.id) > uid).slice(0, limit) + } + onChange(callback: () => void): void { this.change = callback } + onDisconnect(callback: (error: Error) => void): void { this.disconnected = callback } + close(): void { this.closed = true; this.disconnected(new Error('Закрыто')) } + emitChange(): void { this.change() } + disconnect(): void { this.disconnected(new Error('Обрыв соединения')) } +} + +async function settle(): Promise { for (let index: number = 0; index < 60; index++) await Promise.resolve() } + +test('наблюдатель загружает все новые UID, включая первое письмо пустого ящика, без параллельных проверок', async (): Promise => { + const client: TestInboxClient = new TestInboxClient() + const scheduler: TestScheduler = new TestScheduler() + const received: string[] = [] + const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => client, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): never => { throw error }, scheduler) + watcher.start() + await settle() + client.messages = Array.from({ length: 250 }, (_, index: number): MessageEnvelope => ({ ...message(index + 1), flags: { ...message(index + 1).flags, seen: index % 2 === 0 } })) + for (let index: number = 0; index < 10; index++) client.emitChange() + await settle() + assert.equal(received.length, 250) + assert.equal(new Set(received).size, 250) + assert.equal(received[0], '1') + assert.equal(received[249], '250') + assert.equal(client.maximum, 1) + watcher.stop() + assert.equal(scheduler.tasks.filter((task) => task.active).length, 0) +}) + +test('после переподключения догружает пропущенные UID и игнорирует события старого соединения', async (): Promise => { + const first: TestInboxClient = new TestInboxClient() + const second: TestInboxClient = new TestInboxClient() + const clients: TestInboxClient[] = [first, second] + const scheduler: TestScheduler = new TestScheduler() + const received: string[] = [] + const errors: string[] = [] + const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => { const client = clients.shift(); assert.ok(client); return client }, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): void => { errors.push(error.message) }, scheduler) + watcher.start() + await settle() + first.messages = [message(1)] + first.emitChange() + await settle() + first.disconnect() + second.nextUid = 4 + second.messages = [message(1), message(2), message(3)] + scheduler.run(1_000) + await settle() + first.emitChange() + await settle() + assert.deepEqual(received, ['1', '2', '3']) + assert.equal(errors.length, 1) + assert.equal(first.closed, true) + watcher.stop() +}) + +test('резервный таймер находит письма без события IDLE и остановка прекращает наблюдение', async (): Promise => { + const client: TestInboxClient = new TestInboxClient() + const scheduler: TestScheduler = new TestScheduler() + const received: string[] = [] + const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => client, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): never => { throw error }, scheduler) + watcher.start() + await settle() + client.messages = [message(1)] + scheduler.run(60_000) + await settle() + assert.deepEqual(received, ['1']) + watcher.stop() + client.messages.push(message(2)) + client.emitChange() + await settle() + assert.deepEqual(received, ['1']) +}) + +test('смена UIDVALIDITY не создаёт уведомлений обо всём существующем ящике', async (): Promise => { + const first: TestInboxClient = new TestInboxClient() + const second: TestInboxClient = new TestInboxClient() + second.validity = '2' + second.nextUid = 3 + second.messages = [message(1), message(2)] + const clients: TestInboxClient[] = [first, second] + const scheduler: TestScheduler = new TestScheduler() + const received: string[] = [] + const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => { const client = clients.shift(); assert.ok(client); return client }, (messages): void => { received.push(...messages.map((item) => item.id)) }, (): void => {}, scheduler) + watcher.start() + await settle() + watcher.restart() + await settle() + assert.deepEqual(received, []) + second.messages.push(message(3)) + second.emitChange() + await settle() + assert.deepEqual(received, ['3']) + watcher.stop() +}) + + +test('повторяет неудачные подключения с нарастающей паузой', async (): Promise => { + const scheduler: TestScheduler = new TestScheduler() + const errors: string[] = [] + const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => { + const client: TestInboxClient = new TestInboxClient() + client.failure = new Error('Подключение недоступно') + return client + }, (): void => {}, (error): void => { errors.push(error.message) }, scheduler) + watcher.start() + await settle() + scheduler.run(1_000) + await settle() + scheduler.run(5_000) + await settle() + assert.equal(errors.length, 3) + assert.ok(scheduler.tasks.some((task) => task.active && task.interval === 30_000)) + watcher.stop() + assert.equal(scheduler.tasks.filter((task) => task.active).length, 0) +}) diff --git a/tests/mail-agent-realtime.test.ts b/tests/mail-agent-realtime.test.ts new file mode 100644 index 0000000..c2691d2 --- /dev/null +++ b/tests/mail-agent-realtime.test.ts @@ -0,0 +1,159 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import Conf from 'conf' +import { loadAgentTestModule } from './helpers/agent-module.ts' +import { DEFAULT_AGENT_PROMPT } from '../src/shared/constants/agent.ts' +import { getFolderBaselineKey } from '../src/main/services/mail-agent-baseline.ts' +import type { MailAgentService, AgentStoreSchema } from '../src/main/services/mail-agent-service.ts' +import type { MessageEnvelope } from '../src/shared/types/message.ts' +import type { AccountType } from '../src/shared/types/account.ts' +import type { SpecialFolderRole } from '../src/shared/types/folder.ts' + +function message(uid: number): MessageEnvelope { + return { id: String(uid), folderId: 'INBOX', subject: 'Новое', date: '2026-11-17', from: { name: 'Автор', email: 'sender@example.org' }, to: [], cc: [], flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' } +} + +interface RealtimeState { + messages: MessageEnvelope[] + bodyRequests: number + fullRequests: number + beforeBody: (id: string) => Promise +} + +interface RealtimeFixture { + service: MailAgentService + store: Conf + state: RealtimeState + notifications: string[] + errors: string[] + failRequests: () => void + restoreRequests: () => void + close: () => Promise +} + +async function createFixture(): Promise { + const directory: string = await mkdtemp(join(tmpdir(), 'aero-realtime-')) + const environment = await loadAgentTestModule() + const store: Conf = new Conf({ cwd: directory, configName: 'mail-agent', defaults: { + settings: { enabled: true, notifyMutedFolders: false, prompt: DEFAULT_AGENT_PROMPT, pageSize: 100, batchSize: 2, concurrency: 2, url: 'http://localhost/v1', model: 'model' }, + processed: {}, baselines: {}, usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 } + } }) + const state: RealtimeState = { messages: [message(1)], bodyRequests: 0, fullRequests: 0, beforeBody: async (): Promise => {} } + const notifications: string[] = [] + const errors: string[] = [] + const service: MailAgentService = new environment.Service({ + getAccounts: () => [{ id: 'account', email: 'user@example.org', label: 'Пользователь', type: 'imap' as AccountType, credentials: { host: 'localhost', port: 993, secure: true, username: 'user', password: '' } }], + getConnectedAccountIds: (): string[] => ['account'], + listFolders: async () => ({ folders: [{ id: 'INBOX', name: 'Входящие', role: 'inbox' as SpecialFolderRole, parentId: null, totalCount: state.messages.length, unreadCount: 1, children: [], uidNext: state.messages.length + 1, uidValidity: '1' }] }), + listMessages: async () => { state.fullRequests++; return { messages: state.messages, total: state.messages.length, unseen: 1 } }, + listMessagesAfterUid: async (_accountId: string, _folderId: string, afterUid: number, limit: number) => { + const eligible: MessageEnvelope[] = state.messages.filter((item) => Number(item.id) > afterUid) + return { messages: eligible.slice(0, limit), total: eligible.length, unseen: 1 } + }, + fetchMessageBody: async (_accountId: string, _folderId: string, id: string) => { + state.bodyRequests++ + await state.beforeBody(id) + return { id, text: 'Требуется ответ', html: null, references: null, attachments: [], inlineImages: [] } + } + }, store, { load: async (): Promise => {}, get: (): undefined => undefined, save: async (): Promise => {} }, + (event): void => { notifications.push(event.envelope.id) }, (error): void => { errors.push(error) }, (): void => {}, new environment.History(store)) + return { service, store, state, notifications, errors, failRequests: environment.failRequests, restoreRequests: environment.restoreRequests, + close: async (): Promise => { service.stop(); await environment.server.close(); await rm(directory, { recursive: true, force: true }) } + } +} + +test('событие запускает ИИ без минутного таймера и не считает пришедшее письмо старым до первой проверки', async (): Promise => { + const fixture: RealtimeFixture = await createFixture() + try { + fixture.state.messages.push(message(2)) + const event = { accountId: 'account', folderId: 'INBOX', envelope: message(2) } + fixture.service.filterNotification(event) + fixture.service.enqueueNewMail(event) + await new Promise((resolve): void => { setTimeout(resolve, 250) }) + assert.deepEqual(fixture.notifications, ['2']) + assert.equal(fixture.state.bodyRequests, 1) + assert.equal(fixture.state.fullRequests, 0) + fixture.service.enqueueNewMail(event) + await fixture.service.flushNewMail() + await fixture.service.scan() + assert.deepEqual(fixture.notifications, ['2']) + assert.equal(fixture.state.bodyRequests, 1) + assert.equal(fixture.service.getMailStatistics().analyzed, 1) + } finally { await fixture.close() } +}) + +test('объединяет поступившую пачку с настройками ИИ и исключает повторные события', async (): Promise => { + const fixture: RealtimeFixture = await createFixture() + try { + fixture.state.messages.push(message(2), message(3)) + for (const uid of [2, 3, 2, 3]) fixture.service.enqueueNewMail({ accountId: 'account', folderId: 'INBOX', envelope: message(uid) }) + await fixture.service.flushNewMail() + assert.deepEqual(fixture.notifications, ['2', '3']) + assert.equal(fixture.state.bodyRequests, 2) + assert.equal(fixture.service.getUsage().measuredResponses, 1) + } finally { await fixture.close() } +}) + +test('событие во время текущего анализа не теряется и не откатывает курсор UID', async (): Promise => { + const fixture: RealtimeFixture = await createFixture() + try { + await fixture.service.scan() + fixture.state.messages.push(message(2)) + let signal: () => void = (): void => {} + let release: () => void = (): void => {} + const entered: Promise = new Promise((resolve): void => { signal = resolve }) + const gate: Promise = new Promise((resolve): void => { release = resolve }) + fixture.state.beforeBody = async (id: string): Promise => { if (id === '2') { signal(); await gate } } + const checking: Promise = fixture.service.scan() + await entered + fixture.state.messages.push(message(3)) + fixture.service.enqueueNewMail({ accountId: 'account', folderId: 'INBOX', envelope: message(3) }) + release() + await checking + assert.deepEqual(fixture.notifications, ['2', '3']) + assert.equal(fixture.state.bodyRequests, 2) + assert.equal(fixture.store.get('checkpoints')?.[getFolderBaselineKey('account', 'INBOX')].lastUid, 3) + await fixture.service.scan() + assert.equal(fixture.state.bodyRequests, 2) + } finally { await fixture.close() } +}) + +test('при сбое модели показывает резервное уведомление, а восстановление не дублирует его', async (): Promise => { + const fixture: RealtimeFixture = await createFixture() + try { + await fixture.service.scan() + fixture.state.messages.push(message(2)) + const event = { accountId: 'account', folderId: 'INBOX', envelope: message(2) } + assert.equal(fixture.service.filterNotification(event), true) + fixture.failRequests() + fixture.service.enqueueNewMail(event) + await fixture.service.flushNewMail() + assert.deepEqual(fixture.notifications, ['2']) + assert.ok(fixture.errors.length) + fixture.restoreRequests() + await fixture.service.scan() + assert.deepEqual(fixture.notifications, ['2']) + assert.equal(fixture.service.getMailStatistics().analyzed, 1) + } finally { await fixture.close() } +}) + + +test('загрузка списка запускает анализ пропущенного события даже при продвинутом курсоре', async (): Promise => { + const fixture: RealtimeFixture = await createFixture() + try { + await fixture.service.scan() + fixture.state.messages.push(message(2)) + const key: string = getFolderBaselineKey('account', 'INBOX') + fixture.store.set('checkpoints', { [key]: { accountId: 'account', folderId: 'INBOX', uidValidity: '1', lastUid: 2 } }) + fixture.service.annotateMessages('account', [message(1), message(2)]) + await new Promise((resolve): void => { setTimeout(resolve, 250) }) + assert.equal(fixture.state.bodyRequests, 1) + assert.equal(fixture.service.getMailStatistics().analyzed, 1) + assert.ok(fixture.service.annotateMessages('account', [message(2)])[0].agentDecision) + await fixture.service.flushNewMail() + assert.equal(fixture.state.bodyRequests, 1) + } finally { await fixture.close() } +}) diff --git a/tests/new-mail-deduplicator.test.ts b/tests/new-mail-deduplicator.test.ts new file mode 100644 index 0000000..b87aeb2 --- /dev/null +++ b/tests/new-mail-deduplicator.test.ts @@ -0,0 +1,19 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { NewMailDeduplicator } from '../src/main/services/new-mail-deduplicator.ts' +import type { IncomingMail } from '../src/main/services/mail-agent-notifications.ts' + +test('IDLE и резервный опрос не создают два события одного письма', (): void => { + let now: number = 1_000 + const deduplicator: NewMailDeduplicator = new NewMailDeduplicator((): number => now) + const event: IncomingMail = { accountId: 'account', folderId: 'INBOX', envelope: { + id: '1', folderId: 'INBOX', subject: 'Новое', date: '2026-11-17', from: { name: 'Автор', email: 'sender@example.org' }, + to: [], cc: [], flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' + } } + assert.equal(deduplicator.accept(event), true) + assert.equal(deduplicator.accept({ ...event, envelope: { ...event.envelope, date: '2026-11-18' } }), false) + assert.equal(deduplicator.accept({ ...event, folderId: 'Work' }), true) + assert.equal(deduplicator.accept({ ...event, accountId: 'other' }), true) + now += 600_001 + assert.equal(deduplicator.accept(event), true) +})