import { test } from 'node:test' import assert from 'node:assert/strict' import { analyzeMail, parseAgentDecision, AgentResponseError, fetchAgentModels, analyzeMailBatch, parseBatchDecisions, generateMailReply } 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', prompt: 'Проверь важность письма', 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 => { const send: typeof fetch = async (url, options): Promise => { 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.equal(payload.messages[0].content, 'Проверь важность письма') 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 => { const send: typeof fetch = async (): Promise => new Response('', { status: 503 }) await assert.rejects(analyzeMail(request, send, (): void => {}), /HTTP 503/) }) test('отклоняет ответ без решения', async (): Promise => { const send: typeof fetch = async (): Promise => Response.json({ choices: [] }) await assert.rejects(analyzeMail(request, send, (): void => {}), AgentResponseError) }) test('учитывает токены даже при некорректном решении модели', async (): Promise => { const send: typeof fetch = async (): Promise => 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 => { const send: typeof fetch = async (): Promise => 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 => { const send: typeof fetch = async (): Promise => 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 => { const send: typeof fetch = async (): Promise => { 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 => { const send: typeof fetch = async (): Promise => { throw new DOMException('timeout', 'TimeoutError') } await assert.rejects(analyzeMail(request, send, (): void => {}), /90 секунд/) }) test('скрывает ключ в сообщении сервера', async (): Promise => { const send: typeof fetch = async (): Promise => 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 => { const send: typeof fetch = async (url, options): Promise => { 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 => { const send: typeof fetch = async (_url, options): Promise => { 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 => { const send: typeof fetch = async (): Promise => 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 => { for (const response of [{}, { data: [{}] }, { data: [{ id: '' }] }]) { const send: typeof fetch = async (): Promise => Response.json(response) await assert.rejects(fetchAgentModels({ url: 'http://localhost/v1', apiKey: '' }, send), AgentResponseError) } }) test('сопоставляет решения порции по id независимо от порядка ответа', (): void => { assert.deepEqual(parseBatchDecisions('{"decisions":[{"id":"1","notify":false,"reason":"Рассылка"},{"id":"0","notify":true,"reason":"Задача"}]}', 2), [ { notify: true, reason: 'Задача' }, { notify: false, reason: 'Рассылка' } ]) }) test('отклоняет неполные, повторяющиеся и чужие id в порции', (): void => { for (const content of [ '{"decisions":[{"id":"0","notify":true,"reason":"Задача"}]}', '{"decisions":[{"id":"0","notify":true,"reason":"Задача"},{"id":"0","notify":false,"reason":"Рассылка"}]}', '{"decisions":[{"id":"0","notify":true,"reason":"Задача"},{"id":"3","notify":false,"reason":"Рассылка"}]}' ]) assert.throws(() => parseBatchDecisions(content, 2), AgentResponseError) }) test('передаёт порцию одним запросом и учитывает расход один раз', async (): Promise => { let calls: number = 0 let usageCalls: number = 0 const send: typeof fetch = async (_url, options): Promise => { calls++ const payload: { messages: { content: string }[] } = JSON.parse(String(options?.body)) const user: { messages: { id: string }[] } = JSON.parse(payload.messages[1].content) assert.deepEqual(user.messages.map((message) => message.id), ['0', '1']) return Response.json({ usage: { prompt_tokens: 100, completion_tokens: 20 }, choices: [{ message: { content: '{"decisions":[{"id":"0","notify":true,"reason":"Задача"},{"id":"1","notify":false,"reason":"Рассылка"}]}' } }] }) } assert.deepEqual(await analyzeMailBatch([request, { ...request, text: 'Рассылка' }], send, (): void => { usageCalls++ }), [ { notify: true, reason: 'Задача' }, { notify: false, reason: 'Рассылка' } ]) assert.equal(calls, 1) assert.equal(usageCalls, 1) }) test('готовит текст ответа с пожеланиями пользователя и учитывает токены', async (): Promise => { let measured: number = 0 const send: typeof fetch = async (_url, options): Promise => { const payload: { messages: { content: string }[] } = JSON.parse(String(options?.body)) assert.match(payload.messages[0].content, /Не выдумывай факты/) assert.match(payload.messages[0].content, /без Markdown/) const content: { original: { text: string }; instructions: string; draft: string } = JSON.parse(payload.messages[1].content) assert.equal(content.original.text, 'Ответьте до завтра') assert.equal(content.instructions, 'Попроси уточнить срок') assert.equal(content.draft, 'Здравствуйте') return Response.json({ usage: { prompt_tokens: 100, completion_tokens: 10 }, choices: [{ message: { content: ' Уточните, пожалуйста, срок выполнения. ' } }] }) } assert.equal(await generateMailReply(request, { instructions: 'Попроси уточнить срок', draft: 'Здравствуйте' }, send, (): void => { measured++ }), 'Уточните, пожалуйста, срок выполнения.') assert.equal(measured, 1) }) test('не принимает пустой ответ модели и не раскрывает ключ при ошибке подготовки', async (): Promise => { const empty: typeof fetch = async (): Promise => Response.json({ choices: [{ message: { content: ' ' } }] }) await assert.rejects(generateMailReply(request, { instructions: '', draft: '' }, empty, (): void => {}), /пустой черновик/) const failure: typeof fetch = async (): Promise => Response.json({ error: { message: 'Invalid secret' } }, { status: 401 }) await assert.rejects(generateMailReply(request, { instructions: '', draft: '' }, failure, (): void => {}), (error: unknown): boolean => { assert.ok(error instanceof AgentResponseError) assert.match(error.message, /HTTP 401/) assert.doesNotMatch(error.message, /secret/) return true }) })