Добавлены резервные уведомления и обход заглушённых папок для ИИ

This commit is contained in:
r.rasputin 2026-11-16 17:51:36 +07:00
parent dac9ba4f95
commit a9609515df
11 changed files with 150 additions and 20 deletions

View file

@ -128,8 +128,12 @@ OpenAI-совместимого API локальной модели (напри
При личном обращении или важном содержимом показываются системное уведомление
и уведомление внутри приложения с причиной решения. Настройки отключения
уведомлений для папок сохраняют действие. При включённом агенте обычные
уведомления заменяются решениями модели. Обработанные письма запоминаются между
уведомлений для папок сохраняют действие. Настройка «Уведомлять о важных письмах
в заглушённых папках» позволяет уведомлениям ИИ обходить это ограничение; по умолчанию
она выключена и не влияет на обычные уведомления при недоступной модели. При включённом агенте обычные
уведомления заменяются решениями модели. При ошибке запроса к модели включаются
обычные уведомления, включая письма, ожидавшие анализа. Проверка модели повторяется
раз в минуту; после успешного ответа отбор ИИ возобновляется без повторных уведомлений. Обработанные письма запоминаются между
запусками и повторно не анализируются, в том числе после изменения модели.
Ошибки показываются в приложении; необработанное письмо будет проверено повторно.

View file

@ -16,7 +16,7 @@
"build:linux": "npm run build && electron-builder --linux",
"build:win": "npm run build && electron-builder --win",
"build:mac": "npm run build && electron-builder --mac",
"test:agent": "node --experimental-strip-types tests/mail-agent-client.test.ts",
"test:agent": "node --experimental-strip-types --test tests/mail-agent*.test.ts",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web"

View file

@ -31,7 +31,7 @@ let mainWindowRef: BrowserWindow | null = null
const mailAgent = new MailAgentService(accountManager,
new Store<AgentStoreSchema>({
name: 'mail-agent',
defaults: { settings: { enabled: false, url: 'http://localhost:11434/v1', model: '' }, processed: {} }
defaults: { settings: { enabled: false, notifyMutedFolders: false, url: 'http://localhost:11434/v1', model: '' }, processed: {} }
}),
new CredentialStore('agent-credentials.json'),
(event): void => {
@ -41,7 +41,7 @@ const mailAgent = new MailAgentService(accountManager,
if (mainWindowRef && !mainWindowRef.isDestroyed()) mainWindowRef.webContents.send('agent:error', { message })
}
)
accountManager.setAgentEnabledProvider((): boolean => mailAgent.getSettings().enabled)
accountManager.setMailNotificationFilter((event): boolean => mailAgent.filterNotification(event))
app.on('before-quit', (): void => mailAgent.stop())
/** «Открыть» в напоминании: выводим главное окно и показываем событие в календаре. */

View file

@ -1,3 +1,4 @@
import type { IncomingMail } from './mail-agent-notifications'
import { BrowserWindow, powerMonitor } from 'electron'
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
import { AccountType } from '@shared/types/account'
@ -25,7 +26,7 @@ export class AccountManager {
private store: Store<AccountStoreSchema>
private credentialStore: CredentialStore
private mainWindow: BrowserWindow | null = null
private isAgentEnabled: () => boolean = (): boolean => false
private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false
// Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис
private reconnecting = new Map<string, Promise<void>>()
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
@ -42,8 +43,8 @@ export class AccountManager {
})
}
setAgentEnabledProvider(provider: () => boolean): void {
this.isAgentEnabled = provider
setMailNotificationFilter(provider: (event: IncomingMail) => boolean): void {
this.filterMailNotification = provider
}
setMainWindow(win: BrowserWindow): void {
@ -484,7 +485,7 @@ export class AccountManager {
private setupNewMailListener(accountId: string, provider: IEmailProvider): void {
provider.onNewMail((folderId, envelope) => {
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope, agentEnabled: this.isAgentEnabled() })
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope, agentEnabled: this.filterMailNotification({ accountId, folderId, envelope }) })
}
})
provider.onClose(() => {

View file

@ -0,0 +1,43 @@
import { createHash } from 'node:crypto'
import type { IpcEventMap } from '@shared/types/ipc'
export type AgentNotification = IpcEventMap['agent:notification']
export type IncomingMail = Pick<AgentNotification, 'accountId' | 'folderId' | 'envelope'>
export function getMailKey(event: IncomingMail): string {
const { accountId, folderId, envelope } = event
return createHash('sha256').update(JSON.stringify([
accountId, envelope.messageId || [folderId, envelope.id, envelope.date, envelope.subject]
])).digest('hex')
}
export class MailAgentNotifications {
private available: boolean = true
private readonly pending: Map<string, IncomingMail> = new Map<string, IncomingMail>()
private readonly fallbackNotified: Set<string> = new Set<string>()
filter(event: IncomingMail): boolean {
const key: string = getMailKey(event)
if (!this.available) {
this.fallbackNotified.add(key)
return false
}
this.pending.set(key, event)
return true
}
complete(event: IncomingMail): boolean {
this.available = true
const key: string = getMailKey(event)
this.pending.delete(key)
return !this.fallbackNotified.delete(key)
}
fail(): IncomingMail[] {
this.available = false
const events: IncomingMail[] = [...this.pending.values()]
for (const event of events) this.fallbackNotified.add(getMailKey(event))
this.pending.clear()
return events
}
}

View file

@ -1,10 +1,13 @@
import type Store from 'electron-store'
import { createHash } from 'node:crypto'
import { getMailKey, MailAgentNotifications } from './mail-agent-notifications'
import type { IncomingMail } from './mail-agent-notifications'
import type { AgentSettings, AgentSettingsUpdate } 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 { ewsBodyToMarkdown } from '../lib/html-to-markdown'
@ -21,6 +24,7 @@ export class MailAgentService {
private timer: ReturnType<typeof setInterval> | null = null
private running: boolean = false
private revision: number = 0
private readonly notifications: MailAgentNotifications = new MailAgentNotifications()
constructor(
private readonly manager: AccountManager,
@ -30,6 +34,10 @@ export class MailAgentService {
private readonly reportError: (message: string) => void
) {}
filterNotification(event: IncomingMail): boolean {
return this.getSettings().enabled && this.notifications.filter(event)
}
async initialize(): Promise<void> {
await this.credentials.load()
this.timer = setInterval((): void => { void this.scan() }, 60_000)
@ -43,11 +51,12 @@ export class MailAgentService {
}
getSettings(): AgentSettings {
return { ...this.store.get('settings'), hasApiKey: Boolean(this.credentials.get('mail-agent-api-key')) }
return { ...this.store.get('settings'), notifyMutedFolders: this.store.get('settings').notifyMutedFolders ?? false, hasApiKey: Boolean(this.credentials.get('mail-agent-api-key')) }
}
async saveSettings(update: AgentSettingsUpdate): Promise<AgentSettings> {
if (typeof update !== 'object' || update === null || typeof update.enabled !== 'boolean' ||
typeof update.notifyMutedFolders !== 'boolean' ||
typeof update.url !== 'string' || typeof update.model !== 'string' ||
(update.apiKey !== null && typeof update.apiKey !== 'string')) {
throw new AgentSettingsError('Некорректные настройки ИИ-агента')
@ -59,7 +68,7 @@ export class MailAgentService {
}
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, url: url.toString().replace(/\/+$/, ''), model: update.model.trim() })
this.store.set('settings', { enabled: update.enabled, notifyMutedFolders: update.notifyMutedFolders, url: url.toString().replace(/\/+$/, ''), model: update.model.trim() })
this.revision++
void this.scan()
return this.getSettings()
@ -85,6 +94,17 @@ export class MailAgentService {
}
}
private async analyze(request: AgentRequest, revision: number): Promise<AgentDecision> {
try {
return await analyzeMail(request, fetch)
} catch (error: unknown) {
if (revision === this.revision) {
for (const event of this.notifications.fail()) this.publish({ ...event, reason: '', allowMuted: false })
}
throw error
}
}
private async scanFolders(accountId: string, email: string, name: string, folders: Folder[], revision: number): Promise<void> {
for (const folder of folders) {
if (folder.totalCount === 0) {
@ -97,19 +117,21 @@ export class MailAgentService {
const page = await this.manager.listMessages(accountId, folder.id, offset, 50, false)
for (const envelope of page.messages) {
if (revision !== this.revision || !this.getSettings().enabled) return
const key: string = createHash('sha256').update(JSON.stringify([accountId, envelope.messageId || [folder.id, envelope.id, envelope.date, envelope.subject]])).digest('hex')
const event: IncomingMail = { accountId, folderId: folder.id, envelope }
const key: string = getMailKey(event)
if (this.store.get('processed')[key]) continue
const body = await this.manager.fetchMessageBody(accountId, folder.id, envelope.id)
const settings: AgentSettings = this.getSettings()
if (revision !== this.revision || !settings.enabled) return
const decision = await analyzeMail({
const decision = await this.analyze({
url: settings.url, model: settings.model,
apiKey: this.credentials.get('mail-agent-api-key') ?? '',
email, name, envelope,
text: body.text ?? ewsBodyToMarkdown(body.html ?? '', 'html')
}, fetch)
}, revision)
if (revision !== this.revision || !this.getSettings().enabled) return
if (decision.notify) this.publish({ accountId, folderId: folder.id, envelope, reason: decision.reason })
const shouldNotify: boolean = this.notifications.complete(event)
if (decision.notify && shouldNotify) this.publish({ accountId, folderId: folder.id, envelope, reason: decision.reason, allowMuted: settings.notifyMutedFolders })
this.store.set('processed', { ...this.store.get('processed'), [key]: true })
}
offset += page.messages.length

View file

@ -23,6 +23,7 @@ async function save(): Promise<void> {
try {
settings.value = await window.api.invoke('agent:settings:save', {
enabled: settings.value.enabled,
notifyMutedFolders: settings.value.notifyMutedFolders,
url: settings.value.url,
model: settings.value.model,
apiKey: apiKey.value || null
@ -43,6 +44,7 @@ async function removeApiKey(): Promise<void> {
const saved: AgentSettings = await window.api.invoke('agent:settings:get')
const updated: AgentSettings = await window.api.invoke('agent:settings:save', {
enabled: saved.enabled,
notifyMutedFolders: saved.notifyMutedFolders,
url: saved.url,
model: saved.model,
apiKey: ''
@ -65,7 +67,9 @@ async function removeApiKey(): Promise<void> {
<template v-if="settings">
<label class="agent-toggle">Использовать ИИ-агента <Switch v-model="settings.enabled" /></label>
<p>Анализирует текст всех писем во всех папках, включая старые письма при первом запуске. Уведомляет о личных обращениях и важных письмах. Обработанные письма повторно не анализируются. Вложения не анализируются; длинный текст ограничен 60 000 символами.</p>
<p>При включении обычные уведомления заменяются решениями ИИ. При ошибке анализ продолжится во время следующей проверки.</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>

View file

@ -63,10 +63,11 @@ function showOsNotification(from: string, subject: string, onClick: () => void):
}
}
function notify({ accountId, folderId, envelope }: IpcEventMap['mail:new'] | IpcEventMap['agent:notification'], reason: string): void {
function notify(event: IpcEventMap['mail:new'] | IpcEventMap['agent:notification'], reason: string): void {
const { accountId, folderId, envelope } = event
const account = accountsStore.accounts.find(a => a.id === accountId)
if (!account) return
if (notificationsStore.isMuted(accountId, folderId)) return
if (!(('allowMuted' in event) && event.allowMuted) && notificationsStore.isMuted(accountId, folderId)) return
const from = envelope.from.name || envelope.from.email || 'Новое письмо'
const subject = (envelope.subject || '(без темы)') + (reason ? ` — ${reason}` : '')

View file

@ -1,5 +1,6 @@
export interface AgentSettings {
enabled: boolean
notifyMutedFolders: boolean
url: string
model: string
hasApiKey: boolean
@ -7,6 +8,7 @@ export interface AgentSettings {
export interface AgentSettingsUpdate {
enabled: boolean
notifyMutedFolders: boolean
url: string
model: string
apiKey: string | null

View file

@ -89,7 +89,7 @@ export interface IpcChannelMap {
export interface IpcEventMap {
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope; agentEnabled: boolean }
'agent:notification': { accountId: string; folderId: string; envelope: MessageEnvelope; reason: string }
'agent:notification': { accountId: string; folderId: string; envelope: MessageEnvelope; reason: string; allowMuted: boolean }
'agent:error': { message: string }
'account:status': { accountId: string; connected: boolean; error?: string }
'attachment:progress': { attachmentId: string; stage: 'downloading' | 'saving' | 'done' | 'error'; progress: number; error?: string }

View file

@ -0,0 +1,53 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { MailAgentNotifications } from '../src/main/services/mail-agent-notifications.ts'
import type { IncomingMail } from '../src/main/services/mail-agent-notifications.ts'
function createMail(id: string): IncomingMail {
return {
accountId: 'account', folderId: 'INBOX',
envelope: {
id, folderId: 'INBOX', subject: 'Вопрос', date: '2026-11-16',
from: { name: 'Коллега', email: 'other@example.org' }, to: [], cc: [],
flags: { seen: false, flagged: false, answered: false, deleted: false },
hasAttachments: false, snippet: ''
}
}
}
test('при доступной модели письмо ожидает решения ИИ', (): void => {
const notifications: MailAgentNotifications = new MailAgentNotifications()
const mail: IncomingMail = createMail('1')
assert.equal(notifications.filter(mail), true)
assert.equal(notifications.complete(mail), true)
assert.deepEqual(notifications.fail(), [])
})
test('при ошибке возвращает все ожидавшие письма для обычных уведомлений', (): void => {
const notifications: MailAgentNotifications = new MailAgentNotifications()
const first: IncomingMail = createMail('1')
const second: IncomingMail = createMail('2')
notifications.filter(first)
notifications.filter(second)
assert.deepEqual(notifications.fail(), [first, second])
assert.deepEqual(notifications.fail(), [])
assert.equal(notifications.filter(createMail('3')), false)
})
test('после восстановления исключает повтор уже показанного уведомления', (): void => {
const notifications: MailAgentNotifications = new MailAgentNotifications()
const first: IncomingMail = createMail('1')
notifications.filter(first)
notifications.fail()
const second: IncomingMail = createMail('2')
assert.equal(notifications.filter(second), false)
assert.equal(notifications.complete(first), false)
assert.equal(notifications.filter(createMail('3')), true)
assert.equal(notifications.complete(second), false)
})
test('ошибка модели не создаёт уведомлений об архивных письмах', (): void => {
const notifications: MailAgentNotifications = new MailAgentNotifications()
assert.deepEqual(notifications.fail(), [])
assert.equal(notifications.complete(createMail('old')), true)
})