212 lines
11 KiB
TypeScript
212 lines
11 KiB
TypeScript
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() }
|
||
})
|