45 lines
3.9 KiB
TypeScript
45 lines
3.9 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 type { AgentStoreSchema } from '../src/main/services/mail-agent-service.ts'
|
|
import type { AccountType } from '../src/shared/types/account.ts'
|
|
import type { MessageEnvelope } from '../src/shared/types/message.ts'
|
|
|
|
test('готовит черновик по исходному письму без отправки и учитывает расход отдельно от классификации', async (): Promise<void> => {
|
|
const directory: string = await mkdtemp(join(tmpdir(), 'aero-reply-'))
|
|
const { server, Service, History } = 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: 1, concurrency: 2, url: 'http://localhost/v1', model: 'model' },
|
|
processed: {}, baselines: {}, usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 }
|
|
} })
|
|
const envelope: MessageEnvelope = { id: '1', folderId: 'INBOX', subject: 'Нужно уточнение', from: { name: 'Автор', email: 'sender@example.org' }, to: [], cc: [], date: '2026-11-17', flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' }
|
|
let bodyRequests: number = 0
|
|
const 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 (): Promise<never> => { throw new Error('Папки не нужны для ответа') },
|
|
listMessages: async (): Promise<never> => { throw new Error('Полный обход не нужен для ответа') },
|
|
listMessagesAfterUid: async (_accountId: string, _folderId: string, afterUid: number, limit: number) => {
|
|
assert.equal(limit, 1)
|
|
return { messages: afterUid === 0 ? [envelope] : [], total: 1, unseen: 1 }
|
|
},
|
|
fetchMessageBody: async () => { bodyRequests++; return { id: '1', text: 'Прошу выполнить задачу.', html: null, references: null, attachments: [], inlineImages: [] } }
|
|
}, store, { load: async (): Promise<void> => {}, get: (): undefined => undefined, save: async (): Promise<void> => {} },
|
|
(): never => { throw new Error('Генерация ответа не создаёт уведомления') }, (): void => {}, (): never => { throw new Error('Классификация не запускается') }, new History(store))
|
|
try {
|
|
const request = { accountId: 'account', folderId: 'INBOX', messageId: '1', instructions: 'Попроси уточнить срок', draft: '' }
|
|
assert.equal(await service.prepareReply(request), 'Здравствуйте! Уточните, пожалуйста, срок выполнения задачи.')
|
|
assert.equal(bodyRequests, 1)
|
|
assert.equal(service.getUsage().totalTokens, 15)
|
|
assert.equal(service.getMailStatistics().analyzed, 0)
|
|
await assert.rejects(service.prepareReply({ ...request, messageId: '2' }), /Исходное письмо не найдено/)
|
|
store.set('settings', { ...store.get('settings'), enabled: false })
|
|
await assert.rejects(service.prepareReply(request), /Включите ИИ-агента/)
|
|
assert.equal(bodyRequests, 1)
|
|
} finally { await server.close(); await rm(directory, { recursive: true, force: true }) }
|
|
})
|