aero-mail/tests/mail-agent-history.test.ts

149 lines
8.6 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, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import Conf from 'conf'
import type { AgentTestModule } from './helpers/agent-module.ts'
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'
interface HistoryFixture extends AgentTestModule {
store: Conf<AgentStoreSchema>
close: () => Promise<void>
}
async function createFixture(): Promise<HistoryFixture> {
const directory: string = await mkdtemp(join(tmpdir(), 'aero-history-'))
const environment = await loadAgentTestModule()
const store: Conf<AgentStoreSchema> = new Conf<AgentStoreSchema>({ cwd: directory, configName: 'mail-agent', defaults: {
settings: { enabled: false, notifyMutedFolders: false, prompt: DEFAULT_AGENT_PROMPT, pageSize: 100, batchSize: 1, concurrency: 2, url: 'http://localhost/v1', model: 'model' },
processed: {}, baselines: {}, usage: { inputTokens: 15, outputTokens: 5, totalTokens: 20, measuredResponses: 1, unmeasuredResponses: 0 }
} })
return { ...environment, store, close: async (): Promise<void> => { await environment.server.close(); await rm(directory, { recursive: true, force: true }) } }
}
test('миграция удаляет автоматические отметки, сохраняет решения модели и не повторяет счётчики', async (): Promise<void> => {
const fixture = await createFixture()
try {
fixture.store.set('processed', {
important: { notify: true, reason: 'Задача' }, ordinary: { notify: false, reason: 'Рассылка' },
old: { notify: false, reason: 'Старое', source: 'baseline' }, legacy: true
})
const history = new fixture.History(fixture.store)
assert.deepEqual(history.getStatistics(), { analyzed: 3, important: 1, unimportant: 1, withoutDecision: 1, skippedExisting: 1 })
assert.deepEqual(fixture.store.get('processed'), {})
assert.equal(history.getDecision('old'), undefined)
assert.deepEqual(history.getDecision('important'), { notify: true, reason: 'Задача' })
const reopened = new fixture.History(fixture.store)
assert.equal(reopened.getStatistics().analyzed, 3)
assert.equal(reopened.getStorageStatistics().decisions, 3)
assert.equal(fixture.store.get('usage').totalTokens, 20)
} finally { await fixture.close() }
})
test('удаляет отсутствующее решение после двух подтверждений, сохраняя исторические счётчики', async (): Promise<void> => {
const fixture = await createFixture()
try {
const history = new fixture.History(fixture.store)
history.savePage('account', ['key'], { key: { notify: true, reason: 'Задача' } })
history.completeAccount('account', new Set<string>(), 0, 1_000)
assert.equal(history.getStorageStatistics().pendingRemoval, 1)
assert.deepEqual(history.getDecision('key'), { notify: true, reason: 'Задача' })
history.completeAccount('account', new Set<string>(), 0, 60_999)
assert.equal(history.getStorageStatistics().decisions, 1)
history.completeAccount('account', new Set<string>(), 0, 61_000)
assert.equal(history.getStorageStatistics().decisions, 0)
assert.equal(history.getStatistics().important, 1)
assert.equal(history.getStatistics().analyzed, 1)
assert.equal(fixture.store.get('usage').totalTokens, 20)
} finally { await fixture.close() }
})
test('копия или перемещение с тем же ключом отменяет удаление и не увеличивает счётчики', async (): Promise<void> => {
const fixture = await createFixture()
try {
const history = new fixture.History(fixture.store)
history.savePage('account', ['key'], { key: { notify: false, reason: 'Рассылка' } })
history.completeAccount('account', new Set<string>(), 0, 1_000)
history.savePage('account', ['key'], {})
history.completeAccount('account', new Set<string>(['key']), 0, 100_000)
assert.equal(history.getStorageStatistics().pendingRemoval, 0)
assert.equal(history.getStorageStatistics().decisions, 1)
assert.equal(history.getStatistics().analyzed, 1)
} finally { await fixture.close() }
})
test('не чистит неподтверждённые старые записи после синхронизации только одного аккаунта', async (): Promise<void> => {
const fixture = await createFixture()
try {
fixture.store.set('processed', { unknown: { notify: true, reason: 'Задача' } })
const history = new fixture.History(fixture.store)
history.completeAccount('online', new Set<string>(), 0, 1_000)
history.completeAccount('online', new Set<string>(), 0, 100_000)
assert.equal(history.getStorageStatistics().decisions, 1)
assert.equal(history.getStorageStatistics().pendingRemoval, 0)
history.completeAllAccounts(new Set<string>(['online', 'offline']), new Set<string>(), 100_000)
history.completeAllAccounts(new Set<string>(['online', 'offline']), new Set<string>(), 160_000)
assert.equal(history.getStorageStatistics().decisions, 0)
assert.equal(history.getStatistics().important, 1)
} finally { await fixture.close() }
})
test('полная синхронизация запускается не чаще раза в сутки, ручной запрос не меняет расписание будущих аккаунтов', async (): Promise<void> => {
const fixture = await createFixture()
try {
const history = new fixture.History(fixture.store)
const now: number = Date.now()
assert.equal(history.needsMaintenance('account', now), false)
history.requestMaintenance(new Set<string>(['account']))
assert.equal(history.needsMaintenance('account', now), true)
assert.equal(history.needsMaintenance('future', now), false)
history.beginMaintenance('account', now)
assert.equal(history.needsMaintenance('account', now + 86_399_999), false)
assert.equal(history.needsMaintenance('account', now + 86_400_000), true)
} finally { await fixture.close() }
})
test('обновляет старую историю без maintenance и createdAt, сохраняя решения и счётчики после перезапуска', async (): Promise<void> => {
const fixture = await createFixture()
try {
const accountId: string = '1782362735647-5v6rpaf'
const oldHistory = {
version: 1,
records: { important: { accountId, decision: { notify: true, reason: 'Требуется ответ' }, missingSince: null } },
counters: { analyzed: 12, important: 7, unimportant: 4, withoutDecision: 1, skippedExisting: 0 },
baselineCounts: { [accountId]: 100 }, legacyBaselineCount: 0, lastCleanupAt: null
}
await writeFile(fixture.store.path, JSON.stringify({ ...fixture.store.store, history: oldHistory }), 'utf8')
const history = new fixture.History(fixture.store)
const now: number = Date.now()
assert.equal(history.needsMaintenance(accountId, now), false)
assert.equal(history.hasSnapshot(accountId), true)
assert.deepEqual(history.getDecision('important'), { notify: true, reason: 'Требуется ответ' })
assert.equal(history.getStatistics().analyzed, 12)
assert.equal(history.getStatistics().important, 7)
const saved = fixture.store.get('history')
assert.equal(saved?.version, 2)
assert.deepEqual(saved?.maintenance, {})
assert.ok(saved?.createdAt)
history.beginMaintenance(accountId, now)
const reopened = new fixture.History(fixture.store)
assert.equal(reopened.needsMaintenance(accountId, now + 1), false)
assert.equal(reopened.getStatistics().analyzed, 12)
assert.deepEqual(reopened.getDecision('important'), { notify: true, reason: 'Требуется ответ' })
assert.equal(fixture.store.get('usage').totalTokens, 20)
} finally { await fixture.close() }
})
test('не сбрасывает неизвестную версию истории в пустую', async (): Promise<void> => {
const fixture = await createFixture()
try {
await writeFile(fixture.store.path, JSON.stringify({ ...fixture.store.store, history: { version: 99, records: { keep: 'данные' } } }), 'utf8')
const history = new fixture.History(fixture.store)
assert.throws(() => history.needsMaintenance('account', Date.now()), /Неподдерживаемая версия истории/)
assert.equal(fixture.store.get('history')?.version, 99)
} finally { await fixture.close() }
})