Compare commits

...

2 commits

Author SHA1 Message Date
r.rasputin
a2105f3c81 Исключены заглушённые папки из анализа ИИ
Some checks failed
Release / release (push) Failing after 31s
2026-11-17 17:43:08 +07:00
r.rasputin
0f522b9dda Добавлена мгновенная проверка новых писем через ИИ 2026-11-17 17:39:51 +07:00
24 changed files with 1091 additions and 198 deletions

View file

@ -126,8 +126,9 @@ OpenAI-совместимого API (например, `http://localhost:11434/v
### Проверка только новых писем ### Проверка только новых писем
Агент проверяет папки раз в минуту, получая только сообщения с UID после При обнаружении новых UID агент сразу запускает анализ через общую очередь,
сохранённого курсора. Если UIDNEXT не изменился, заголовки писем не запрашиваются. с коротким объединением событий за 100 мс. Минутная проверка получает только
сообщения с UID после сохранённого курсора и повторяет неудачные попытки. Если UIDNEXT не изменился, заголовки писем не запрашиваются.
Тела загружаются только для новых писем без сохранённого решения. Курсор Тела загружаются только для новых писем без сохранённого решения. Курсор
сохраняется между запусками и не продвигается за письмо с неудавшимся анализом. сохраняется между запусками и не продвигается за письмо с неудавшимся анализом.
Успешные соседние результаты сохраняются и не требуют повторного запроса к ИИ. Успешные соседние результаты сохраняются и не требуют повторного запроса к ИИ.
@ -244,3 +245,42 @@ id; неполная или некорректная порция будет п
но не увеличивает счётчик классифицированных писем. Вложения модели не передаются. но не увеличивает счётчик классифицированных писем. Вложения модели не передаются.
Проверка редактора и подписи: `npm run test:compose`. Проверка редактора и подписи: `npm run test:compose`.
## Новая почта через IMAP IDLE
Для каждого подключённого аккаунта открывается отдельное IMAP-соединение,
которое постоянно держит «Входящие» выбранными в режиме чтения. Оно не используется
для открытия писем, поиска, отправки или переключения папок. При поддержке IDLE
сервер сообщает о новых письмах без ожидания минутного таймера. Наблюдатель
выгружает все новые UID порциями по 100 заголовков, включая первое письмо пустого
ящика и письма, уже прочитанные другим клиентом. Получение заголовков не меняет
флаги прочитанности.
После события обновляются список писем и счётчик непрочитанных, а при включённом
ИИ письмо сразу ставится в очередь анализа. Размер порции к модели и параллельность
берутся из настроек агента. Очередь общая для событий и периодического обхода:
анализы не запускаются параллельно сверх настройки, повторные события не создают
повторных решений и уведомлений. Событие во время проверки сохраняется до
освобождения очереди; во время полного обхода очередь новых писем проверяется
между страницами.
После обрыва наблюдатель переподключается с паузами 1, 5, 30 и 60 секунд и
догружает UID после последнего полученного. После сна соединение перезапускается.
Смена UIDVALIDITY задаёт новую начальную границу, чтобы не уведомлять обо всём
пересозданном ящике. При удалении аккаунта, изменении подключения и выходе из
приложения старое наблюдение останавливается.
Резервная проверка в основном процессе выполняется раз в минуту независимо от
открытой вкладки; она охватывает и другие папки, куда серверные правила могут
сразу переместить входящие письма. При отсутствии IDLE наблюдатель также проверяет
входящие раз в минуту. Общий фильтр повторов объединяет результаты IDLE и опроса.
Для ИИ недоступность модели сохраняет обычные уведомления; повторные попытки
в этом случае идут по минутному таймеру, а не на каждое новое событие.
Проверка наблюдателя и фильтра повторов: `npm run test:realtime`.
Если «Уведомлять о важных письмах в заглушённых папках» выключено, агент
не загружает письма для анализа в заглушённых папках и их подпапках.
Учитываются бессрочные и временные заглушки. Служебные статусы папок
по-прежнему запрашиваются для счётчиков и UID; обычная синхронизация почты продолжается.

View file

@ -16,6 +16,7 @@
"build:linux": "npm run build && electron-builder --linux", "build:linux": "npm run build && electron-builder --linux",
"build:win": "npm run build && electron-builder --win", "build:win": "npm run build && electron-builder --win",
"build:mac": "npm run build && electron-builder --mac", "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:compose": "node --experimental-strip-types --test tests/compose*.test.ts",
"test:navigation": "node --experimental-strip-types tests/message-navigation.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", "test:agent": "node --experimental-strip-types --test tests/mail-agent*.test.ts",

View file

@ -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 type { ComposeSettings } from '@shared/types/compose'
import { ComposeSettingsService } from './services/compose-settings-service' import { ComposeSettingsService } from './services/compose-settings-service'
import { registerComposeSettingsHandlers } from './ipc/compose-settings.handler' 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 { ComposeSession } from '@shared/types/message'
import type { CalendarEvent } from '@shared/types/calendar' 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) const retentionService = new RetentionService(accountManager)
let mainWindowRef: BrowserWindow | null = null let mainWindowRef: BrowserWindow | null = null
@ -55,7 +63,8 @@ const mailAgent = new MailAgentService(accountManager,
new JsonAgentHistoryRepository(mailAgentStore) new JsonAgentHistoryRepository(mailAgentStore)
) )
accountManager.setMailNotificationFilter((event): boolean => mailAgent.filterNotification(event)) 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 { function openEventInMainWindow(event: CalendarEvent): void {

View file

@ -2,6 +2,7 @@ import { registerHandler } from './registry'
import type { MailAgentService } from '../services/mail-agent-service' import type { MailAgentService } from '../services/mail-agent-service'
export function registerAgentHandlers(agent: MailAgentService): void { export function registerAgentHandlers(agent: MailAgentService): void {
registerHandler('agent:muted-folders:set', async (folders) => agent.setMutedFolders(folders))
registerHandler('agent:reply', async (request) => agent.prepareReply(request)) registerHandler('agent:reply', async (request) => agent.prepareReply(request))
registerHandler('agent:status:get', async () => agent.getStatus()) registerHandler('agent:status:get', async () => agent.getStatus())
registerHandler('agent:progress:get', async () => agent.getProgress()) registerHandler('agent:progress:get', async () => agent.getProgress())

View file

@ -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<string>
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<string> = message.flags ?? new Set<string>()
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
}
}

View file

@ -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
})
}

View file

@ -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<void> { await this.client.connect() }
async selectInbox(): Promise<MailCursor> {
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<MessageEnvelope[]> {
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() }
}

View file

@ -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 { getAccountEmail } from '@shared/utils/account-email'
import { SmtpSendError } from '../lib/smtp-error' import { SmtpSendError } from '../lib/smtp-error'
import { buildComposeAttachments } from '../lib/compose-attachments' import { buildComposeAttachments } from '../lib/compose-attachments'
import { ImapFlow } from 'imapflow' import type { ImapFlow } from 'imapflow'
import { simpleParser } from 'mailparser' import { simpleParser } from 'mailparser'
import nodemailer from 'nodemailer' import nodemailer from 'nodemailer'
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider' 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 { SpecialFolderRole } from '@shared/types/folder'
import type { Folder } from '@shared/types/folder' import type { Folder } from '@shared/types/folder'
import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { AccountConfig, ImapCredentials } from '@shared/types/account'
@ -21,43 +24,18 @@ interface ImapMailbox {
folders?: ImapMailbox[] folders?: ImapMailbox[]
} }
// imapflow BodyStructure type
interface BodyPart {
part?: string
type?: string
subtype?: string
disposition?: string
parameters?: Record<string, string>
id?: string
encoding?: string
childNodes?: BodyPart[]
}
export class ImapProvider implements IEmailProvider { export class ImapProvider implements IEmailProvider {
private client: ImapFlow private client: ImapFlow
private connected = false private connected = false
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
private closeCallback: (() => void) | null = null private closeCallback: (() => void) | null = null
// folderId → last known unseen count for polling private mailCursors: Map<string, MailCursor> = new Map<string, MailCursor>()
private lastUnseenCount = new Map<string, number>() private readonly pollingFolders: Map<string, Promise<void>> = new Map<string, Promise<void>>()
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
private notifiedUids = new Map<string, number>()
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
// Промис с именем отправителя из Sent-папки; await-ится в sendMessage() // Промис с именем отправителя из Sent-папки; await-ится в sendMessage()
private senderNamePromise: Promise<string | null> = Promise.resolve(null) private senderNamePromise: Promise<string | null> = Promise.resolve(null)
constructor(private config: AccountConfig) { constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials this.client = createImapClient(config)
this.client = new ImapFlow({
host: creds.host,
port: creds.port,
secure: creds.secure,
auth: {
user: creds.username,
pass: creds.password
},
logger: false
})
// Без слушателя 'error' обрыв сокета превращается в uncaught exception в main // Без слушателя 'error' обрыв сокета превращается в uncaught exception в main
this.client.on('error', (err: Error) => { this.client.on('error', (err: Error) => {
console.warn('[IMAP] connection error:', err.message) console.warn('[IMAP] connection error:', err.message)
@ -73,14 +51,12 @@ export class ImapProvider implements IEmailProvider {
this.closeCallback = callback this.closeCallback = callback
} }
getUnseenCounts(): Map<string, number> { getMailCursors(): Map<string, MailCursor> {
return new Map(this.lastUnseenCount) return new Map<string, MailCursor>(this.mailCursors)
} }
seedUnseenCounts(counts: Map<string, number>): void { seedMailCursors(cursors: Map<string, MailCursor>): void {
for (const [path, count] of counts) { this.mailCursors = new Map<string, MailCursor>(cursors)
if (!this.lastUnseenCount.has(path)) this.lastUnseenCount.set(path, count)
}
} }
async connect(): Promise<void> { async connect(): Promise<void> {
@ -178,11 +154,11 @@ export class ImapProvider implements IEmailProvider {
for await (const msg of this.client.fetch(`${start}:${end}`, { for await (const msg of this.client.fetch(`${start}:${end}`, {
uid: true, uid: true,
envelope: true, envelope: true, internalDate: true,
flags: true, flags: true,
bodyStructure: true bodyStructure: true
})) { })) {
messages.push(this.convertMessage(msg, options.folderId)) messages.push(convertImapMessage(msg, options.folderId))
} }
// Newest first // Newest first
@ -209,11 +185,11 @@ export class ImapProvider implements IEmailProvider {
const messages: MessageEnvelope[] = [] const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(uidSet, { for await (const msg of this.client.fetch(uidSet, {
uid: true, uid: true,
envelope: true, envelope: true, internalDate: true,
flags: true, flags: true,
bodyStructure: true bodyStructure: true
}, { uid: true })) { }, { uid: true })) {
messages.push(this.convertMessage(msg, options.folderId)) messages.push(convertImapMessage(msg, options.folderId))
} }
// Fetch returns ascending order → reverse to newest first // Fetch returns ascending order → reverse to newest first
messages.sort((a, b) => Number(b.id) - Number(a.id)) 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) const page: number[] = uids.slice(0, limit)
if (!page.length) return { messages: [], total: 0, unseen: 0 } if (!page.length) return { messages: [], total: 0, unseen: 0 }
const messages: MessageEnvelope[] = [] const messages: MessageEnvelope[] = []
for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) { for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) {
messages.push(this.convertMessage(message, folderId)) messages.push(convertImapMessage(message, folderId))
} }
messages.sort((first: MessageEnvelope, second: MessageEnvelope): number => Number(first.id) - Number(second.id)) 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 } 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 { onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
this.newMailCallback = callback this.newMailCallback = callback
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => { this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо) // Первый STATUS задаёт границу, события после неё проверяются по UID.
if (data.prevCount > 0 && data.count > data.prevCount) { if (data.count > data.prevCount) {
// Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения // Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
this.pollSingleFolder(data.path).catch(() => {}) this.pollSingleFolder(data.path).catch(() => {})
} }
@ -597,9 +573,9 @@ export class ImapProvider implements IEmailProvider {
const remaining = limit - results.length const remaining = limit - results.length
const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining) const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining)
for await (const msg of this.client.fetch(sorted.join(','), { 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 })) { }, { uid: true })) {
results.push(this.convertMessage(msg, folder.path)) results.push(convertImapMessage(msg, folder.path))
} }
} }
} catch (e) { } catch (e) {
@ -628,71 +604,48 @@ export class ImapProvider implements IEmailProvider {
if (!this.newMailCallback) return if (!this.newMailCallback) return
try { try {
await this.pollFolderTree([{ name: folderPath, path: folderPath }]) await this.pollFolderTree([{ name: folderPath, path: folderPath }])
} catch { /* ignore */ } } catch (error: unknown) { console.warn('[IMAP] Ошибка проверки после EXISTS:', error) }
} }
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> { private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
for (const folder of folders) { for (const folder of folders) {
try { try { await this.pollMailbox(folder.path) } catch (error: unknown) {
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null if (!this.connected) throw error
// Если STATUS вернул null или упал — не трогаем сохранённый счётчик console.warn('[IMAP] Ошибка проверки папки %s:', folder.path, error)
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)
} }
if (folder.folders?.length) await this.pollFolderTree(folder.folders)
} }
} }
private isRecentlyNotified(key: string): boolean { private pollMailbox(folderPath: string): Promise<void> {
const expiry = this.notifiedUids.get(key) const pending: Promise<void> | undefined = this.pollingFolders.get(folderPath)
if (expiry === undefined) return false if (pending) return pending
if (Date.now() < expiry) return true const task: Promise<void> = this.checkMailbox(folderPath).finally(() => this.pollingFolders.delete(folderPath))
this.notifiedUids.delete(key) this.pollingFolders.set(folderPath, task)
return false return task
} }
private markNotified(key: string): void { private async checkMailbox(folderPath: string): Promise<void> {
// Чистим старые записи при росте кэша const status = await this.client.status(folderPath, { uidNext: true, uidValidity: true })
if (this.notifiedUids.size > 200) { if (!status || !status.uidNext || status.uidValidity === undefined) return
const now = Date.now() const snapshot: MailCursor = { nextUid: status.uidNext, uidValidity: status.uidValidity.toString() }
for (const [k, exp] of this.notifiedUids) { const previous: MailCursor | undefined = this.mailCursors.get(folderPath)
if (now >= exp) this.notifiedUids.delete(k) 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 ---- // ---- Private helpers ----
@ -732,48 +685,6 @@ export class ImapProvider implements IEmailProvider {
return SpecialFolderRole.None 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<string>
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<string>()
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 { private static buildComposeHtml(compose: ComposeData): string | undefined {
if (!compose.contentHtml && !compose.htmlBody) return undefined if (!compose.contentHtml && !compose.htmlBody) return undefined
const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '') const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '')
@ -852,10 +763,5 @@ export class ImapProvider implements IEmailProvider {
.trim() .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
}
} }

View file

@ -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 type { IncomingMail } from './mail-agent-notifications'
import { BrowserWindow, powerMonitor } from 'electron' import { BrowserWindow, powerMonitor } from 'electron'
import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { AccountConfig, ImapCredentials } from '@shared/types/account'
@ -25,13 +27,20 @@ export class AccountManager {
private calendarProviders = new Map<string, CalDavProvider>() private calendarProviders = new Map<string, CalDavProvider>()
private store: Store<AccountStoreSchema> private store: Store<AccountStoreSchema>
private credentialStore: CredentialStore private credentialStore: CredentialStore
private fallbackTimer: ReturnType<typeof setInterval> | null = null
private readonly pollingAccounts: Map<string, Promise<void>> = new Map<string, Promise<void>>()
private readonly inboxWatchers: Map<string, InboxWatcher> = new Map<string, InboxWatcher>()
private onNewMail: (event: IncomingMail) => void = (): void => {}
private mainWindow: BrowserWindow | null = null private mainWindow: BrowserWindow | null = null
private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false
// Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис // Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис
private reconnecting = new Map<string, Promise<void>>() private reconnecting = new Map<string, Promise<void>>()
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>() private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
constructor() { constructor(
private readonly createInboxWatcher: (config: AccountConfig, publish: (messages: MessageEnvelope[]) => void) => InboxWatcher,
private readonly newMailDeduplicator: MailDeduplicator
) {
this.store = new Store<AccountStoreSchema>({ this.store = new Store<AccountStoreSchema>({
name: 'accounts', name: 'accounts',
defaults: { accounts: [] } defaults: { accounts: [] }
@ -39,10 +48,47 @@ export class AccountManager {
this.credentialStore = new CredentialStore('credentials.json') this.credentialStore = new CredentialStore('credentials.json')
// После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса // После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса
powerMonitor.on('resume', () => { powerMonitor.on('resume', () => {
for (const watcher of this.inboxWatchers.values()) watcher.restart()
for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId) 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 { setMailNotificationFilter(provider: (event: IncomingMail) => boolean): void {
this.filterMailNotification = provider this.filterMailNotification = provider
} }
@ -53,6 +99,9 @@ export class AccountManager {
async initialize(): Promise<void> { async initialize(): Promise<void> {
await this.credentialStore.load() 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[] { getAccounts(): AccountConfig[] {
@ -81,7 +130,7 @@ export class AccountManager {
this.store.set('accounts', accounts) this.store.set('accounts', accounts)
this.providers.set(config.id, provider) this.providers.set(config.id, provider)
this.setupNewMailListener(config.id, provider) this.setupNewMailListener(config.id, provider, config)
return { success: true } return { success: true }
} catch (error) { } catch (error) {
@ -90,6 +139,7 @@ export class AccountManager {
} }
async removeAccount(accountId: string): Promise<void> { async removeAccount(accountId: string): Promise<void> {
this.stopInboxWatcher(accountId)
this.cancelScheduledReconnect(accountId) this.cancelScheduledReconnect(accountId)
const provider = this.providers.get(accountId) const provider = this.providers.get(accountId)
if (provider) { if (provider) {
@ -140,7 +190,7 @@ export class AccountManager {
const provider = this.createProvider(config) const provider = this.createProvider(config)
await provider.connect() await provider.connect()
this.providers.set(accountId, provider) this.providers.set(accountId, provider)
this.setupNewMailListener(accountId, provider) this.setupNewMailListener(accountId, provider, config)
return { success: true } return { success: true }
} catch (error) { } catch (error) {
@ -156,11 +206,13 @@ export class AccountManager {
async pollNewMessages(accountId: string): Promise<void> { async pollNewMessages(accountId: string): Promise<void> {
if (!this.providers.has(accountId)) return if (!this.providers.has(accountId)) return
try { const pending: Promise<void> | undefined = this.pollingAccounts.get(accountId)
await this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages()) if (pending) return pending
} catch (err) { const task: Promise<void> = this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages())
console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message) .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<void> { async sendMessage(accountId: string, compose: ComposeData): Promise<void> {
@ -364,9 +416,9 @@ export class AccountManager {
private async doReconnect(accountId: string): Promise<void> { private async doReconnect(accountId: string): Promise<void> {
this.cancelScheduledReconnect(accountId) this.cancelScheduledReconnect(accountId)
// Убиваем старый провайдер, забирая его счётчики непрочитанных // Убиваем старый провайдер, забирая его курсоры UID
const old = this.providers.get(accountId) const old = this.providers.get(accountId)
const unseenCounts = old?.getUnseenCounts() const mailCursors = old?.getMailCursors()
if (old) { if (old) {
old.offNewMail() old.offNewMail()
try { await old.disconnect() } catch { /* уже отвалился */ } try { await old.disconnect() } catch { /* уже отвалился */ }
@ -391,9 +443,9 @@ export class AccountManager {
const provider = this.createProvider(config) const provider = this.createProvider(config)
await provider.connect() await provider.connect()
// Без этого первое письмо после реконнекта не даст уведомления // Без этого первое письмо после реконнекта не даст уведомления
if (unseenCounts) provider.seedUnseenCounts(unseenCounts) if (mailCursors) provider.seedMailCursors(mailCursors)
this.providers.set(accountId, provider) 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) this.store.set('accounts', accounts)
// Reconnect if currently connected // Reconnect if currently connected
this.stopInboxWatcher(config.id)
this.cancelScheduledReconnect(config.id) this.cancelScheduledReconnect(config.id)
const existingProvider = this.providers.get(config.id) const existingProvider = this.providers.get(config.id)
if (existingProvider) { if (existingProvider) {
@ -477,7 +530,7 @@ export class AccountManager {
const newProvider = this.createProvider(configWithCreds) const newProvider = this.createProvider(configWithCreds)
await newProvider.connect() await newProvider.connect()
this.providers.set(config.id, newProvider) this.providers.set(config.id, newProvider)
this.setupNewMailListener(config.id, newProvider) this.setupNewMailListener(config.id, newProvider, configWithCreds)
} }
return { success: true } return { success: true }
@ -486,12 +539,9 @@ export class AccountManager {
} }
} }
private setupNewMailListener(accountId: string, provider: IEmailProvider): void { private setupNewMailListener(accountId: string, provider: IEmailProvider, config: AccountConfig): void {
provider.onNewMail((folderId, envelope) => { this.ensureInboxWatcher(config)
if (this.mainWindow && !this.mainWindow.isDestroyed()) { provider.onNewMail((folderId, envelope) => this.handleNewMail({ accountId, folderId, envelope }))
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope, agentEnabled: this.filterMailNotification({ accountId, folderId, envelope }) })
}
})
provider.onClose(() => { provider.onClose(() => {
// Игнорируем close устаревшего провайдера (его уже заменили) // Игнорируем close устаревшего провайдера (его уже заменили)
if (this.providers.get(accountId) !== provider) return if (this.providers.get(accountId) !== provider) return

View file

@ -0,0 +1,160 @@
import type { MessageEnvelope } from '@shared/types/message'
import type { MailCursor } from '@shared/types/mail-cursor'
export interface InboxClient {
connect(): Promise<void>
selectInbox(): Promise<MailCursor>
fetchAfter(uid: number, limit: number): Promise<MessageEnvelope[]>
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<void> | 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<void> {
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<void> {
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<void> = 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<void> {
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()
})
}
}

View file

@ -28,6 +28,7 @@ import { ewsBodyToMarkdown } from '../lib/html-to-markdown'
export interface AgentStoreSchema { export interface AgentStoreSchema {
settings: Omit<AgentSettings, 'hasApiKey'> settings: Omit<AgentSettings, 'hasApiKey'>
processed: ProcessedMail processed: ProcessedMail
mutedFolders?: Record<string, number | null>
history?: AgentHistoryState history?: AgentHistoryState
checkpoints?: Record<string, { accountId?: string; folderId?: string; uidValidity: string; lastUid: number }> checkpoints?: Record<string, { accountId?: string; folderId?: string; uidValidity: string; lastUid: number }>
usage: AgentUsageStatistics usage: AgentUsageStatistics
@ -53,7 +54,14 @@ function validateAgentUrl(value: string): URL {
return url return url
} }
interface QueuedAgentFolder {
accountId: string
folderId: string
firstUid: number
}
interface AccountScanContext { interface AccountScanContext {
firstUid?: number
observed: Set<string> observed: Set<string>
historical: Set<string> historical: Set<string>
mode: 'incremental' | 'maintenance' mode: 'incremental' | 'maintenance'
@ -72,6 +80,12 @@ function snapshotSignature(folders: Folder[]): string {
type AgentEvent = IpcEventMap['agent:notification'] type AgentEvent = IpcEventMap['agent:notification']
export class MailAgentService { export class MailAgentService {
private readonly knownFolders: Map<string, Folder[]> = new Map<string, Folder[]>()
private readonly queuedFolders: Map<string, QueuedAgentFolder> = new Map<string, QueuedAgentFolder>()
private eventTimer: ReturnType<typeof setTimeout> | null = null
private drainingEvents: boolean = false
private realtimeRetryBlocked: boolean = false
private stopped: boolean = false
private timer: ReturnType<typeof setInterval> | null = null private timer: ReturnType<typeof setInterval> | null = null
private running: boolean = false private running: boolean = false
private revision: number = 0 private revision: number = 0
@ -91,24 +105,149 @@ export class MailAgentService {
private readonly history: AgentHistoryRepository private readonly history: AgentHistoryRepository
) {} ) {}
setMutedFolders(folders: Record<string, number | null>): void {
if (!folders || typeof folders !== 'object' || Array.isArray(folders) || Object.values(folders).some((expiry) => expiry !== null && (typeof expiry !== 'number' || !Number.isFinite(expiry)))) {
throw new AgentSettingsError('Некорректные настройки заглушённых папок')
}
this.store.set('mutedFolders', { ...folders })
this.notifications.discardMatching((event): boolean => !this.shouldAnalyzeFolder(event.accountId, event.folderId))
}
private shouldAnalyzeFolder(accountId: string, folderId: string): boolean {
if (this.getSettings().notifyMutedFolders) return true
const muted: Record<string, number | null> = this.store.get('mutedFolders') ?? {}
const folders: Folder[] = flattenFolders(this.knownFolders.get(accountId) ?? [])
const visited: Set<string> = new Set<string>()
let current: string | null = folderId
while (current !== null && !visited.has(current)) {
visited.add(current)
const expiry: number | null | undefined = muted[`${accountId}:${current}`]
if (expiry === null || (expiry !== undefined && expiry > Date.now())) return false
current = folders.find((folder) => folder.id === current)?.parentId ?? null
}
return true
}
filterNotification(event: IncomingMail): boolean { filterNotification(event: IncomingMail): boolean {
if (!this.getSettings().enabled) return false if (!this.getSettings().enabled || !this.shouldAnalyzeFolder(event.accountId, event.folderId)) return false
if (this.history.getDecision(getMailKey(event))) return true
const baseline: FolderBaseline | undefined = this.getBaselines()[getFolderBaselineKey(event.accountId, event.folderId)] const baseline: FolderBaseline | undefined = this.getBaselines()[getFolderBaselineKey(event.accountId, event.folderId)]
if (baseline && isExistingMessage(event.envelope.id, baseline)) return true if (baseline && isExistingMessage(event.envelope.id, baseline)) return true
return this.notifications.filter(event) return this.notifications.filter(event)
} }
enqueueNewMail(event: IncomingMail): void {
if (this.stopped || !this.getSettings().enabled || !this.shouldAnalyzeFolder(event.accountId, event.folderId) || 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<void> {
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) }
})
this.knownFolders.set(accountId, folders)
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<void> {
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<string>(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) {
if (!this.shouldAnalyzeFolder(accountId, target.folderId)) continue
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<string>(), historical: new Set<string>(), 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 { private getBaselines(): FolderBaselines {
return this.store.get('baselines') ?? {} return this.store.get('baselines') ?? {}
} }
async initialize(): Promise<void> { async initialize(): Promise<void> {
this.stopped = false
await this.credentials.load() await this.credentials.load()
this.timer = setInterval((): void => { void this.scan() }, 60_000) this.timer = setInterval((): void => { void this.scan() }, 60_000)
void this.scan() void this.scan()
} }
stop(): void { stop(): void {
this.stopped = true
this.queuedFolders.clear()
if (this.eventTimer) clearTimeout(this.eventTimer)
this.eventTimer = null
this.revision++ this.revision++
if (this.timer) clearInterval(this.timer) if (this.timer) clearInterval(this.timer)
this.timer = null this.timer = null
@ -140,7 +279,9 @@ export class MailAgentService {
const decision: true | AgentDecision | undefined = this.history.getDecision(getMailKey({ accountId, folderId: envelope.folderId, envelope })) const decision: true | AgentDecision | undefined = this.history.getDecision(getMailKey({ accountId, folderId: envelope.folderId, envelope }))
if (decision && decision !== true) return { ...envelope, agentDecision: decision } if (decision && decision !== true) return { ...envelope, agentDecision: decision }
const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(accountId, envelope.folderId)] 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 +372,14 @@ export class MailAgentService {
} }
async scan(): Promise<void> { async scan(): Promise<void> {
if (this.running || !this.getSettings().enabled) return if (this.stopped || this.running || !this.getSettings().enabled) return
this.running = true const revision: number = this.beginRun()
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
const plans: { id: string; email: string; name: string; folders: Folder[]; mode: 'incremental' | 'maintenance' }[] = [] const plans: { id: string; email: string; name: string; folders: Folder[]; mode: 'incremental' | 'maintenance' }[] = []
try { try {
const accounts = this.manager.getAccounts() const accounts = this.manager.getAccounts()
const accountIds: Set<string> = new Set<string>(accounts.map((account) => account.id)) const accountIds: Set<string> = new Set<string>(accounts.map((account) => account.id))
this.history.removeAccountsExcept(accountIds) this.history.removeAccountsExcept(accountIds)
for (const [key, target] of this.queuedFolders) if (!accountIds.has(target.accountId)) this.queuedFolders.delete(key)
const allObserved: Set<string> = new Set<string>() const allObserved: Set<string> = new Set<string>()
const completeAccounts: Set<string> = new Set<string>() const completeAccounts: Set<string> = new Set<string>()
const verifiedFolders: Map<string, Set<string>> = new Map<string, Set<string>>() const verifiedFolders: Map<string, Set<string>> = new Map<string, Set<string>>()
@ -251,9 +389,7 @@ export class MailAgentService {
try { try {
const { folders } = await this.manager.listFolders(account.id) const { folders } = await this.manager.listFolders(account.id)
if (revision !== this.revision || !this.getSettings().enabled) return if (revision !== this.revision || !this.getSettings().enabled) return
const previousBaselines: FolderBaselines = this.getBaselines() const baselines: FolderBaselines = this.captureBaselines(account.id, folders, [...this.queuedFolders.values()])
const baselines: FolderBaselines = captureFolderBaselines(account.id, folders, previousBaselines)
if (baselines !== previousBaselines) this.store.set('baselines', baselines)
this.notifications.discardMatching((event: IncomingMail): boolean => { this.notifications.discardMatching((event: IncomingMail): boolean => {
const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(event.accountId, event.folderId)] const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(event.accountId, event.folderId)]
return Boolean(baseline && isExistingMessage(event.envelope.id, baseline)) return Boolean(baseline && isExistingMessage(event.envelope.id, baseline))
@ -297,8 +433,7 @@ export class MailAgentService {
} }
} catch (error: unknown) { this.recordError(error, 'Обход почты') } finally { } catch (error: unknown) { this.recordError(error, 'Обход почты') } finally {
this.running = false this.finishRun()
this.progress = { ...this.progress, running: false, finishedAt: new Date().toISOString() }
} }
} }
@ -348,7 +483,9 @@ export class MailAgentService {
for (const folder of folders) { for (const folder of folders) {
if (revision !== this.revision || !this.getSettings().enabled) return if (revision !== this.revision || !this.getSettings().enabled) return
this.progress = { ...this.progress, folder: folder.name, account: email } this.progress = { ...this.progress, folder: folder.name, account: email }
if (folder.statusError) { if (!this.shouldAnalyzeFolder(accountId, folder.id)) {
context.complete = false
} else if (folder.statusError) {
context.complete = false context.complete = false
this.recordError(new AgentSettingsError(folder.statusError), `Статус папки ${email} / ${folder.name}`) this.recordError(new AgentSettingsError(folder.statusError), `Статус папки ${email} / ${folder.name}`)
} else if (folder.totalCount > 0) { } else if (folder.totalCount > 0) {
@ -365,11 +502,13 @@ export class MailAgentService {
let offset: number = 0 let offset: number = 0
let checkpointBlocked: boolean = false let checkpointBlocked: boolean = false
while (revision === this.revision && this.getSettings().enabled) { while (revision === this.revision && this.getSettings().enabled) {
if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return }
const settings: AgentSettings = this.getSettings() const settings: AgentSettings = this.getSettings()
const inspectedBeforePage: number = this.progress.inspected const inspectedBeforePage: number = this.progress.inspected
const checkpointKey: string = getFolderBaselineKey(accountId, folder.id) const checkpointKey: string = getFolderBaselineKey(accountId, folder.id)
const checkpoint = this.store.get('checkpoints')?.[checkpointKey] 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 const afterUid: number = offset > 0 && context.mode === 'incremental' ? offset : savedUid
if (context.mode === 'incremental' && folder.uidNext !== undefined && folder.uidNext <= afterUid + 1) return if (context.mode === 'incremental' && folder.uidNext !== undefined && folder.uidNext <= afterUid + 1) return
const page = context.mode === 'maintenance' const page = context.mode === 'maintenance'
@ -382,6 +521,7 @@ export class MailAgentService {
const seen: Set<string> = new Set<string>() const seen: Set<string> = new Set<string>()
const newKeys: Set<string> = new Set<string>() const newKeys: Set<string> = new Set<string>()
for (const envelope of page.messages) { for (const envelope of page.messages) {
if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return }
const event: IncomingMail = { accountId, folderId: folder.id, envelope } const event: IncomingMail = { accountId, folderId: folder.id, envelope }
const key: string = getMailKey(event) const key: string = getMailKey(event)
context.observed.add(key) context.observed.add(key)
@ -410,6 +550,7 @@ export class MailAgentService {
const batches = splitIntoBatches(requests, settings.batchSize) const batches = splitIntoBatches(requests, settings.batchSize)
this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length - requests.length } this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length - requests.length }
const tasks: (() => Promise<null>)[] = batches.map((batch) => async (): Promise<null> => { const tasks: (() => Promise<null>)[] = batches.map((batch) => async (): Promise<null> => {
if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return null }
const decisions: AgentDecision[] | null = await this.analyzeBatch(batch.map((item) => item.request), revision) const decisions: AgentDecision[] | null = await this.analyzeBatch(batch.map((item) => item.request), revision)
if (!decisions || revision !== this.revision) return null if (!decisions || revision !== this.revision) return null
for (const [position, decision] of decisions.entries()) { for (const [position, decision] of decisions.entries()) {
@ -433,10 +574,11 @@ export class MailAgentService {
this.publishAnalysis({ ...event, decision }) this.publishAnalysis({ ...event, decision })
if (decision.source === 'baseline') continue if (decision.source === 'baseline') continue
const shouldNotify: boolean = this.modelFailedInScan ? this.notifications.finish(event) : this.notifications.complete(event) const shouldNotify: boolean = this.modelFailedInScan ? this.notifications.finish(event) : this.notifications.complete(event)
if (decision.notify && shouldNotify) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders }) if (decision.notify && shouldNotify && this.shouldAnalyzeFolder(accountId, folder.id)) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders })
} }
} }
this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length } this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length }
let hasNextPage: boolean
if (context.mode === 'incremental') { if (context.mode === 'incremental') {
const sorted: MessageEnvelope[] = [...page.messages].sort((first, second) => Number(first.id) - Number(second.id)) const sorted: MessageEnvelope[] = [...page.messages].sort((first, second) => Number(first.id) - Number(second.id))
let lastUid: number = savedUid let lastUid: number = savedUid
@ -446,15 +588,19 @@ export class MailAgentService {
if (!this.history.getDecision(key)) { checkpointBlocked = true; break } if (!this.history.getDecision(key)) { checkpointBlocked = true; break }
lastUid = Math.max(lastUid, Number(message.id)) 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 (!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 hasNextPage = sorted.length > 0 && sorted.length < page.total
offset = Number(sorted[sorted.length - 1].id) if (sorted.length) offset = Number(sorted[sorted.length - 1].id)
} else { } else {
offset += page.messages.length offset += page.messages.length
if (!page.messages.length && offset < page.total) context.complete = false if (!page.messages.length && offset < page.total) context.complete = false
if (offset < folder.totalCount && 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
} }
} }
} }

View file

@ -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<string, number> = new Map<string, number>()
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
}
}

View file

@ -0,0 +1,12 @@
import type { WatcherScheduler } from './inbox-watcher'
export const watcherScheduler: WatcherScheduler = {
after(milliseconds: number, callback: () => void): () => void {
const timer: ReturnType<typeof setTimeout> = setTimeout(callback, milliseconds)
return (): void => clearTimeout(timer)
},
every(milliseconds: number, callback: () => void): () => void {
const timer: ReturnType<typeof setInterval> = setInterval(callback, milliseconds)
return (): void => clearInterval(timer)
}
}

View file

@ -173,10 +173,10 @@ async function removeApiKey(): Promise<void> {
</div> </div>
<template v-if="settings"> <template v-if="settings">
<label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label> <label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label>
<p>Анализирует только новые письма во всех папках. Уже полученные письма при первом обходе помечаются неважными без анализа ИИ и уведомлений. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p> <p>Анализирует только новые письма в разрешённых папках. Уже полученные письма при первом обходе помечаются неважными без анализа ИИ и уведомлений. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
<p>При включении обычные уведомления заменяются решениями ИИ. Если модель недоступна, включаются обычные уведомления. После успешного ответа модели ИИ-отбор возобновляется.</p> <p>При включении обычные уведомления заменяются решениями ИИ. Если модель недоступна, включаются обычные уведомления. После успешного ответа модели ИИ-отбор возобновляется.</p>
<label class="agent-toggle">Уведомлять о важных письмах в заглушённых папках <Switch v-model="settings.notifyMutedFolders" /></label> <label class="agent-toggle">Уведомлять о важных письмах в заглушённых папках <Switch v-model="settings.notifyMutedFolders" /></label>
<small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Обычные уведомления эту настройку не используют.</small> <small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Если выключено, ИИ не анализирует письма в заглушённых папках и их подпапках. Обычные уведомления эту настройку не используют.</small>
<AgentProgress v-if="progress" :progress="progress" /> <AgentProgress v-if="progress" :progress="progress" />
<button class="action-btn agent-save" type="button" :disabled="!settings.enabled || checking || progress?.running" @click="checkNow">{{ checking ? 'Проверка…' : 'Проверить сейчас' }}</button> <button class="action-btn agent-save" type="button" :disabled="!settings.enabled || checking || progress?.running" @click="checkNow">{{ checking ? 'Проверка…' : 'Проверить сейчас' }}</button>
<button class="action-btn agent-save" type="button" :disabled="!settings.enabled || checking || progress?.running" @click="synchronize">Полная синхронизация и очистка</button> <button class="action-btn agent-save" type="button" :disabled="!settings.enabled || checking || progress?.running" @click="synchronize">Полная синхронизация и очистка</button>

View file

@ -28,8 +28,8 @@ export const useAccountsStore = defineStore('accounts', () => {
connected: result.success, connected: result.success,
error: result.error error: result.error
} }
// Инициализируем lastUnseenCount сразу после подключения — // Инициализируем курсоры новых UID сразу после подключения —
// иначе первый autoCheckTimer только заполняет карту, а второй уже шлёт уведомления. // иначе первый autoCheckTimer только заполняет курсоры, а второй уже шлёт уведомления.
if (result.success) { if (result.success) {
invoke('messages:poll', { accountId: acc.id }).catch(() => {}) invoke('messages:poll', { accountId: acc.id }).catch(() => {})
} }

View file

@ -467,8 +467,10 @@ export const useMessagesStore = defineStore('messages', () => {
data.accountId === accountsStore.activeAccountId && data.accountId === accountsStore.activeAccountId &&
data.folderId === foldersStore.activeFolderId data.folderId === foldersStore.activeFolderId
) { ) {
messages.value.unshift(data.envelope) if (!messages.value.some((message: MessageEnvelope): boolean => message.id === data.envelope.id)) {
totalCount.value++ messages.value.unshift(data.envelope)
totalCount.value++
}
} }
if (!data.envelope.flags.seen) { if (!data.envelope.flags.seen) {
foldersStore.updateFolderUnread(data.accountId, data.folderId, 1) foldersStore.updateFolderUnread(data.accountId, data.folderId, 1)

View file

@ -18,8 +18,17 @@ export const useNotificationsStore = defineStore('notifications', () => {
} }
} }
function syncAgent(): void {
void window.api.invoke('agent:muted-folders:set', { ...mutedFolders.value }).catch((error: unknown): void => {
console.error('Не удалось передать заглушённые папки агенту:', error)
})
}
syncAgent()
function persist(): void { function persist(): void {
localStorage.setItem(STORAGE_KEY, JSON.stringify(mutedFolders.value)) localStorage.setItem(STORAGE_KEY, JSON.stringify(mutedFolders.value))
syncAgent()
} }
function isFolderKeyMuted(accountId: string, folderId: string): boolean { function isFolderKeyMuted(accountId: string, folderId: string): boolean {

View file

@ -8,6 +8,7 @@ import type { CalendarInfo, CalendarEvent, MeetingReminder, MeetingReminderSetti
import type { FolderRetentionRule, RetentionCleanupResult } from './retention' import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
export interface IpcChannelMap { export interface IpcChannelMap {
'agent:muted-folders:set': [Record<string, number | null>, void]
'compose:settings:get': [void, ComposeSettings] 'compose:settings:get': [void, ComposeSettings]
'compose:settings:save': [ComposeSettings, ComposeSettings] 'compose:settings:save': [ComposeSettings, ComposeSettings]
'agent:reply': [AiReplyRequest, string] 'agent:reply': [AiReplyRequest, string]

View file

@ -0,0 +1,4 @@
export interface MailCursor {
uidValidity: string
nextUid: number
}

View file

@ -1,3 +1,4 @@
import type { MailCursor } from './mail-cursor'
import type { Folder } from './folder' import type { Folder } from './folder'
import type { MessageEnvelope, MessageBody, MessageFlags, ComposeData } from './message' import type { MessageEnvelope, MessageBody, MessageFlags, ComposeData } from './message'
import type { FolderRetentionRule, RetentionCleanupResult } from './retention' import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
@ -35,9 +36,8 @@ export interface IEmailProvider {
offNewMail(): void offNewMail(): void
/** Вызывается, когда соединение закрылось не по инициативе приложения. */ /** Вызывается, когда соединение закрылось не по инициативе приложения. */
onClose(callback: () => void): void onClose(callback: () => void): void
/** Счётчики непрочитанных по папкам — переносятся в новый провайдер при реконнекте. */ getMailCursors(): Map<string, MailCursor>
getUnseenCounts(): Map<string, number> seedMailCursors(cursors: Map<string, MailCursor>): void
seedUnseenCounts(counts: Map<string, number>): void
pollNewMessages(): Promise<void> pollNewMessages(): Promise<void>
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
sendMessage(compose: ComposeData): Promise<void> sendMessage(compose: ComposeData): Promise<void>

View file

@ -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: '<message@example.org>' }, flags: new Set<string>(['\\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')
})

164
tests/inbox-watcher.test.ts Normal file
View file

@ -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<void> { if (this.failure) throw this.failure }
async selectInbox(): Promise<MailCursor> { return { uidValidity: this.validity, nextUid: this.nextUid } }
async fetchAfter(uid: number, limit: number): Promise<MessageEnvelope[]> {
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<void> { for (let index: number = 0; index < 60; index++) await Promise.resolve() }
test('наблюдатель загружает все новые UID, включая первое письмо пустого ящика, без параллельных проверок', async (): Promise<void> => {
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<string>(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<void> => {
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<void> => {
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<void> => {
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<void> => {
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)
})

View file

@ -0,0 +1,212 @@
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 {
parentId: string | null
messages: MessageEnvelope[]
bodyRequests: number
fullRequests: number
beforeBody: (id: string) => Promise<void>
}
interface RealtimeFixture {
service: MailAgentService
store: Conf<AgentStoreSchema>
state: RealtimeState
notifications: string[]
errors: string[]
failRequests: () => void
restoreRequests: () => void
close: () => Promise<void>
}
async function createFixture(): Promise<RealtimeFixture> {
const directory: string = await mkdtemp(join(tmpdir(), 'aero-realtime-'))
const environment = await loadAgentTestModule()
const store: Conf<AgentStoreSchema> = new Conf<AgentStoreSchema>({ 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 = { parentId: null, messages: [message(1)], bodyRequests: 0, fullRequests: 0, beforeBody: async (): Promise<void> => {} }
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: state.parentId, 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<void> => {}, get: (): undefined => undefined, save: async (): Promise<void> => {} },
(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<void> => { service.stop(); await environment.server.close(); await rm(directory, { recursive: true, force: true }) }
}
}
test('событие запускает ИИ без минутного таймера и не считает пришедшее письмо старым до первой проверки', async (): Promise<void> => {
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<void>((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<void> => {
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<void> => {
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<void> = new Promise<void>((resolve): void => { signal = resolve })
const gate: Promise<void> = new Promise<void>((resolve): void => { release = resolve })
fixture.state.beforeBody = async (id: string): Promise<void> => { if (id === '2') { signal(); await gate } }
const checking: Promise<void> = 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<void> => {
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<void> => {
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<void>((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() }
})
test('заглушённая папка пропускается в очереди и обходе, а включённая галка разрешает анализ', async (): Promise<void> => {
const fixture: RealtimeFixture = await createFixture()
try {
await fixture.service.scan()
fixture.service.setMutedFolders({ 'account:INBOX': null })
fixture.state.messages.push(message(2))
const event = { accountId: 'account', folderId: 'INBOX', envelope: message(2) }
assert.equal(fixture.service.filterNotification(event), false)
fixture.service.enqueueNewMail(event)
fixture.service.annotateMessages('account', [message(2)])
await fixture.service.flushNewMail()
await fixture.service.scan()
assert.equal(fixture.state.bodyRequests, 0)
assert.deepEqual(fixture.notifications, [])
fixture.store.set('settings', { ...fixture.store.get('settings'), notifyMutedFolders: true })
fixture.service.enqueueNewMail(event)
await fixture.service.flushNewMail()
assert.equal(fixture.state.bodyRequests, 1)
assert.deepEqual(fixture.notifications, ['2'])
} finally { await fixture.close() }
})
test('временная заглушка перестаёт блокировать анализ после истечения срока', async (): Promise<void> => {
const fixture: RealtimeFixture = await createFixture()
try {
await fixture.service.scan()
fixture.service.setMutedFolders({ 'account:INBOX': Date.now() - 1 })
fixture.state.messages.push(message(2))
fixture.service.enqueueNewMail({ accountId: 'account', folderId: 'INBOX', envelope: message(2) })
await fixture.service.flushNewMail()
assert.equal(fixture.state.bodyRequests, 1)
} finally { await fixture.close() }
})
test('заглушка родительской папки блокирует анализ дочерней', async (): Promise<void> => {
const fixture: RealtimeFixture = await createFixture()
try {
fixture.state.parentId = 'parent'
await fixture.service.scan()
fixture.service.setMutedFolders({ 'account:parent': null })
fixture.state.messages.push(message(2))
fixture.service.enqueueNewMail({ accountId: 'account', folderId: 'INBOX', envelope: message(2) })
await fixture.service.flushNewMail()
await fixture.service.scan()
assert.equal(fixture.state.bodyRequests, 0)
fixture.service.setMutedFolders({})
await fixture.service.scan()
assert.equal(fixture.state.bodyRequests, 1)
} finally { await fixture.close() }
})

View file

@ -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)
})