Добавлены статистика токенов, загрузка моделей и подробные ошибки ИИ
This commit is contained in:
parent
b9a936eb84
commit
f5fc312afd
14 changed files with 465 additions and 52 deletions
13
README.md
13
README.md
|
|
@ -138,3 +138,16 @@ OpenAI-совместимого API локальной модели (напри
|
|||
Ошибки показываются в приложении; необработанное письмо будет проверено повторно.
|
||||
|
||||
Проверка клиента модели без сети (Node.js 22.6+): `npm run test:agent`.
|
||||
|
||||
В настройках ИИ-агента отображается накопленный расход входных и выходных токенов
|
||||
и общий итог по всем моделям. Статистика берётся из поля `usage` ответа сервера,
|
||||
обновляется каждые пять секунд и сохраняется между запусками. Учёт начинается с
|
||||
добавления счётчика; прежний расход восстановить нельзя. Ответы без корректного
|
||||
`usage` отмечаются отдельно, их расход не оценивается. При HTTP-ошибке или обрыве
|
||||
соединения расход неизвестен. Если ответ получен со статистикой, токены учитываются
|
||||
даже при некорректном решении модели.
|
||||
|
||||
Кнопка «Загрузить модели» рядом с названием модели запрашивает `GET <URL API>/models`
|
||||
и предлагает выбрать имя из `data[].id`. Используются текущий URL и введённый ключ,
|
||||
а при пустом поле ключа — сохранённый ключ. Загрузка списка не сохраняет настройки;
|
||||
после выбора нажмите «Сохранить настройки ИИ». Ручной ввод имени также доступен.
|
||||
|
|
|
|||
|
|
@ -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<AgentStoreSchema>({
|
||||
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 => {
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<AgentDecision> {
|
||||
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<string> {
|
||||
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<AgentDecision> {
|
||||
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<AgentDecision> {
|
||||
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<string[]> {
|
||||
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<string>(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 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<AgentSettings, 'hasApiKey'>
|
||||
processed: Record<string, true>
|
||||
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<typeof setInterval> | 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<string[]> {
|
||||
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<AgentSettings> {
|
||||
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<AgentDecision> {
|
||||
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 })
|
||||
|
|
|
|||
16
src/main/services/mail-agent-usage.ts
Normal file
16
src/main/services/mail-agent-usage.ts
Normal file
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,69 @@
|
|||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'
|
||||
import CustomSelect from './CustomSelect.vue'
|
||||
import Switch from './Switch.vue'
|
||||
import type { AgentSettings } from '@shared/types/agent'
|
||||
import AppIcon from './AppIcon.vue'
|
||||
import type { AgentSettings, AgentUsageStatistics, AgentErrorDetails } from '@shared/types/agent'
|
||||
|
||||
const settings = ref<AgentSettings | null>(null)
|
||||
const apiKey = ref<string>('')
|
||||
const saving = ref<boolean>(false)
|
||||
const status = ref<string>('')
|
||||
const usage = ref<AgentUsageStatistics | null>(null)
|
||||
const usageError = ref<string>('')
|
||||
const lastError = ref<AgentErrorDetails | null>(null)
|
||||
const models = ref<string[]>([])
|
||||
const loadingModels = ref<boolean>(false)
|
||||
const modelsStatus = ref<string>('')
|
||||
const modelOptions = computed<{ value: string; label: string }[]>(() => models.value.map((model: string) => ({ value: model, label: model })))
|
||||
watch([() => settings.value?.url, apiKey], (): void => {
|
||||
models.value = []
|
||||
modelsStatus.value = ''
|
||||
})
|
||||
|
||||
async function loadModels(): Promise<void> {
|
||||
if (!settings.value) return
|
||||
const url: string = settings.value.url
|
||||
const key: string = apiKey.value
|
||||
loadingModels.value = true
|
||||
modelsStatus.value = ''
|
||||
try {
|
||||
const result: string[] = await window.api.invoke('agent:models:list', { url, apiKey: key || null })
|
||||
if (settings.value.url !== url || apiKey.value !== key) return
|
||||
models.value = result
|
||||
modelsStatus.value = result.length ? `Загружено моделей: ${result.length}` : 'Сервер вернул пустой список моделей'
|
||||
} catch (error: unknown) {
|
||||
modelsStatus.value = error instanceof Error ? error.message : String(error)
|
||||
} finally {
|
||||
loadingModels.value = false
|
||||
}
|
||||
}
|
||||
|
||||
let usageTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
async function refreshUsage(): Promise<void> {
|
||||
try {
|
||||
const [statistics, error] = await Promise.all([
|
||||
window.api.invoke('agent:usage:get'),
|
||||
window.api.invoke('agent:error:get')
|
||||
])
|
||||
usage.value = statistics
|
||||
lastError.value = error
|
||||
usageError.value = ''
|
||||
} catch (error: unknown) {
|
||||
usageError.value = error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
|
||||
onUnmounted((): void => {
|
||||
if (usageTimer !== null) clearInterval(usageTimer)
|
||||
})
|
||||
|
||||
onMounted(async (): Promise<void> => {
|
||||
usageTimer = setInterval((): void => { void refreshUsage() }, 5_000)
|
||||
try {
|
||||
settings.value = await window.api.invoke('agent:settings:get')
|
||||
await refreshUsage()
|
||||
} catch (error: unknown) {
|
||||
status.value = error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
|
@ -62,42 +115,81 @@ async function removeApiKey(): Promise<void> {
|
|||
</script>
|
||||
|
||||
<template>
|
||||
<section class="agent-settings">
|
||||
<h3>ИИ-агент</h3>
|
||||
<template v-if="settings">
|
||||
<label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label>
|
||||
<p>Анализирует текст всех писем во всех папках, включая старые письма при первом запуске. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
|
||||
<p>При включении обычные уведомления заменяются решениями ИИ. Если модель недоступна, включаются обычные уведомления. После успешного ответа модели ИИ-отбор возобновляется.</p>
|
||||
<label class="agent-toggle">Уведомлять о важных письмах в заглушённых папках <Switch v-model="settings.notifyMutedFolders" /></label>
|
||||
<small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Обычные уведомления эту настройку не используют.</small>
|
||||
<label>URL API локальной модели
|
||||
<input v-model="settings.url" type="url" placeholder="http://localhost:11434/v1" />
|
||||
</label>
|
||||
<small>OpenAI-совместимый API. Укажите базовый URL с /v1; приложение добавит /chat/completions.</small>
|
||||
<label>Название модели
|
||||
<input v-model="settings.model" type="text" placeholder="Название модели на сервере" />
|
||||
</label>
|
||||
<label>API-ключ
|
||||
<input v-model="apiKey" type="password" autocomplete="new-password" :placeholder="settings.hasApiKey ? 'Ключ сохранён; оставьте пустым, чтобы сохранить' : 'Необязательно для локального сервера'" />
|
||||
</label>
|
||||
<div v-if="settings.hasApiKey" class="agent-key-actions">
|
||||
<span>API-ключ сохранён</span>
|
||||
<button class="action-btn danger" type="button" :disabled="saving" @click="removeApiKey">Удалить ключ</button>
|
||||
<details class="agent-settings">
|
||||
<summary class="agent-summary">
|
||||
<span>ИИ-агент</span>
|
||||
<AppIcon name="chevron-right" :size="16" class="agent-chevron" />
|
||||
</summary>
|
||||
<div class="agent-content">
|
||||
<div v-if="lastError" class="agent-error" role="alert">
|
||||
<strong>Последняя ошибка ИИ-агента</strong>
|
||||
<small>{{ new Date(lastError.occurredAt).toLocaleString('ru-RU') }}</small>
|
||||
<pre>{{ lastError.message }}</pre>
|
||||
<small>Ошибка исчезнет после успешного ответа модели. Проверка повторяется автоматически.</small>
|
||||
</div>
|
||||
<button class="action-btn accent-btn agent-save" type="button" :disabled="saving" @click="save">{{ saving ? 'Сохранение…' : 'Сохранить настройки ИИ' }}</button>
|
||||
</template>
|
||||
<p v-if="status" role="status">{{ status }}</p>
|
||||
</section>
|
||||
<template v-if="settings">
|
||||
<label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label>
|
||||
<p>Анализирует текст всех писем во всех папках, включая старые письма при первом запуске. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
|
||||
<p>При включении обычные уведомления заменяются решениями ИИ. Если модель недоступна, включаются обычные уведомления. После успешного ответа модели ИИ-отбор возобновляется.</p>
|
||||
<label class="agent-toggle">Уведомлять о важных письмах в заглушённых папках <Switch v-model="settings.notifyMutedFolders" /></label>
|
||||
<small>Если ИИ сочтёт письмо важным, уведомление придёт даже при отключённых уведомлениях для папки. Обычные уведомления эту настройку не используют.</small>
|
||||
<div v-if="usage" class="agent-usage" aria-live="polite">
|
||||
<span>Всего токенов: <strong>{{ usage.totalTokens.toLocaleString('ru-RU') }}</strong></span>
|
||||
<span>Входные: {{ usage.inputTokens.toLocaleString('ru-RU') }} · Выходные: {{ usage.outputTokens.toLocaleString('ru-RU') }}</span>
|
||||
<small>Ответов со статистикой: {{ usage.measuredResponses.toLocaleString('ru-RU') }}. Счётчик сохраняется между запусками и суммирует расход всех моделей с момента добавления учёта.</small>
|
||||
<small v-if="usage.unmeasuredResponses">Сервер не передал корректную статистику для {{ usage.unmeasuredResponses.toLocaleString('ru-RU') }} ответов — их расход неизвестен и не включён в итог.</small>
|
||||
</div>
|
||||
<p v-if="usageError" role="status">Не удалось обновить расход токенов: {{ usageError }}</p>
|
||||
<label>URL API локальной модели
|
||||
<input v-model="settings.url" type="url" placeholder="http://localhost:11434/v1" />
|
||||
</label>
|
||||
<small>OpenAI-совместимый API. Укажите базовый URL с /v1; приложение добавит /chat/completions.</small>
|
||||
<div class="agent-model-field">
|
||||
<label for="agent-model">Название модели</label>
|
||||
<div class="agent-model-row">
|
||||
<input id="agent-model" v-model="settings.model" type="text" placeholder="Название модели на сервере" />
|
||||
<button class="action-btn" type="button" :disabled="loadingModels || saving || !settings.url.trim()" @click="loadModels">{{ loadingModels ? 'Загрузка…' : 'Загрузить модели' }}</button>
|
||||
</div>
|
||||
<CustomSelect v-if="models.length" v-model="settings.model" :options="modelOptions" />
|
||||
<p v-if="modelsStatus" class="agent-model-status" role="status">{{ modelsStatus }}</p>
|
||||
</div>
|
||||
<label>API-ключ
|
||||
<input v-model="apiKey" type="password" autocomplete="new-password" :placeholder="settings.hasApiKey ? 'Ключ сохранён; оставьте пустым, чтобы сохранить' : 'Необязательно для локального сервера'" />
|
||||
</label>
|
||||
<div v-if="settings.hasApiKey" class="agent-key-actions">
|
||||
<span>API-ключ сохранён</span>
|
||||
<button class="action-btn danger" type="button" :disabled="saving" @click="removeApiKey">Удалить ключ</button>
|
||||
</div>
|
||||
<button class="action-btn accent-btn agent-save" type="button" :disabled="saving" @click="save">{{ saving ? 'Сохранение…' : 'Сохранить настройки ИИ' }}</button>
|
||||
</template>
|
||||
<p v-if="status" role="status">{{ status }}</p>
|
||||
</div>
|
||||
</details>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.agent-settings { padding: 20px; border: 1px solid var(--border-color, #5555); border-radius: 12px; display: flex; flex-direction: column; gap: 12px; }
|
||||
h3, p { margin: 0; }
|
||||
.agent-settings { padding: 20px; border: 1px solid var(--border-color, #5555); border-radius: 12px; }
|
||||
.agent-summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; cursor: pointer; list-style: none; font-size: 14px; font-weight: 600; }
|
||||
.agent-summary::-webkit-details-marker { display: none; }
|
||||
.agent-summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; }
|
||||
.agent-chevron { transition: transform 150ms ease; }
|
||||
.agent-settings[open] .agent-chevron { transform: rotate(90deg); }
|
||||
.agent-content { display: flex; flex-direction: column; gap: 12px; padding-top: 16px; }
|
||||
p { margin: 0; }
|
||||
p, small { color: var(--text-secondary); font-size: 12px; line-height: 1.5; }
|
||||
label { display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
|
||||
.agent-toggle { flex-direction: row; align-items: center; justify-content: space-between; }
|
||||
input { background: var(--bg-input, transparent); color: var(--text-primary); border: 1px solid var(--border-color, #8886); border-radius: 6px; padding: 9px; }
|
||||
.agent-model-field { display: flex; flex-direction: column; gap: 8px; }
|
||||
.agent-model-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.agent-model-row input { flex: 1; min-width: 180px; }
|
||||
.agent-model-row button { flex-shrink: 0; }
|
||||
.agent-model-status { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.agent-key-actions { display: flex; align-items: center; gap: 12px; font-size: 12px; color: var(--text-secondary); }
|
||||
.agent-error { display: flex; flex-direction: column; gap: 8px; padding: 12px; border: 1px solid var(--danger, #f87171); border-radius: 8px; font-size: 13px; }
|
||||
.agent-error strong { color: var(--danger, #f87171); }
|
||||
.agent-error pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; user-select: text; }
|
||||
.agent-usage { display: flex; flex-direction: column; gap: 6px; padding: 12px; border: 1px solid var(--border-color, #5555); border-radius: 8px; font-size: 13px; }
|
||||
.agent-save { align-self: flex-start; }
|
||||
.action-btn { cursor: pointer; }
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -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: '' })
|
||||
}))
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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(() => {
|
|||
<div class="toast-body">
|
||||
<div class="toast-from">{{ from }}</div>
|
||||
<div class="toast-subject">{{ subject }}</div>
|
||||
<pre v-if="details" class="toast-details">{{ details }}</pre>
|
||||
<div class="toast-account">{{ accountEmail }}</div>
|
||||
</div>
|
||||
<button class="toast-close" @click.stop="onClose(id)">
|
||||
|
|
@ -121,6 +123,8 @@ onMounted(() => {
|
|||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.toast-details { margin: 4px 0; max-height: 180px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: 12px; color: inherit; user-select: text; }
|
||||
|
||||
.toast-account {
|
||||
font-size: 10.5px;
|
||||
color: var(--text-muted);
|
||||
|
|
|
|||
|
|
@ -67,8 +67,6 @@ function folderDisplayName(path: string): string {
|
|||
<div class="settings-view">
|
||||
<div class="settings-panel">
|
||||
|
||||
<AgentSettings />
|
||||
|
||||
<!-- Шапка панели — как заголовок письма -->
|
||||
<div class="panel-header">
|
||||
<button class="back-btn" @click="router.push('/')">
|
||||
|
|
@ -80,6 +78,7 @@ function folderDisplayName(path: string): string {
|
|||
|
||||
<!-- Секции в стиле header-details -->
|
||||
<div class="sections">
|
||||
<AgentSettings />
|
||||
|
||||
<!-- Аккаунты -->
|
||||
<div class="section">
|
||||
|
|
|
|||
|
|
@ -18,3 +18,24 @@ export interface AgentDecision {
|
|||
notify: boolean
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface AgentTokenUsage {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
totalTokens: number
|
||||
}
|
||||
|
||||
export interface AgentUsageStatistics extends AgentTokenUsage {
|
||||
measuredResponses: number
|
||||
unmeasuredResponses: number
|
||||
}
|
||||
|
||||
export interface AgentErrorDetails {
|
||||
message: string
|
||||
occurredAt: string
|
||||
}
|
||||
|
||||
export interface AgentModelsRequest {
|
||||
url: string
|
||||
apiKey: string | null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { AgentSettings, AgentSettingsUpdate } from './agent'
|
||||
import type { AgentSettings, AgentSettingsUpdate, AgentUsageStatistics, AgentErrorDetails, AgentModelsRequest } from './agent'
|
||||
import type { AccountConfig } from './account'
|
||||
import type { FolderListResult, MessageListResult } from './provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, ComposeSession } from './message'
|
||||
|
|
@ -6,6 +6,9 @@ import type { CalendarInfo, CalendarEvent, MeetingReminder, MeetingReminderSetti
|
|||
import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
|
||||
|
||||
export interface IpcChannelMap {
|
||||
'agent:models:list': [AgentModelsRequest, string[]]
|
||||
'agent:error:get': [void, AgentErrorDetails | null]
|
||||
'agent:usage:get': [void, AgentUsageStatistics]
|
||||
'agent:settings:get': [void, AgentSettings]
|
||||
'agent:settings:save': [AgentSettingsUpdate, AgentSettings]
|
||||
'accounts:list': [void, AccountConfig[]]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { analyzeMail, parseAgentDecision, AgentResponseError } from '../src/main/services/mail-agent-client.ts'
|
||||
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 = {
|
||||
|
|
@ -42,15 +42,107 @@ test('передаёт текст, адрес пользователя и клю
|
|||
assert.match(payload.messages[1].content, /Ответьте до завтра/)
|
||||
return Response.json({ choices: [{ message: { content: '{"notify":true,"reason":"Нужен ответ"}' } }] })
|
||||
}
|
||||
assert.deepEqual(await analyzeMail(request, send), { 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), /HTTP 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), AgentResponseError)
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
40
tests/mail-agent-usage.test.ts
Normal file
40
tests/mail-agent-usage.test.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { parseTokenUsage } from '../src/main/services/mail-agent-client.ts'
|
||||
import { addTokenUsage, createUsageStatistics } from '../src/main/services/mail-agent-usage.ts'
|
||||
import type { AgentUsageStatistics } from '../src/shared/types/agent.ts'
|
||||
|
||||
test('читает расход из ответа модели', (): void => {
|
||||
assert.deepEqual(parseTokenUsage({ usage: { prompt_tokens: 100, completion_tokens: 20, total_tokens: 120 } }), {
|
||||
inputTokens: 100, outputTokens: 20, totalTokens: 120
|
||||
})
|
||||
})
|
||||
|
||||
test('вычисляет сумму, если сервер не прислал итог', (): void => {
|
||||
assert.deepEqual(parseTokenUsage({ usage: { prompt_tokens: 100, completion_tokens: 20 } }), {
|
||||
inputTokens: 100, outputTokens: 20, totalTokens: 120
|
||||
})
|
||||
})
|
||||
|
||||
test('не подменяет отсутствующий или неверный расход нулём', (): void => {
|
||||
for (const response of [null, {}, { usage: null }, { usage: {} },
|
||||
{ usage: { prompt_tokens: -1, completion_tokens: 2 } },
|
||||
{ usage: { prompt_tokens: '10', completion_tokens: 2 } },
|
||||
{ usage: { prompt_tokens: 1.5, completion_tokens: 2 } }]) {
|
||||
assert.equal(parseTokenUsage(response), null)
|
||||
}
|
||||
})
|
||||
|
||||
test('суммирует измеренный расход без изменения исходных данных', (): void => {
|
||||
const original: AgentUsageStatistics = createUsageStatistics()
|
||||
const first: AgentUsageStatistics = addTokenUsage(original, { inputTokens: 100, outputTokens: 20, totalTokens: 120 })
|
||||
const result: AgentUsageStatistics = addTokenUsage(first, { inputTokens: 50, outputTokens: 10, totalTokens: 60 })
|
||||
assert.deepEqual(result, { inputTokens: 150, outputTokens: 30, totalTokens: 180, measuredResponses: 2, unmeasuredResponses: 0 })
|
||||
assert.deepEqual(original, { inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 0 })
|
||||
})
|
||||
|
||||
test('отдельно учитывает ответы без статистики', (): void => {
|
||||
assert.deepEqual(addTokenUsage(createUsageStatistics(), null), {
|
||||
inputTokens: 0, outputTokens: 0, totalTokens: 0, measuredResponses: 0, unmeasuredResponses: 1
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue