Compare commits
No commits in common. "a2105f3c8104dd3e2146f657564606639dfd1326" and "b59270aedbd07d8b0a06bb394ffdddcd0c855395" have entirely different histories.
a2105f3c81
...
b59270aedb
24 changed files with 198 additions and 1091 deletions
44
README.md
44
README.md
|
|
@ -126,9 +126,8 @@ OpenAI-совместимого API (например, `http://localhost:11434/v
|
|||
|
||||
### Проверка только новых писем
|
||||
|
||||
При обнаружении новых UID агент сразу запускает анализ через общую очередь,
|
||||
с коротким объединением событий за 100 мс. Минутная проверка получает только
|
||||
сообщения с UID после сохранённого курсора и повторяет неудачные попытки. Если UIDNEXT не изменился, заголовки писем не запрашиваются.
|
||||
Агент проверяет папки раз в минуту, получая только сообщения с UID после
|
||||
сохранённого курсора. Если UIDNEXT не изменился, заголовки писем не запрашиваются.
|
||||
Тела загружаются только для новых писем без сохранённого решения. Курсор
|
||||
сохраняется между запусками и не продвигается за письмо с неудавшимся анализом.
|
||||
Успешные соседние результаты сохраняются и не требуют повторного запроса к ИИ.
|
||||
|
|
@ -245,42 +244,3 @@ id; неполная или некорректная порция будет п
|
|||
но не увеличивает счётчик классифицированных писем. Вложения модели не передаются.
|
||||
|
||||
Проверка редактора и подписи: `npm run test:compose`.
|
||||
|
||||
|
||||
## Новая почта через IMAP IDLE
|
||||
|
||||
Для каждого подключённого аккаунта открывается отдельное IMAP-соединение,
|
||||
которое постоянно держит «Входящие» выбранными в режиме чтения. Оно не используется
|
||||
для открытия писем, поиска, отправки или переключения папок. При поддержке IDLE
|
||||
сервер сообщает о новых письмах без ожидания минутного таймера. Наблюдатель
|
||||
выгружает все новые UID порциями по 100 заголовков, включая первое письмо пустого
|
||||
ящика и письма, уже прочитанные другим клиентом. Получение заголовков не меняет
|
||||
флаги прочитанности.
|
||||
|
||||
После события обновляются список писем и счётчик непрочитанных, а при включённом
|
||||
ИИ письмо сразу ставится в очередь анализа. Размер порции к модели и параллельность
|
||||
берутся из настроек агента. Очередь общая для событий и периодического обхода:
|
||||
анализы не запускаются параллельно сверх настройки, повторные события не создают
|
||||
повторных решений и уведомлений. Событие во время проверки сохраняется до
|
||||
освобождения очереди; во время полного обхода очередь новых писем проверяется
|
||||
между страницами.
|
||||
|
||||
После обрыва наблюдатель переподключается с паузами 1, 5, 30 и 60 секунд и
|
||||
догружает UID после последнего полученного. После сна соединение перезапускается.
|
||||
Смена UIDVALIDITY задаёт новую начальную границу, чтобы не уведомлять обо всём
|
||||
пересозданном ящике. При удалении аккаунта, изменении подключения и выходе из
|
||||
приложения старое наблюдение останавливается.
|
||||
|
||||
Резервная проверка в основном процессе выполняется раз в минуту независимо от
|
||||
открытой вкладки; она охватывает и другие папки, куда серверные правила могут
|
||||
сразу переместить входящие письма. При отсутствии IDLE наблюдатель также проверяет
|
||||
входящие раз в минуту. Общий фильтр повторов объединяет результаты IDLE и опроса.
|
||||
Для ИИ недоступность модели сохраняет обычные уведомления; повторные попытки
|
||||
в этом случае идут по минутному таймеру, а не на каждое новое событие.
|
||||
|
||||
Проверка наблюдателя и фильтра повторов: `npm run test:realtime`.
|
||||
|
||||
Если «Уведомлять о важных письмах в заглушённых папках» выключено, агент
|
||||
не загружает письма для анализа в заглушённых папках и их подпапках.
|
||||
Учитываются бессрочные и временные заглушки. Служебные статусы папок
|
||||
по-прежнему запрашиваются для счётчиков и UID; обычная синхронизация почты продолжается.
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@
|
|||
"build:linux": "npm run build && electron-builder --linux",
|
||||
"build:win": "npm run build && electron-builder --win",
|
||||
"build:mac": "npm run build && electron-builder --mac",
|
||||
"test:realtime": "node --experimental-strip-types --test tests/inbox-watcher.test.ts tests/new-mail-deduplicator.test.ts tests/imap-message.test.ts",
|
||||
"test:compose": "node --experimental-strip-types --test tests/compose*.test.ts",
|
||||
"test:navigation": "node --experimental-strip-types tests/message-navigation.test.ts",
|
||||
"test:agent": "node --experimental-strip-types --test tests/mail-agent*.test.ts",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,3 @@
|
|||
import { NewMailDeduplicator } from './services/new-mail-deduplicator'
|
||||
import { ImapInboxWatcher } from './services/inbox-watcher'
|
||||
import { ImapInboxClientAdapter } from './providers/imap-inbox-client'
|
||||
import { createImapClient } from './providers/imap-client'
|
||||
import { watcherScheduler } from './services/watcher-scheduler'
|
||||
import type { ComposeSettings } from '@shared/types/compose'
|
||||
import { ComposeSettingsService } from './services/compose-settings-service'
|
||||
import { registerComposeSettingsHandlers } from './ipc/compose-settings.handler'
|
||||
|
|
@ -36,10 +31,7 @@ import { updater } from './services/updater'
|
|||
import type { ComposeSession } from '@shared/types/message'
|
||||
import type { CalendarEvent } from '@shared/types/calendar'
|
||||
|
||||
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 accountManager = new AccountManager()
|
||||
const retentionService = new RetentionService(accountManager)
|
||||
|
||||
let mainWindowRef: BrowserWindow | null = null
|
||||
|
|
@ -63,8 +55,7 @@ const mailAgent = new MailAgentService(accountManager,
|
|||
new JsonAgentHistoryRepository(mailAgentStore)
|
||||
)
|
||||
accountManager.setMailNotificationFilter((event): boolean => mailAgent.filterNotification(event))
|
||||
accountManager.setNewMailObserver((event): void => mailAgent.enqueueNewMail(event))
|
||||
app.on('before-quit', (): void => { mailAgent.stop(); accountManager.disposeWatchers() })
|
||||
app.on('before-quit', (): void => mailAgent.stop())
|
||||
|
||||
/** «Открыть» в напоминании: выводим главное окно и показываем событие в календаре. */
|
||||
function openEventInMainWindow(event: CalendarEvent): void {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { registerHandler } from './registry'
|
|||
import type { MailAgentService } from '../services/mail-agent-service'
|
||||
|
||||
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:status:get', async () => agent.getStatus())
|
||||
registerHandler('agent:progress:get', async () => agent.getProgress())
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
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
|
||||
})
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
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() }
|
||||
}
|
||||
|
|
@ -1,14 +1,11 @@
|
|||
import { createImapClient } from './imap-client'
|
||||
import { convertImapMessage } from '../lib/imap-message'
|
||||
import type { MailCursor } from '@shared/types/mail-cursor'
|
||||
import { getAccountEmail } from '@shared/utils/account-email'
|
||||
import { SmtpSendError } from '../lib/smtp-error'
|
||||
import { buildComposeAttachments } from '../lib/compose-attachments'
|
||||
import type { ImapFlow } from 'imapflow'
|
||||
import { ImapFlow } from 'imapflow'
|
||||
import { simpleParser } from 'mailparser'
|
||||
import nodemailer from 'nodemailer'
|
||||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, InlineImage, Attachment } from '@shared/types/message'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
|
|
@ -24,18 +21,43 @@ interface 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 {
|
||||
private client: ImapFlow
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private closeCallback: (() => void) | null = null
|
||||
private mailCursors: Map<string, MailCursor> = new Map<string, MailCursor>()
|
||||
private readonly pollingFolders: Map<string, Promise<void>> = new Map<string, Promise<void>>()
|
||||
// folderId → last known unseen count for polling
|
||||
private lastUnseenCount = new Map<string, number>()
|
||||
// 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()
|
||||
private senderNamePromise: Promise<string | null> = Promise.resolve(null)
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
this.client = createImapClient(config)
|
||||
const creds = config.credentials as ImapCredentials
|
||||
this.client = new ImapFlow({
|
||||
host: creds.host,
|
||||
port: creds.port,
|
||||
secure: creds.secure,
|
||||
auth: {
|
||||
user: creds.username,
|
||||
pass: creds.password
|
||||
},
|
||||
logger: false
|
||||
})
|
||||
// Без слушателя 'error' обрыв сокета превращается в uncaught exception в main
|
||||
this.client.on('error', (err: Error) => {
|
||||
console.warn('[IMAP] connection error:', err.message)
|
||||
|
|
@ -51,12 +73,14 @@ export class ImapProvider implements IEmailProvider {
|
|||
this.closeCallback = callback
|
||||
}
|
||||
|
||||
getMailCursors(): Map<string, MailCursor> {
|
||||
return new Map<string, MailCursor>(this.mailCursors)
|
||||
getUnseenCounts(): Map<string, number> {
|
||||
return new Map(this.lastUnseenCount)
|
||||
}
|
||||
|
||||
seedMailCursors(cursors: Map<string, MailCursor>): void {
|
||||
this.mailCursors = new Map<string, MailCursor>(cursors)
|
||||
seedUnseenCounts(counts: Map<string, number>): void {
|
||||
for (const [path, count] of counts) {
|
||||
if (!this.lastUnseenCount.has(path)) this.lastUnseenCount.set(path, count)
|
||||
}
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
|
|
@ -154,11 +178,11 @@ export class ImapProvider implements IEmailProvider {
|
|||
|
||||
for await (const msg of this.client.fetch(`${start}:${end}`, {
|
||||
uid: true,
|
||||
envelope: true, internalDate: true,
|
||||
envelope: true,
|
||||
flags: true,
|
||||
bodyStructure: true
|
||||
})) {
|
||||
messages.push(convertImapMessage(msg, options.folderId))
|
||||
messages.push(this.convertMessage(msg, options.folderId))
|
||||
}
|
||||
|
||||
// Newest first
|
||||
|
|
@ -185,11 +209,11 @@ export class ImapProvider implements IEmailProvider {
|
|||
const messages: MessageEnvelope[] = []
|
||||
for await (const msg of this.client.fetch(uidSet, {
|
||||
uid: true,
|
||||
envelope: true, internalDate: true,
|
||||
envelope: true,
|
||||
flags: true,
|
||||
bodyStructure: true
|
||||
}, { uid: true })) {
|
||||
messages.push(convertImapMessage(msg, options.folderId))
|
||||
messages.push(this.convertMessage(msg, options.folderId))
|
||||
}
|
||||
// Fetch returns ascending order → reverse to newest first
|
||||
messages.sort((a, b) => Number(b.id) - Number(a.id))
|
||||
|
|
@ -205,8 +229,8 @@ export class ImapProvider implements IEmailProvider {
|
|||
const page: number[] = uids.slice(0, limit)
|
||||
if (!page.length) return { messages: [], total: 0, unseen: 0 }
|
||||
const messages: MessageEnvelope[] = []
|
||||
for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) {
|
||||
messages.push(convertImapMessage(message, folderId))
|
||||
for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) {
|
||||
messages.push(this.convertMessage(message, folderId))
|
||||
}
|
||||
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 }
|
||||
|
|
@ -510,8 +534,8 @@ export class ImapProvider implements IEmailProvider {
|
|||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
|
||||
// Первый STATUS задаёт границу, события после неё проверяются по UID.
|
||||
if (data.count > data.prevCount) {
|
||||
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
|
||||
if (data.prevCount > 0 && data.count > data.prevCount) {
|
||||
// Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
|
||||
this.pollSingleFolder(data.path).catch(() => {})
|
||||
}
|
||||
|
|
@ -573,9 +597,9 @@ export class ImapProvider implements IEmailProvider {
|
|||
const remaining = limit - results.length
|
||||
const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining)
|
||||
for await (const msg of this.client.fetch(sorted.join(','), {
|
||||
uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true
|
||||
uid: true, envelope: true, flags: true, bodyStructure: true
|
||||
}, { uid: true })) {
|
||||
results.push(convertImapMessage(msg, folder.path))
|
||||
results.push(this.convertMessage(msg, folder.path))
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -604,48 +628,71 @@ export class ImapProvider implements IEmailProvider {
|
|||
if (!this.newMailCallback) return
|
||||
try {
|
||||
await this.pollFolderTree([{ name: folderPath, path: folderPath }])
|
||||
} catch (error: unknown) { console.warn('[IMAP] Ошибка проверки после EXISTS:', error) }
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
|
||||
for (const folder of folders) {
|
||||
try { await this.pollMailbox(folder.path) } catch (error: unknown) {
|
||||
if (!this.connected) throw error
|
||||
console.warn('[IMAP] Ошибка проверки папки %s:', folder.path, error)
|
||||
try {
|
||||
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null
|
||||
// Если STATUS вернул null или упал — не трогаем сохранённый счётчик
|
||||
if (status) {
|
||||
const unseen = status.unseen ?? 0
|
||||
const prev = this.lastUnseenCount.get(folder.path)
|
||||
this.lastUnseenCount.set(folder.path, unseen)
|
||||
|
||||
if (prev !== undefined && unseen > prev && this.newMailCallback) {
|
||||
// Получаем последнее непрочитанное письмо для уведомления
|
||||
const lock = await this.client.getMailboxLock(folder.path)
|
||||
try {
|
||||
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
|
||||
if (uids?.length) {
|
||||
const latestUid = Math.max(...uids).toString()
|
||||
const dedupKey = `${folder.path}:${latestUid}`
|
||||
if (!this.isRecentlyNotified(dedupKey)) {
|
||||
for await (const msg of this.client.fetch(latestUid, {
|
||||
uid: true, envelope: true, flags: true
|
||||
}, { uid: true })) {
|
||||
this.markNotified(dedupKey)
|
||||
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Соединение умерло — не перебираем остальные папки с той же ошибкой
|
||||
if (!this.connected) throw err
|
||||
console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message)
|
||||
}
|
||||
|
||||
if (folder.folders?.length) {
|
||||
await this.pollFolderTree(folder.folders)
|
||||
}
|
||||
if (folder.folders?.length) await this.pollFolderTree(folder.folders)
|
||||
}
|
||||
}
|
||||
|
||||
private pollMailbox(folderPath: string): Promise<void> {
|
||||
const pending: Promise<void> | undefined = this.pollingFolders.get(folderPath)
|
||||
if (pending) return pending
|
||||
const task: Promise<void> = this.checkMailbox(folderPath).finally(() => this.pollingFolders.delete(folderPath))
|
||||
this.pollingFolders.set(folderPath, task)
|
||||
return task
|
||||
private isRecentlyNotified(key: string): boolean {
|
||||
const expiry = this.notifiedUids.get(key)
|
||||
if (expiry === undefined) return false
|
||||
if (Date.now() < expiry) return true
|
||||
this.notifiedUids.delete(key)
|
||||
return false
|
||||
}
|
||||
|
||||
private async checkMailbox(folderPath: string): Promise<void> {
|
||||
const status = await this.client.status(folderPath, { uidNext: true, uidValidity: true })
|
||||
if (!status || !status.uidNext || status.uidValidity === undefined) return
|
||||
const snapshot: MailCursor = { nextUid: status.uidNext, uidValidity: status.uidValidity.toString() }
|
||||
const previous: MailCursor | undefined = this.mailCursors.get(folderPath)
|
||||
if (!previous || previous.uidValidity !== snapshot.uidValidity) {
|
||||
this.mailCursors.set(folderPath, snapshot)
|
||||
return
|
||||
}
|
||||
let afterUid: number = previous.nextUid - 1
|
||||
while (afterUid + 1 < snapshot.nextUid && this.newMailCallback) {
|
||||
const page = await this.listMessagesAfterUid(folderPath, afterUid, 100)
|
||||
const messages: MessageEnvelope[] = page.messages.filter((message: MessageEnvelope): boolean => Number(message.id) < snapshot.nextUid)
|
||||
if (!messages.length) break
|
||||
for (const message of messages) {
|
||||
this.newMailCallback?.(folderPath, message)
|
||||
afterUid = Math.max(afterUid, Number(message.id))
|
||||
this.mailCursors.set(folderPath, { ...snapshot, nextUid: afterUid + 1 })
|
||||
private markNotified(key: string): void {
|
||||
// Чистим старые записи при росте кэша
|
||||
if (this.notifiedUids.size > 200) {
|
||||
const now = Date.now()
|
||||
for (const [k, exp] of this.notifiedUids) {
|
||||
if (now >= exp) this.notifiedUids.delete(k)
|
||||
}
|
||||
}
|
||||
this.mailCursors.set(folderPath, snapshot)
|
||||
this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS)
|
||||
}
|
||||
|
||||
// ---- Private helpers ----
|
||||
|
|
@ -685,6 +732,48 @@ export class ImapProvider implements IEmailProvider {
|
|||
return SpecialFolderRole.None
|
||||
}
|
||||
|
||||
private convertMessage(msg: unknown, folderId: string): MessageEnvelope {
|
||||
const m = msg as {
|
||||
uid: number
|
||||
envelope: {
|
||||
subject?: string
|
||||
from?: Array<{ name?: string; address?: string }>
|
||||
to?: Array<{ name?: string; address?: string }>
|
||||
cc?: Array<{ name?: string; address?: string }>
|
||||
date?: Date
|
||||
messageId?: string
|
||||
inReplyTo?: string
|
||||
}
|
||||
flags: Set<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 {
|
||||
if (!compose.contentHtml && !compose.htmlBody) return undefined
|
||||
const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '')
|
||||
|
|
@ -763,5 +852,10 @@ export class ImapProvider implements IEmailProvider {
|
|||
.trim()
|
||||
}
|
||||
|
||||
|
||||
private hasAttachments(node?: BodyPart): boolean {
|
||||
if (!node) return false
|
||||
if (node.disposition === 'attachment') return true
|
||||
if (node.childNodes) return node.childNodes.some((c) => this.hasAttachments(c))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import type { InboxWatcher } from './inbox-watcher'
|
||||
import type { MailDeduplicator } from './new-mail-deduplicator'
|
||||
import type { IncomingMail } from './mail-agent-notifications'
|
||||
import { BrowserWindow, powerMonitor } from 'electron'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
|
|
@ -27,20 +25,13 @@ export class AccountManager {
|
|||
private calendarProviders = new Map<string, CalDavProvider>()
|
||||
private store: Store<AccountStoreSchema>
|
||||
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 filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false
|
||||
// Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис
|
||||
private reconnecting = new Map<string, Promise<void>>()
|
||||
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
constructor(
|
||||
private readonly createInboxWatcher: (config: AccountConfig, publish: (messages: MessageEnvelope[]) => void) => InboxWatcher,
|
||||
private readonly newMailDeduplicator: MailDeduplicator
|
||||
) {
|
||||
constructor() {
|
||||
this.store = new Store<AccountStoreSchema>({
|
||||
name: 'accounts',
|
||||
defaults: { accounts: [] }
|
||||
|
|
@ -48,47 +39,10 @@ export class AccountManager {
|
|||
this.credentialStore = new CredentialStore('credentials.json')
|
||||
// После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса
|
||||
powerMonitor.on('resume', () => {
|
||||
for (const watcher of this.inboxWatchers.values()) watcher.restart()
|
||||
for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId)
|
||||
})
|
||||
}
|
||||
|
||||
setNewMailObserver(observer: (event: IncomingMail) => void): void {
|
||||
this.onNewMail = observer
|
||||
}
|
||||
|
||||
disposeWatchers(): void {
|
||||
if (this.fallbackTimer) clearInterval(this.fallbackTimer)
|
||||
this.fallbackTimer = null
|
||||
for (const watcher of this.inboxWatchers.values()) watcher.stop()
|
||||
this.inboxWatchers.clear()
|
||||
}
|
||||
|
||||
private stopInboxWatcher(accountId: string): void {
|
||||
this.inboxWatchers.get(accountId)?.stop()
|
||||
this.inboxWatchers.delete(accountId)
|
||||
}
|
||||
|
||||
private ensureInboxWatcher(config: AccountConfig): void {
|
||||
if (this.inboxWatchers.has(config.id)) return
|
||||
const watcher: InboxWatcher = this.createInboxWatcher(config, (messages: MessageEnvelope[]): void => {
|
||||
for (const envelope of messages) this.handleNewMail({ accountId: config.id, folderId: envelope.folderId, envelope })
|
||||
})
|
||||
this.inboxWatchers.set(config.id, watcher)
|
||||
watcher.start()
|
||||
}
|
||||
|
||||
private handleNewMail(event: IncomingMail): void {
|
||||
if (!this.newMailDeduplicator.accept(event)) return
|
||||
let agentEnabled: boolean = false
|
||||
try { agentEnabled = this.filterMailNotification(event) } catch (error: unknown) {
|
||||
console.error('[AccountManager] Не удалось применить фильтр ИИ:', error)
|
||||
if (this.mainWindow && !this.mainWindow.isDestroyed()) this.mainWindow.webContents.send('agent:error', { message: error instanceof Error ? error.message : String(error) })
|
||||
}
|
||||
if (this.mainWindow && !this.mainWindow.isDestroyed()) this.mainWindow.webContents.send('mail:new', { ...event, agentEnabled })
|
||||
try { this.onNewMail(event) } catch (error: unknown) { console.error('[AccountManager] Не удалось поставить письмо в очередь ИИ:', error) }
|
||||
}
|
||||
|
||||
setMailNotificationFilter(provider: (event: IncomingMail) => boolean): void {
|
||||
this.filterMailNotification = provider
|
||||
}
|
||||
|
|
@ -99,9 +53,6 @@ export class AccountManager {
|
|||
|
||||
async initialize(): Promise<void> {
|
||||
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[] {
|
||||
|
|
@ -130,7 +81,7 @@ export class AccountManager {
|
|||
this.store.set('accounts', accounts)
|
||||
|
||||
this.providers.set(config.id, provider)
|
||||
this.setupNewMailListener(config.id, provider, config)
|
||||
this.setupNewMailListener(config.id, provider)
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
|
|
@ -139,7 +90,6 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
async removeAccount(accountId: string): Promise<void> {
|
||||
this.stopInboxWatcher(accountId)
|
||||
this.cancelScheduledReconnect(accountId)
|
||||
const provider = this.providers.get(accountId)
|
||||
if (provider) {
|
||||
|
|
@ -190,7 +140,7 @@ export class AccountManager {
|
|||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
this.providers.set(accountId, provider)
|
||||
this.setupNewMailListener(accountId, provider, config)
|
||||
this.setupNewMailListener(accountId, provider)
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
|
|
@ -206,13 +156,11 @@ export class AccountManager {
|
|||
|
||||
async pollNewMessages(accountId: string): Promise<void> {
|
||||
if (!this.providers.has(accountId)) return
|
||||
const pending: Promise<void> | undefined = this.pollingAccounts.get(accountId)
|
||||
if (pending) return pending
|
||||
const task: Promise<void> = this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages())
|
||||
.catch((error: unknown): void => { console.warn('[AccountManager] Ошибка резервной проверки %s:', accountId, error) })
|
||||
.finally(() => this.pollingAccounts.delete(accountId))
|
||||
this.pollingAccounts.set(accountId, task)
|
||||
return task
|
||||
try {
|
||||
await this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages())
|
||||
} catch (err) {
|
||||
console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(accountId: string, compose: ComposeData): Promise<void> {
|
||||
|
|
@ -416,9 +364,9 @@ export class AccountManager {
|
|||
private async doReconnect(accountId: string): Promise<void> {
|
||||
this.cancelScheduledReconnect(accountId)
|
||||
|
||||
// Убиваем старый провайдер, забирая его курсоры UID
|
||||
// Убиваем старый провайдер, забирая его счётчики непрочитанных
|
||||
const old = this.providers.get(accountId)
|
||||
const mailCursors = old?.getMailCursors()
|
||||
const unseenCounts = old?.getUnseenCounts()
|
||||
if (old) {
|
||||
old.offNewMail()
|
||||
try { await old.disconnect() } catch { /* уже отвалился */ }
|
||||
|
|
@ -443,9 +391,9 @@ export class AccountManager {
|
|||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
// Без этого первое письмо после реконнекта не даст уведомления
|
||||
if (mailCursors) provider.seedMailCursors(mailCursors)
|
||||
if (unseenCounts) provider.seedUnseenCounts(unseenCounts)
|
||||
this.providers.set(accountId, provider)
|
||||
this.setupNewMailListener(accountId, provider, config)
|
||||
this.setupNewMailListener(accountId, provider)
|
||||
}
|
||||
|
||||
// Фоновый реконнект после обрыва, с нарастающей паузой
|
||||
|
|
@ -519,7 +467,6 @@ export class AccountManager {
|
|||
this.store.set('accounts', accounts)
|
||||
|
||||
// Reconnect if currently connected
|
||||
this.stopInboxWatcher(config.id)
|
||||
this.cancelScheduledReconnect(config.id)
|
||||
const existingProvider = this.providers.get(config.id)
|
||||
if (existingProvider) {
|
||||
|
|
@ -530,7 +477,7 @@ export class AccountManager {
|
|||
const newProvider = this.createProvider(configWithCreds)
|
||||
await newProvider.connect()
|
||||
this.providers.set(config.id, newProvider)
|
||||
this.setupNewMailListener(config.id, newProvider, configWithCreds)
|
||||
this.setupNewMailListener(config.id, newProvider)
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
|
|
@ -539,9 +486,12 @@ export class AccountManager {
|
|||
}
|
||||
}
|
||||
|
||||
private setupNewMailListener(accountId: string, provider: IEmailProvider, config: AccountConfig): void {
|
||||
this.ensureInboxWatcher(config)
|
||||
provider.onNewMail((folderId, envelope) => this.handleNewMail({ accountId, folderId, envelope }))
|
||||
private setupNewMailListener(accountId: string, provider: IEmailProvider): void {
|
||||
provider.onNewMail((folderId, envelope) => {
|
||||
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||||
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope, agentEnabled: this.filterMailNotification({ accountId, folderId, envelope }) })
|
||||
}
|
||||
})
|
||||
provider.onClose(() => {
|
||||
// Игнорируем close устаревшего провайдера (его уже заменили)
|
||||
if (this.providers.get(accountId) !== provider) return
|
||||
|
|
|
|||
|
|
@ -1,160 +0,0 @@
|
|||
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()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -28,7 +28,6 @@ import { ewsBodyToMarkdown } from '../lib/html-to-markdown'
|
|||
export interface AgentStoreSchema {
|
||||
settings: Omit<AgentSettings, 'hasApiKey'>
|
||||
processed: ProcessedMail
|
||||
mutedFolders?: Record<string, number | null>
|
||||
history?: AgentHistoryState
|
||||
checkpoints?: Record<string, { accountId?: string; folderId?: string; uidValidity: string; lastUid: number }>
|
||||
usage: AgentUsageStatistics
|
||||
|
|
@ -54,14 +53,7 @@ function validateAgentUrl(value: string): URL {
|
|||
return url
|
||||
}
|
||||
|
||||
interface QueuedAgentFolder {
|
||||
accountId: string
|
||||
folderId: string
|
||||
firstUid: number
|
||||
}
|
||||
|
||||
interface AccountScanContext {
|
||||
firstUid?: number
|
||||
observed: Set<string>
|
||||
historical: Set<string>
|
||||
mode: 'incremental' | 'maintenance'
|
||||
|
|
@ -80,12 +72,6 @@ function snapshotSignature(folders: Folder[]): string {
|
|||
type AgentEvent = IpcEventMap['agent:notification']
|
||||
|
||||
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 running: boolean = false
|
||||
private revision: number = 0
|
||||
|
|
@ -105,149 +91,24 @@ export class MailAgentService {
|
|||
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 {
|
||||
if (!this.getSettings().enabled || !this.shouldAnalyzeFolder(event.accountId, event.folderId)) return false
|
||||
if (this.history.getDecision(getMailKey(event))) return true
|
||||
if (!this.getSettings().enabled) return false
|
||||
const baseline: FolderBaseline | undefined = this.getBaselines()[getFolderBaselineKey(event.accountId, event.folderId)]
|
||||
if (baseline && isExistingMessage(event.envelope.id, baseline)) return true
|
||||
return this.notifications.filter(event)
|
||||
}
|
||||
|
||||
enqueueNewMail(event: IncomingMail): void {
|
||||
if (this.stopped || !this.getSettings().enabled || !this.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 {
|
||||
return this.store.get('baselines') ?? {}
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
this.stopped = false
|
||||
await this.credentials.load()
|
||||
this.timer = setInterval((): void => { void this.scan() }, 60_000)
|
||||
void this.scan()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true
|
||||
this.queuedFolders.clear()
|
||||
if (this.eventTimer) clearTimeout(this.eventTimer)
|
||||
this.eventTimer = null
|
||||
this.revision++
|
||||
if (this.timer) clearInterval(this.timer)
|
||||
this.timer = null
|
||||
|
|
@ -279,9 +140,7 @@ export class MailAgentService {
|
|||
const decision: true | AgentDecision | undefined = this.history.getDecision(getMailKey({ accountId, folderId: envelope.folderId, envelope }))
|
||||
if (decision && decision !== true) return { ...envelope, agentDecision: decision }
|
||||
const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(accountId, envelope.folderId)]
|
||||
if (baseline && isExistingMessage(envelope.id, baseline)) return { ...envelope, agentDecision: this.getHistoricalDecision() }
|
||||
if (baseline) this.enqueueNewMail({ accountId, folderId: envelope.folderId, envelope })
|
||||
return envelope
|
||||
return baseline && isExistingMessage(envelope.id, baseline) ? { ...envelope, agentDecision: this.getHistoricalDecision() } : envelope
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -372,14 +231,17 @@ export class MailAgentService {
|
|||
}
|
||||
|
||||
async scan(): Promise<void> {
|
||||
if (this.stopped || this.running || !this.getSettings().enabled) return
|
||||
const revision: number = this.beginRun()
|
||||
if (this.running || !this.getSettings().enabled) return
|
||||
this.running = true
|
||||
this.modelFailedInScan = false
|
||||
this.pendingKeys.clear()
|
||||
this.progress = { mode: 'incremental', running: true, startedAt: new Date().toISOString(), finishedAt: null, inspected: 0, total: 0, folder: '', account: '', pending: 0, errors: 0, estimatedSeconds: null }
|
||||
const revision: number = this.revision
|
||||
const plans: { id: string; email: string; name: string; folders: Folder[]; mode: 'incremental' | 'maintenance' }[] = []
|
||||
try {
|
||||
const accounts = this.manager.getAccounts()
|
||||
const accountIds: Set<string> = new Set<string>(accounts.map((account) => account.id))
|
||||
this.history.removeAccountsExcept(accountIds)
|
||||
for (const [key, target] of this.queuedFolders) if (!accountIds.has(target.accountId)) this.queuedFolders.delete(key)
|
||||
const allObserved: Set<string> = new Set<string>()
|
||||
const completeAccounts: Set<string> = new Set<string>()
|
||||
const verifiedFolders: Map<string, Set<string>> = new Map<string, Set<string>>()
|
||||
|
|
@ -389,7 +251,9 @@ export class MailAgentService {
|
|||
try {
|
||||
const { folders } = await this.manager.listFolders(account.id)
|
||||
if (revision !== this.revision || !this.getSettings().enabled) return
|
||||
const baselines: FolderBaselines = this.captureBaselines(account.id, folders, [...this.queuedFolders.values()])
|
||||
const previousBaselines: FolderBaselines = this.getBaselines()
|
||||
const baselines: FolderBaselines = captureFolderBaselines(account.id, folders, previousBaselines)
|
||||
if (baselines !== previousBaselines) this.store.set('baselines', baselines)
|
||||
this.notifications.discardMatching((event: IncomingMail): boolean => {
|
||||
const baseline: FolderBaseline | undefined = baselines[getFolderBaselineKey(event.accountId, event.folderId)]
|
||||
return Boolean(baseline && isExistingMessage(event.envelope.id, baseline))
|
||||
|
|
@ -433,7 +297,8 @@ export class MailAgentService {
|
|||
}
|
||||
|
||||
} catch (error: unknown) { this.recordError(error, 'Обход почты') } finally {
|
||||
this.finishRun()
|
||||
this.running = false
|
||||
this.progress = { ...this.progress, running: false, finishedAt: new Date().toISOString() }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -483,9 +348,7 @@ export class MailAgentService {
|
|||
for (const folder of folders) {
|
||||
if (revision !== this.revision || !this.getSettings().enabled) return
|
||||
this.progress = { ...this.progress, folder: folder.name, account: email }
|
||||
if (!this.shouldAnalyzeFolder(accountId, folder.id)) {
|
||||
context.complete = false
|
||||
} else if (folder.statusError) {
|
||||
if (folder.statusError) {
|
||||
context.complete = false
|
||||
this.recordError(new AgentSettingsError(folder.statusError), `Статус папки ${email} / ${folder.name}`)
|
||||
} else if (folder.totalCount > 0) {
|
||||
|
|
@ -502,13 +365,11 @@ export class MailAgentService {
|
|||
let offset: number = 0
|
||||
let checkpointBlocked: boolean = false
|
||||
while (revision === this.revision && this.getSettings().enabled) {
|
||||
if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return }
|
||||
const settings: AgentSettings = this.getSettings()
|
||||
const inspectedBeforePage: number = this.progress.inspected
|
||||
const checkpointKey: string = getFolderBaselineKey(accountId, folder.id)
|
||||
const checkpoint = this.store.get('checkpoints')?.[checkpointKey]
|
||||
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 savedUid: number = checkpoint?.uidValidity === baseline.uidValidity ? checkpoint.lastUid : baseline.nextUid - 1
|
||||
const afterUid: number = offset > 0 && context.mode === 'incremental' ? offset : savedUid
|
||||
if (context.mode === 'incremental' && folder.uidNext !== undefined && folder.uidNext <= afterUid + 1) return
|
||||
const page = context.mode === 'maintenance'
|
||||
|
|
@ -521,7 +382,6 @@ export class MailAgentService {
|
|||
const seen: Set<string> = new Set<string>()
|
||||
const newKeys: Set<string> = new Set<string>()
|
||||
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 key: string = getMailKey(event)
|
||||
context.observed.add(key)
|
||||
|
|
@ -550,7 +410,6 @@ export class MailAgentService {
|
|||
const batches = splitIntoBatches(requests, settings.batchSize)
|
||||
this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length - requests.length }
|
||||
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)
|
||||
if (!decisions || revision !== this.revision) return null
|
||||
for (const [position, decision] of decisions.entries()) {
|
||||
|
|
@ -574,11 +433,10 @@ export class MailAgentService {
|
|||
this.publishAnalysis({ ...event, decision })
|
||||
if (decision.source === 'baseline') continue
|
||||
const shouldNotify: boolean = this.modelFailedInScan ? this.notifications.finish(event) : this.notifications.complete(event)
|
||||
if (decision.notify && shouldNotify && this.shouldAnalyzeFolder(accountId, folder.id)) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders })
|
||||
if (decision.notify && shouldNotify) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders })
|
||||
}
|
||||
}
|
||||
this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length }
|
||||
let hasNextPage: boolean
|
||||
if (context.mode === 'incremental') {
|
||||
const sorted: MessageEnvelope[] = [...page.messages].sort((first, second) => Number(first.id) - Number(second.id))
|
||||
let lastUid: number = savedUid
|
||||
|
|
@ -588,19 +446,15 @@ export class MailAgentService {
|
|||
if (!this.history.getDecision(key)) { checkpointBlocked = true; break }
|
||||
lastUid = Math.max(lastUid, Number(message.id))
|
||||
}
|
||||
const currentCheckpoint = this.store.get('checkpoints')?.[checkpointKey]
|
||||
if (currentCheckpoint?.uidValidity === baseline.uidValidity) lastUid = Math.max(lastUid, currentCheckpoint.lastUid)
|
||||
if (!wasBlocked && lastUid > savedUid) this.store.set('checkpoints', { ...this.store.get('checkpoints'), [checkpointKey]: { accountId, folderId: folder.id, uidValidity: baseline.uidValidity, lastUid } })
|
||||
hasNextPage = sorted.length > 0 && sorted.length < page.total
|
||||
if (sorted.length) offset = Number(sorted[sorted.length - 1].id)
|
||||
if (!sorted.length || sorted.length >= page.total) break
|
||||
offset = Number(sorted[sorted.length - 1].id)
|
||||
} else {
|
||||
offset += page.messages.length
|
||||
if (!page.messages.length && offset < page.total) context.complete = false
|
||||
if (offset < folder.totalCount && offset >= page.total) context.complete = false
|
||||
hasNextPage = page.messages.length > 0 && offset < page.total
|
||||
if (!page.messages.length || offset >= page.total) break
|
||||
}
|
||||
if (!this.drainingEvents && this.queuedFolders.size) await this.processQueuedFolders(revision)
|
||||
if (revision !== this.revision || !hasNextPage) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +0,0 @@
|
|||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -173,10 +173,10 @@ async function removeApiKey(): Promise<void> {
|
|||
</div>
|
||||
<template v-if="settings">
|
||||
<label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label>
|
||||
<p>Анализирует только новые письма в разрешённых папках. Уже полученные письма при первом обходе помечаются неважными без анализа ИИ и уведомлений. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
|
||||
<p>Анализирует только новые письма во всех папках. Уже полученные письма при первом обходе помечаются неважными без анализа ИИ и уведомлений. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
|
||||
<p>При включении обычные уведомления заменяются решениями ИИ. Если модель недоступна, включаются обычные уведомления. После успешного ответа модели ИИ-отбор возобновляется.</p>
|
||||
<label class="agent-toggle">Уведомлять о важных письмах в заглушённых папках <Switch v-model="settings.notifyMutedFolders" /></label>
|
||||
<small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Если выключено, ИИ не анализирует письма в заглушённых папках и их подпапках. Обычные уведомления эту настройку не используют.</small>
|
||||
<small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Обычные уведомления эту настройку не используют.</small>
|
||||
<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="synchronize">Полная синхронизация и очистка</button>
|
||||
|
|
|
|||
|
|
@ -28,8 +28,8 @@ export const useAccountsStore = defineStore('accounts', () => {
|
|||
connected: result.success,
|
||||
error: result.error
|
||||
}
|
||||
// Инициализируем курсоры новых UID сразу после подключения —
|
||||
// иначе первый autoCheckTimer только заполняет курсоры, а второй уже шлёт уведомления.
|
||||
// Инициализируем lastUnseenCount сразу после подключения —
|
||||
// иначе первый autoCheckTimer только заполняет карту, а второй уже шлёт уведомления.
|
||||
if (result.success) {
|
||||
invoke('messages:poll', { accountId: acc.id }).catch(() => {})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -467,10 +467,8 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
data.accountId === accountsStore.activeAccountId &&
|
||||
data.folderId === foldersStore.activeFolderId
|
||||
) {
|
||||
if (!messages.value.some((message: MessageEnvelope): boolean => message.id === data.envelope.id)) {
|
||||
messages.value.unshift(data.envelope)
|
||||
totalCount.value++
|
||||
}
|
||||
messages.value.unshift(data.envelope)
|
||||
totalCount.value++
|
||||
}
|
||||
if (!data.envelope.flags.seen) {
|
||||
foldersStore.updateFolderUnread(data.accountId, data.folderId, 1)
|
||||
|
|
|
|||
|
|
@ -18,17 +18,8 @@ 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 {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(mutedFolders.value))
|
||||
syncAgent()
|
||||
}
|
||||
|
||||
function isFolderKeyMuted(accountId: string, folderId: string): boolean {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import type { CalendarInfo, CalendarEvent, MeetingReminder, MeetingReminderSetti
|
|||
import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
|
||||
|
||||
export interface IpcChannelMap {
|
||||
'agent:muted-folders:set': [Record<string, number | null>, void]
|
||||
'compose:settings:get': [void, ComposeSettings]
|
||||
'compose:settings:save': [ComposeSettings, ComposeSettings]
|
||||
'agent:reply': [AiReplyRequest, string]
|
||||
|
|
|
|||
|
|
@ -1,4 +0,0 @@
|
|||
export interface MailCursor {
|
||||
uidValidity: string
|
||||
nextUid: number
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
import type { MailCursor } from './mail-cursor'
|
||||
import type { Folder } from './folder'
|
||||
import type { MessageEnvelope, MessageBody, MessageFlags, ComposeData } from './message'
|
||||
import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
|
||||
|
|
@ -36,8 +35,9 @@ export interface IEmailProvider {
|
|||
offNewMail(): void
|
||||
/** Вызывается, когда соединение закрылось не по инициативе приложения. */
|
||||
onClose(callback: () => void): void
|
||||
getMailCursors(): Map<string, MailCursor>
|
||||
seedMailCursors(cursors: Map<string, MailCursor>): void
|
||||
/** Счётчики непрочитанных по папкам — переносятся в новый провайдер при реконнекте. */
|
||||
getUnseenCounts(): Map<string, number>
|
||||
seedUnseenCounts(counts: Map<string, number>): void
|
||||
pollNewMessages(): Promise<void>
|
||||
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
|
||||
sendMessage(compose: ComposeData): Promise<void>
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
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')
|
||||
})
|
||||
|
|
@ -1,164 +0,0 @@
|
|||
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)
|
||||
})
|
||||
|
|
@ -1,212 +0,0 @@
|
|||
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() }
|
||||
})
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
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)
|
||||
})
|
||||
Loading…
Reference in a new issue