aero-mail/tests/mail-agent-new-messages.test.ts

127 lines
8.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import Conf from 'conf'
import { loadAgentTestModule } from './helpers/agent-module.ts'
import { getMailKey } from '../src/main/services/mail-agent-notifications.ts'
import { DEFAULT_AGENT_PROMPT } from '../src/shared/constants/agent.ts'
import type { 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 createMessage(id: string): MessageEnvelope {
return { id, folderId: 'INBOX', subject: 'Вопрос', date: '2000-01-01', from: { name: 'Автор', email: 'sender@example.org' }, to: [], cc: [], flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' }
}
test('старые письма не вызывают модель и уведомления, а новые анализируются после перезапуска', async (): Promise<void> => {
const directory: string = await mkdtemp(join(tmpdir(), 'aero-agent-new-'))
const { server, Service, History } = await loadAgentTestModule()
let messages: MessageEnvelope[] = [createMessage('1'), createMessage('2')]
let includeBrokenFolder: boolean = false
let headerRequests: number = 0
let fullRequests: number = 0
let bodyRequests: number = 0
const notifications: string[] = []
const errors: string[] = []
const createStore = (): Conf<AgentStoreSchema> => new Conf<AgentStoreSchema>({ cwd: directory, configName: 'mail-agent', defaults: {
settings: { enabled: true, notifyMutedFolders: false, prompt: DEFAULT_AGENT_PROMPT, pageSize: 100, batchSize: 1, concurrency: 2, url: 'http://localhost/v1', model: 'model' },
processed: {}, baselines: {}, usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 }
} })
const createService = (store: Conf<AgentStoreSchema>): InstanceType<typeof Service> => new 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: [...(includeBrokenFolder ? [{ id: 'Broken', name: 'Недоступная', role: 'none' as SpecialFolderRole, parentId: null, totalCount: 1, unreadCount: 0, children: [] }] : []), { id: 'INBOX', name: 'Входящие', role: 'inbox' as SpecialFolderRole, parentId: null, totalCount: messages.length, unreadCount: 1, children: [], uidNext: messages.length + 1, uidValidity: '1' }] }),
listMessagesAfterUid: async (_accountId: string, _folderId: string, afterUid: number) => {
headerRequests++
const eligible: MessageEnvelope[] = messages.filter((message) => Number(message.id) > afterUid).sort((first, second) => Number(first.id) - Number(second.id))
return { messages: eligible, total: eligible.length, unseen: 1 }
},
listMessages: async () => { fullRequests++; return { messages, total: messages.length, unseen: 1 } },
fetchMessageBody: async () => { bodyRequests++; return { id: '2', 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) }, (message): void => { errors.push(message) }, (): void => {}, new History(store))
try {
const initialStore: Conf<AgentStoreSchema> = createStore()
const oldEvent = { accountId: 'account', folderId: 'INBOX', envelope: messages[0] }
initialStore.set('processed', { [getMailKey(oldEvent)]: { notify: true, reason: 'Прежнее решение' } })
const first = createService(initialStore)
assert.equal(first.filterNotification(oldEvent), true)
await first.scan()
assert.equal(bodyRequests, 0)
assert.deepEqual(notifications, [])
assert.deepEqual(first.annotateMessages('account', messages)[0].agentDecision, { notify: true, reason: 'Прежнее решение' })
assert.deepEqual(first.annotateMessages('account', messages)[1].agentDecision, { notify: false, reason: 'Получено до начала обработки новых писем. Помечено неважным без анализа ИИ.', source: 'baseline' })
assert.equal(first.getUsage().totalTokens, 0)
messages = [...['3', '4', '5', '6', '7'].map(createMessage), ...messages]
const reopenedStore: Conf<AgentStoreSchema> = createStore()
reopenedStore.set('settings', { ...reopenedStore.get('settings'), batchSize: 2, concurrency: 2 })
const reopened = createService(reopenedStore)
await reopened.scan()
await reopened.scan()
assert.equal(bodyRequests, 5)
assert.deepEqual(notifications, ['3', '4', '5', '6', '7'])
assert.equal(reopened.getUsage().totalTokens, 45)
assert.equal(reopened.getMailStatistics().skippedExisting, 0)
assert.deepEqual(errors, [])
assert.equal(reopened.getProgress().inspected, 0)
assert.equal(reopened.getProgress().pending, 0)
assert.equal(reopened.getProgress().total, 0)
assert.equal(headerRequests, 1)
assert.equal(fullRequests, 0)
await reopened.synchronize()
assert.equal(reopened.getStorageStatistics().decisions, 6)
messages = messages.filter((message) => message.id !== '1')
includeBrokenFolder = true
await reopened.synchronize()
assert.equal(reopened.getProgress().inspected, 6)
assert.equal(reopened.getProgress().total, 7)
assert.equal(reopened.getProgress().errors, 1)
assert.match(errors[0], /UIDNEXT\/UIDVALIDITY/)
assert.equal(reopened.getStorageStatistics().decisions, 6)
assert.equal(reopened.getStorageStatistics().pendingRemoval, 0)
assert.equal(bodyRequests, 5)
} finally {
await server.close()
await rm(directory, { recursive: true, force: true })
}
})
test('сбой модели при синхронизации не сдвигает курсор новых писем следующего аккаунта', async (): Promise<void> => {
const directory: string = await mkdtemp(join(tmpdir(), 'aero-agent-retry-'))
const { server, Service, History, failRequests, restoreRequests } = await loadAgentTestModule()
let messages: MessageEnvelope[] = [createMessage('1')]
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: 1, concurrency: 2, url: 'http://localhost/v1', model: 'model' },
processed: {}, baselines: {}, usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 }
} })
const notifications: string[] = []
const errors: string[] = []
const service = new Service({
getAccounts: () => ['a', 'b'].map((id: string) => ({ id, email: `${id}@example.org`, label: id, type: 'imap' as AccountType, credentials: { host: 'localhost', port: 993, secure: true, username: id, password: '' } })),
getConnectedAccountIds: (): string[] => ['a', 'b'],
listFolders: async () => ({ folders: [{ id: 'INBOX', name: 'Входящие', role: 'inbox' as SpecialFolderRole, parentId: null, totalCount: messages.length, unreadCount: 1, children: [], uidNext: messages.length + 1, uidValidity: '1' }] }),
listMessages: async () => ({ messages, total: messages.length, unseen: 1 }),
listMessagesAfterUid: async (_accountId: string, _folderId: string, afterUid: number) => {
const eligible: MessageEnvelope[] = messages.filter((message) => Number(message.id) > afterUid)
return { messages: eligible, total: eligible.length, unseen: 1 }
},
fetchMessageBody: async () => ({ id: '2', text: 'Требуется ответ', html: null, references: null, attachments: [], inlineImages: [] })
}, store, { load: async (): Promise<void> => {}, get: (): undefined => undefined, save: async (): Promise<void> => {} },
(event): void => { notifications.push(event.accountId) }, (message): void => { errors.push(message) }, (): void => {}, new History(store))
try {
await service.scan()
messages = [...messages, createMessage('2')]
failRequests()
await service.synchronize()
assert.ok(errors.length > 0)
assert.deepEqual(notifications, [])
restoreRequests()
await service.scan()
assert.deepEqual(notifications, ['a', 'b'])
assert.equal(service.getProgress().pending, 0)
assert.equal(service.getMailStatistics().important, 2)
} finally { await server.close(); await rm(directory, { recursive: true, force: true }) }
})