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

148 lines
8.1 KiB
TypeScript
Raw 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 { analyzeMail, parseAgentDecision, AgentResponseError, fetchAgentModels } from '../src/main/services/mail-agent-client.ts'
import type { AgentRequest } from '../src/main/services/mail-agent-client.ts'
const request: AgentRequest = {
url: 'http://localhost:11434/v1/', model: 'local-model', apiKey: 'secret',
email: 'user@example.org', name: 'Пользователь', text: 'Ответьте до завтра',
envelope: {
id: '1', folderId: 'INBOX', subject: 'Вопрос', from: { name: 'Коллега', email: 'other@example.org' },
to: [{ name: 'Пользователь', email: 'user@example.org' }], cc: [], date: '2026-11-16',
flags: { seen: false, flagged: false, answered: false, deleted: false },
hasAttachments: false, snippet: ''
}
}
test('разбирает решение с причиной и JSON в блоке кода', (): void => {
assert.deepEqual(parseAgentDecision('```json\n{"notify":true,"reason":" Нужен ответ "}\n```'), {
notify: true, reason: 'Нужен ответ'
})
})
test('принимает решение без уведомления', (): void => {
assert.deepEqual(parseAgentDecision('{"notify":false,"reason":"Рассылка"}'), { notify: false, reason: 'Рассылка' })
})
test('отклоняет неполные решения и неверные типы', (): void => {
for (const content of ['null', '{}', '{"notify":"false","reason":"x"}', '{"notify":true,"reason":""}']) {
assert.throws(() => parseAgentDecision(content), AgentResponseError)
}
assert.throws(() => parseAgentDecision('не JSON'), SyntaxError)
})
test('передаёт текст, адрес пользователя и ключ в локальный API', async (): Promise<void> => {
const send: typeof fetch = async (url, options): Promise<Response> => {
assert.equal(url, 'http://localhost:11434/v1/chat/completions')
assert.equal(new Headers(options?.headers).get('Authorization'), 'Bearer secret')
assert.equal(options?.redirect, 'error')
const payload: { model: string; messages: { content: string }[] } = JSON.parse(String(options?.body))
assert.equal(payload.model, 'local-model')
assert.match(payload.messages[1].content, /user@example.org/)
assert.match(payload.messages[1].content, /Ответьте до завтра/)
return Response.json({ choices: [{ message: { content: '{"notify":true,"reason":"Нужен ответ"}' } }] })
}
assert.deepEqual(await analyzeMail(request, send, (): void => {}), { notify: true, reason: 'Нужен ответ' })
})
test('явно сообщает об ошибке сервера', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => new Response('', { status: 503 })
await assert.rejects(analyzeMail(request, send, (): void => {}), /HTTP 503/)
})
test('отклоняет ответ без решения', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({ choices: [] })
await assert.rejects(analyzeMail(request, send, (): void => {}), AgentResponseError)
})
test('учитывает токены даже при некорректном решении модели', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({
usage: { prompt_tokens: 100, completion_tokens: 20, total_tokens: 120 },
choices: [{ message: { content: 'не JSON' } }]
})
const recorded: unknown[] = []
await assert.rejects(analyzeMail(request, send, (usage): void => { recorded.push(usage) }), AgentResponseError)
assert.deepEqual(recorded, [{ inputTokens: 100, outputTokens: 20, totalTokens: 120 }])
})
test('сообщает об отсутствии статистики в ответе', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({
choices: [{ message: { content: '{"notify":false,"reason":"Рассылка"}' } }]
})
const recorded: unknown[] = []
await analyzeMail(request, send, (usage): void => { recorded.push(usage) })
assert.deepEqual(recorded, [null])
})
test('показывает HTTP-статус, сообщение сервера, адрес и модель', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({
error: { message: 'Model local-model was not found' }
}, { status: 404 })
await assert.rejects(analyzeMail(request, send, (): void => {}), (error: unknown): boolean => {
assert.ok(error instanceof AgentResponseError)
assert.match(error.message, /HTTP 404/)
assert.match(error.message, /Model local-model was not found/)
assert.match(error.message, /localhost:11434\/v1\/chat\/completions/)
assert.match(error.message, /Модель: local-model/)
return true
})
})
test('раскрывает причину сетевого сбоя', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => {
throw new TypeError('fetch failed', { cause: Object.assign(new Error('Connection refused'), { code: 'ECONNREFUSED' }) })
}
await assert.rejects(analyzeMail(request, send, (): void => {}), /Connection refused \[ECONNREFUSED\]/)
})
test('поясняет тайм-аут', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => { throw new DOMException('timeout', 'TimeoutError') }
await assert.rejects(analyzeMail(request, send, (): void => {}), /90 секунд/)
})
test('скрывает ключ в сообщении сервера', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({ error: { message: 'Invalid key secret' } }, { status: 401 })
await assert.rejects(analyzeMail(request, send, (): void => {}), (error: unknown): boolean => {
assert.ok(error instanceof AgentResponseError)
assert.doesNotMatch(error.message, /secret/)
assert.match(error.message, /ключ скрыт/)
return true
})
})
test('загружает уникальные имена моделей с указанного сервера и передаёт ключ', async (): Promise<void> => {
const send: typeof fetch = async (url, options): Promise<Response> => {
assert.equal(url, 'https://local.example/v1/models')
assert.equal(options?.method, 'GET')
assert.equal(options?.redirect, 'error')
assert.equal(new Headers(options?.headers).get('Authorization'), 'Bearer token')
return Response.json({ data: [{ id: 'model-b' }, { id: 'model-a' }, { id: 'model-b' }] })
}
assert.deepEqual(await fetchAgentModels({ url: 'https://local.example/v1/', apiKey: 'token' }, send), ['model-a', 'model-b'])
})
test('загружает модели без авторизации для локального сервера', async (): Promise<void> => {
const send: typeof fetch = async (_url, options): Promise<Response> => {
assert.equal(new Headers(options?.headers).has('Authorization'), false)
return Response.json({ data: [] })
}
assert.deepEqual(await fetchAgentModels({ url: 'http://localhost:11434/v1', apiKey: '' }, send), [])
})
test('показывает ошибку загрузки моделей и скрывает ключ', async (): Promise<void> => {
const send: typeof fetch = async (): Promise<Response> => Response.json({ error: { message: 'Invalid token secret' } }, { status: 401 })
await assert.rejects(fetchAgentModels({ url: 'https://local.example/v1', apiKey: 'secret' }, send), (error: unknown): boolean => {
assert.ok(error instanceof AgentResponseError)
assert.match(error.message, /HTTP 401/)
assert.match(error.message, /\/v1\/models/)
assert.doesNotMatch(error.message, /secret/)
return true
})
})
test('отклоняет неверный формат списка моделей', async (): Promise<void> => {
for (const response of [{}, { data: [{}] }, { data: [{ id: '' }] }]) {
const send: typeof fetch = async (): Promise<Response> => Response.json(response)
await assert.rejects(fetchAgentModels({ url: 'http://localhost/v1', apiKey: '' }, send), AgentResponseError)
}
})