From f5fc312afda571820de3bce796b4aad6ad525778 Mon Sep 17 00:00:00 2001 From: "r.rasputin" Date: Mon, 16 Nov 2026 18:12:54 +0700 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D1=81=D1=82=D0=B0=D1=82=D0=B8=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D0=BE=D0=B2,=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA=D0=B0=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B5=D0=B9=20=D0=B8=20=D0=BF=D0=BE=D0=B4?= =?UTF-8?q?=D1=80=D0=BE=D0=B1=D0=BD=D1=8B=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=98=D0=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 ++ src/main/index.ts | 3 +- src/main/ipc/agent.handler.ts | 3 + src/main/services/mail-agent-client.ts | 106 ++++++++++++- src/main/services/mail-agent-service.ts | 50 +++++- src/main/services/mail-agent-usage.ts | 16 ++ src/renderer/src/components/AgentSettings.vue | 150 ++++++++++++++---- .../notifications/NotificationContainer.vue | 3 +- .../notifications/NotificationToast.vue | 4 + src/renderer/src/views/SettingsView.vue | 3 +- src/shared/types/agent.ts | 21 +++ src/shared/types/ipc.ts | 5 +- tests/mail-agent-client.test.ts | 100 +++++++++++- tests/mail-agent-usage.test.ts | 40 +++++ 14 files changed, 465 insertions(+), 52 deletions(-) create mode 100644 src/main/services/mail-agent-usage.ts create mode 100644 tests/mail-agent-usage.test.ts diff --git a/README.md b/README.md index 5546032..5ba9f9c 100644 --- a/README.md +++ b/README.md @@ -138,3 +138,16 @@ OpenAI-совместимого API локальной модели (напри Ошибки показываются в приложении; необработанное письмо будет проверено повторно. Проверка клиента модели без сети (Node.js 22.6+): `npm run test:agent`. + +В настройках ИИ-агента отображается накопленный расход входных и выходных токенов +и общий итог по всем моделям. Статистика берётся из поля `usage` ответа сервера, +обновляется каждые пять секунд и сохраняется между запусками. Учёт начинается с +добавления счётчика; прежний расход восстановить нельзя. Ответы без корректного +`usage` отмечаются отдельно, их расход не оценивается. При HTTP-ошибке или обрыве +соединения расход неизвестен. Если ответ получен со статистикой, токены учитываются +даже при некорректном решении модели. + +Кнопка «Загрузить модели» рядом с названием модели запрашивает `GET /models` +и предлагает выбрать имя из `data[].id`. Используются текущий URL и введённый ключ, +а при пустом поле ключа — сохранённый ключ. Загрузка списка не сохраняет настройки; +после выбора нажмите «Сохранить настройки ИИ». Ручной ввод имени также доступен. diff --git a/src/main/index.ts b/src/main/index.ts index 251b2f2..a3205b1 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,3 +1,4 @@ +import { createUsageStatistics } from './services/mail-agent-usage' import Store from 'electron-store' import { CredentialStore } from './services/credential-store' import type { AgentStoreSchema } from './services/mail-agent-service' @@ -31,7 +32,7 @@ let mainWindowRef: BrowserWindow | null = null const mailAgent = new MailAgentService(accountManager, new Store({ name: 'mail-agent', - defaults: { settings: { enabled: false, notifyMutedFolders: false, url: 'http://localhost:11434/v1', model: '' }, processed: {} } + defaults: { settings: { enabled: false, notifyMutedFolders: false, url: 'http://localhost:11434/v1', model: '' }, processed: {}, usage: createUsageStatistics() } }), new CredentialStore('agent-credentials.json'), (event): void => { diff --git a/src/main/ipc/agent.handler.ts b/src/main/ipc/agent.handler.ts index d348537..4801fa1 100644 --- a/src/main/ipc/agent.handler.ts +++ b/src/main/ipc/agent.handler.ts @@ -2,6 +2,9 @@ import { registerHandler } from './registry' import type { MailAgentService } from '../services/mail-agent-service' export function registerAgentHandlers(agent: MailAgentService): void { + registerHandler('agent:models:list', async (request) => agent.listModels(request)) + registerHandler('agent:error:get', async () => agent.getLastError()) + registerHandler('agent:usage:get', async () => agent.getUsage()) registerHandler('agent:settings:get', async () => agent.getSettings()) registerHandler('agent:settings:save', async (settings) => agent.saveSettings(settings)) } diff --git a/src/main/services/mail-agent-client.ts b/src/main/services/mail-agent-client.ts index 0cbcd47..545a4c2 100644 --- a/src/main/services/mail-agent-client.ts +++ b/src/main/services/mail-agent-client.ts @@ -1,4 +1,4 @@ -import type { AgentDecision } from '@shared/types/agent' +import type { AgentDecision, AgentTokenUsage } from '@shared/types/agent' import type { MessageEnvelope } from '@shared/types/message' export class AgentResponseError extends Error {} @@ -13,18 +13,73 @@ export interface AgentRequest { text: string } +function isTokenCount(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 +} + +export function parseTokenUsage(response: unknown): AgentTokenUsage | null { + if (typeof response !== 'object' || response === null || !('usage' in response)) return null + const usage: unknown = response.usage + if (typeof usage !== 'object' || usage === null || + !('prompt_tokens' in usage) || !isTokenCount(usage.prompt_tokens) || + !('completion_tokens' in usage) || !isTokenCount(usage.completion_tokens)) return null + const totalTokens: number = 'total_tokens' in usage && isTokenCount(usage.total_tokens) + ? usage.total_tokens : usage.prompt_tokens + usage.completion_tokens + return { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens, totalTokens } +} + export function parseAgentDecision(content: string): AgentDecision { const decision: unknown = JSON.parse(content.replace(/^```(?:json)?\s*|\s*```$/g, '').trim()) if (typeof decision !== 'object' || decision === null || !('notify' in decision) || typeof decision.notify !== 'boolean' || !('reason' in decision) || typeof decision.reason !== 'string' || (decision.notify && !decision.reason.trim())) { - throw new AgentResponseError('Модель вернула некорректное решение') + throw new AgentResponseError('Неверный формат решения: ожидается JSON с полями notify (boolean) и reason (string); для уведомления причина должна быть непустой') } return { notify: decision.notify, reason: decision.reason.trim().slice(0, 500) } } -export async function analyzeMail(request: AgentRequest, send: typeof fetch): Promise { +function describeFailure(error: unknown): string { + if (!(error instanceof Error)) return String(error) + const code: string = 'code' in error && typeof error.code === 'string' ? ` [${error.code}]` : '' + const cause: string = error.cause instanceof Error ? `: ${describeFailure(error.cause)}` : '' + if (error.name === 'TimeoutError' || error.name === 'AbortError') return 'Превышено время ожидания ответа модели (90 секунд)' + return `${error.message}${code}${cause}` +} + +function redactSecret(message: string, apiKey: string): string { + return apiKey ? message.split(apiKey).join('[ключ скрыт]') : message +} + +async function describeServerError(response: Response): Promise { + const body: string = await response.text() + if (!body.trim()) return 'Сервер не передал описание ошибки' + let parsed: unknown + try { parsed = JSON.parse(body) } catch (error: unknown) { + if (!(error instanceof SyntaxError)) throw error + return body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 1500) + } + if (typeof parsed === 'object' && parsed !== null && 'error' in parsed) { + const detail: unknown = parsed.error + if (typeof detail === 'string') return detail.slice(0, 1500) + if (typeof detail === 'object' && detail !== null && 'message' in detail && typeof detail.message === 'string') { + return detail.message.slice(0, 1500) + } + } + if (typeof parsed === 'object' && parsed !== null && 'message' in parsed && typeof parsed.message === 'string') return parsed.message.slice(0, 1500) + return 'Сервер вернул ошибку без текстового описания' +} + +export async function analyzeMail(request: AgentRequest, send: typeof fetch, recordUsage: (usage: AgentTokenUsage | null) => void): Promise { + const endpoint: string = `${request.url.replace(/\/+$/, '')}/chat/completions` + try { + return await requestMailAnalysis(request, send, recordUsage) + } catch (error: unknown) { + throw new AgentResponseError(redactSecret(`Сервер: ${endpoint}\nМодель: ${request.model}\n${describeFailure(error)}`, request.apiKey), { cause: error }) + } +} + +async function requestMailAnalysis(request: AgentRequest, send: typeof fetch, recordUsage: (usage: AgentTokenUsage | null) => void): Promise { const endpoint: string = `${request.url.replace(/\/+$/, '')}/chat/completions` const response: Response = await send(endpoint, { method: 'POST', @@ -43,8 +98,13 @@ export async function analyzeMail(request: AgentRequest, send: typeof fetch): Pr ] }) }) - if (!response.ok) throw new AgentResponseError(`Сервер модели вернул HTTP ${response.status}`) - const result: unknown = await response.json() + if (!response.ok) throw new AgentResponseError(`HTTP ${response.status} ${response.statusText}: ${await describeServerError(response)}`) + let result: unknown + try { result = await response.json() } catch (error: unknown) { + if (!(error instanceof SyntaxError)) throw error + throw new AgentResponseError(`Сервер вернул ответ, который не является JSON (Content-Type: ${response.headers.get('content-type') ?? 'не указан'})`, { cause: error }) + } + recordUsage(parseTokenUsage(result)) if (typeof result !== 'object' || result === null || !('choices' in result) || !Array.isArray(result.choices)) { throw new AgentResponseError('В ответе модели отсутствует choices') } @@ -54,5 +114,39 @@ export async function analyzeMail(request: AgentRequest, send: typeof fetch): Pr !('content' in choice.message) || typeof choice.message.content !== 'string') { throw new AgentResponseError('В ответе модели отсутствует текст решения') } - return parseAgentDecision(choice.message.content) + try { return parseAgentDecision(choice.message.content) } catch (error: unknown) { + if (!(error instanceof SyntaxError)) throw error + throw new AgentResponseError('Модель вернула текст вместо JSON-решения; ожидается {"notify": boolean, "reason": "причина"}') + } +} + +export interface AgentConnection { + url: string + apiKey: string +} + +export async function fetchAgentModels(connection: AgentConnection, send: typeof fetch): Promise { + const endpoint: string = `${connection.url.replace(/\/+$/, '')}/models` + try { + const response: Response = await send(endpoint, { + method: 'GET', redirect: 'error', signal: AbortSignal.timeout(15_000), + headers: connection.apiKey ? { Authorization: `Bearer ${connection.apiKey}` } : {} + }) + if (!response.ok) throw new AgentResponseError(`HTTP ${response.status} ${response.statusText}: ${await describeServerError(response)}`) + const result: unknown = await response.json() + if (typeof result !== 'object' || result === null || !('data' in result) || !Array.isArray(result.data)) { + throw new AgentResponseError('В ответе сервера отсутствует список data') + } + const models: string[] = result.data.map((model: unknown): string => { + if (typeof model !== 'object' || model === null || !('id' in model) || typeof model.id !== 'string' || !model.id.trim()) { + throw new AgentResponseError('В списке моделей обнаружен некорректный id') + } + return model.id + }) + return [...new Set(models)].sort((first: string, second: string): number => first.localeCompare(second)) + } catch (error: unknown) { + const detail: string = error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError') + ? 'Превышено время ожидания списка моделей (15 секунд)' : describeFailure(error) + throw new AgentResponseError(redactSecret(`Сервер: ${endpoint}\n${detail}`, connection.apiKey), { cause: error }) + } } diff --git a/src/main/services/mail-agent-service.ts b/src/main/services/mail-agent-service.ts index 2f21872..a232746 100644 --- a/src/main/services/mail-agent-service.ts +++ b/src/main/services/mail-agent-service.ts @@ -1,29 +1,42 @@ +import { addTokenUsage, createUsageStatistics } from './mail-agent-usage' +import type { AgentUsageStatistics, AgentErrorDetails } from '@shared/types/agent' import type Store from 'electron-store' import { getMailKey, MailAgentNotifications } from './mail-agent-notifications' import type { IncomingMail } from './mail-agent-notifications' -import type { AgentSettings, AgentSettingsUpdate } from '@shared/types/agent' +import type { AgentSettings, AgentSettingsUpdate, AgentModelsRequest } from '@shared/types/agent' import type { IpcEventMap } from '@shared/types/ipc' import type { Folder } from '@shared/types/folder' import type { AccountManager } from './account-manager' import type { CredentialStore } from './credential-store' import type { AgentRequest } from './mail-agent-client' import type { AgentDecision } from '@shared/types/agent' -import { analyzeMail } from './mail-agent-client' +import { analyzeMail, fetchAgentModels } from './mail-agent-client' import { ewsBodyToMarkdown } from '../lib/html-to-markdown' export interface AgentStoreSchema { settings: Omit processed: Record + usage: AgentUsageStatistics } export class AgentSettingsError extends Error {} +function validateAgentUrl(value: string): URL { + let url: URL + try { url = new URL(value) } catch { throw new AgentSettingsError('Укажите корректный URL сервера') } + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) { + throw new AgentSettingsError('Нужен HTTP(S) URL без пароля, параметров и фрагмента') + } + return url +} + type AgentEvent = IpcEventMap['agent:notification'] export class MailAgentService { private timer: ReturnType | null = null private running: boolean = false private revision: number = 0 + private lastError: AgentErrorDetails | null = null private readonly notifications: MailAgentNotifications = new MailAgentNotifications() constructor( @@ -50,10 +63,30 @@ export class MailAgentService { this.timer = null } + getLastError(): AgentErrorDetails | null { + return this.lastError + } + + getUsage(): AgentUsageStatistics { + return this.store.get('usage') ?? createUsageStatistics() + } + getSettings(): AgentSettings { return { ...this.store.get('settings'), notifyMutedFolders: this.store.get('settings').notifyMutedFolders ?? false, hasApiKey: Boolean(this.credentials.get('mail-agent-api-key')) } } + async listModels(request: AgentModelsRequest): Promise { + if (typeof request !== 'object' || request === null || typeof request.url !== 'string' || + (request.apiKey !== null && typeof request.apiKey !== 'string')) { + throw new AgentSettingsError('Некорректные параметры загрузки моделей') + } + const url: URL = validateAgentUrl(request.url) + return fetchAgentModels({ + url: url.toString(), + apiKey: request.apiKey === null ? this.credentials.get('mail-agent-api-key') ?? '' : request.apiKey.trim() + }, fetch) + } + async saveSettings(update: AgentSettingsUpdate): Promise { if (typeof update !== 'object' || update === null || typeof update.enabled !== 'boolean' || typeof update.notifyMutedFolders !== 'boolean' || @@ -61,11 +94,7 @@ export class MailAgentService { (update.apiKey !== null && typeof update.apiKey !== 'string')) { throw new AgentSettingsError('Некорректные настройки ИИ-агента') } - let url: URL - try { url = new URL(update.url) } catch { throw new AgentSettingsError('Укажите корректный URL сервера') } - if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) { - throw new AgentSettingsError('Нужен HTTP(S) URL без пароля, параметров и фрагмента') - } + const url: URL = validateAgentUrl(update.url) if (update.enabled && !update.model.trim()) throw new AgentSettingsError('Укажите название модели') if (update.apiKey !== null) await this.credentials.save('mail-agent-api-key', update.apiKey.trim()) this.store.set('settings', { enabled: update.enabled, notifyMutedFolders: update.notifyMutedFolders, url: url.toString().replace(/\/+$/, ''), model: update.model.trim() }) @@ -87,6 +116,7 @@ export class MailAgentService { } } catch (error: unknown) { const message: string = error instanceof Error ? error.message : 'Неизвестная ошибка анализа почты' + this.lastError = { message, occurredAt: new Date().toISOString() } console.error('[MailAgent]', message) this.reportError(message) } finally { @@ -96,7 +126,11 @@ export class MailAgentService { private async analyze(request: AgentRequest, revision: number): Promise { try { - return await analyzeMail(request, fetch) + const decision: AgentDecision = await analyzeMail(request, fetch, (usage): void => { + this.store.set('usage', addTokenUsage(this.getUsage(), usage)) + }) + if (revision === this.revision) this.lastError = null + return decision } catch (error: unknown) { if (revision === this.revision) { for (const event of this.notifications.fail()) this.publish({ ...event, reason: '', allowMuted: false }) diff --git a/src/main/services/mail-agent-usage.ts b/src/main/services/mail-agent-usage.ts new file mode 100644 index 0000000..7336452 --- /dev/null +++ b/src/main/services/mail-agent-usage.ts @@ -0,0 +1,16 @@ +import type { AgentTokenUsage, AgentUsageStatistics } from '@shared/types/agent' + +export function createUsageStatistics(): AgentUsageStatistics { + return { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 } +} + +export function addTokenUsage(statistics: AgentUsageStatistics, usage: AgentTokenUsage | null): AgentUsageStatistics { + if (usage === null) return { ...statistics, unmeasuredResponses: statistics.unmeasuredResponses + 1 } + return { + inputTokens: statistics.inputTokens + usage.inputTokens, + outputTokens: statistics.outputTokens + usage.outputTokens, + totalTokens: statistics.totalTokens + usage.totalTokens, + measuredResponses: statistics.measuredResponses + 1, + unmeasuredResponses: statistics.unmeasuredResponses + } +} diff --git a/src/renderer/src/components/AgentSettings.vue b/src/renderer/src/components/AgentSettings.vue index effae6f..b072ece 100644 --- a/src/renderer/src/components/AgentSettings.vue +++ b/src/renderer/src/components/AgentSettings.vue @@ -1,16 +1,69 @@ diff --git a/src/renderer/src/components/notifications/NotificationContainer.vue b/src/renderer/src/components/notifications/NotificationContainer.vue index b15b5ce..15ed914 100644 --- a/src/renderer/src/components/notifications/NotificationContainer.vue +++ b/src/renderer/src/components/notifications/NotificationContainer.vue @@ -9,6 +9,7 @@ import type { IpcEventMap } from '@shared/types/ipc' import { useNotificationsStore } from '../../stores/notifications.store' interface ToastItem { + details?: string id: string from: string subject: string @@ -94,7 +95,7 @@ onMounted(() => { })) unsubscribers.push(on('agent:notification', (event) => notify(event, event.reason))) unsubscribers.push(on('agent:error', ({ message }) => { - addToast({ from: 'Ошибка ИИ-агента', subject: message, accountEmail: '', accountId: '', folderId: '', messageId: '' }) + addToast({ from: 'Ошибка ИИ-агента', subject: 'Подробности также доступны в настройках ИИ', details: message, accountEmail: '', accountId: '', folderId: '', messageId: '' }) })) }) diff --git a/src/renderer/src/components/notifications/NotificationToast.vue b/src/renderer/src/components/notifications/NotificationToast.vue index 642c242..9637170 100644 --- a/src/renderer/src/components/notifications/NotificationToast.vue +++ b/src/renderer/src/components/notifications/NotificationToast.vue @@ -6,6 +6,7 @@ const props = defineProps<{ id: string from: string subject: string + details?: string accountEmail: string onClose: (id: string) => void onClick: (id: string) => void @@ -30,6 +31,7 @@ onMounted(() => {
{{ from }}
{{ subject }}
+
{{ details }}