From a9609515df26e4c2c11cbd25929b022ac91ab2dd Mon Sep 17 00:00:00 2001 From: "r.rasputin" Date: Mon, 16 Nov 2026 17:51:36 +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=80=D0=B5=D0=B7=D0=B5=D1=80=D0=B2=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D1=83=D0=B2=D0=B5=D0=B4=D0=BE=D0=BC=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B8=20=D0=BE=D0=B1=D1=85=D0=BE=D0=B4=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B3=D0=BB=D1=83=D1=88=D1=91=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=BF=D0=B0=D0=BF=D0=BE=D0=BA=20=D0=B4=D0=BB=D1=8F=20=D0=98?= =?UTF-8?q?=D0=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++- package.json | 2 +- src/main/index.ts | 4 +- src/main/services/account-manager.ts | 9 ++-- src/main/services/mail-agent-notifications.ts | 43 +++++++++++++++ src/main/services/mail-agent-service.ts | 36 ++++++++++--- src/renderer/src/components/AgentSettings.vue | 6 ++- .../notifications/NotificationContainer.vue | 5 +- src/shared/types/agent.ts | 2 + src/shared/types/ipc.ts | 2 +- tests/mail-agent-notifications.test.ts | 53 +++++++++++++++++++ 11 files changed, 150 insertions(+), 20 deletions(-) create mode 100644 src/main/services/mail-agent-notifications.ts create mode 100644 tests/mail-agent-notifications.test.ts diff --git a/README.md b/README.md index 85e3aaf..5546032 100644 --- a/README.md +++ b/README.md @@ -128,8 +128,12 @@ OpenAI-совместимого API локальной модели (напри При личном обращении или важном содержимом показываются системное уведомление и уведомление внутри приложения с причиной решения. Настройки отключения -уведомлений для папок сохраняют действие. При включённом агенте обычные -уведомления заменяются решениями модели. Обработанные письма запоминаются между +уведомлений для папок сохраняют действие. Настройка «Уведомлять о важных письмах +в заглушённых папках» позволяет уведомлениям ИИ обходить это ограничение; по умолчанию +она выключена и не влияет на обычные уведомления при недоступной модели. При включённом агенте обычные +уведомления заменяются решениями модели. При ошибке запроса к модели включаются +обычные уведомления, включая письма, ожидавшие анализа. Проверка модели повторяется +раз в минуту; после успешного ответа отбор ИИ возобновляется без повторных уведомлений. Обработанные письма запоминаются между запусками и повторно не анализируются, в том числе после изменения модели. Ошибки показываются в приложении; необработанное письмо будет проверено повторно. diff --git a/package.json b/package.json index 43f076f..205b30f 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/src/main/index.ts b/src/main/index.ts index 3a262f2..251b2f2 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -31,7 +31,7 @@ let mainWindowRef: BrowserWindow | null = null const mailAgent = new MailAgentService(accountManager, new Store({ 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()) /** «Открыть» в напоминании: выводим главное окно и показываем событие в календаре. */ diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index 0354b5c..36951af 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -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 private credentialStore: CredentialStore private mainWindow: BrowserWindow | null = null - private isAgentEnabled: () => boolean = (): boolean => false + private filterMailNotification: (event: IncomingMail) => boolean = (): boolean => false // Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис private reconnecting = new Map>() private reconnectTimers = new Map>() @@ -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(() => { diff --git a/src/main/services/mail-agent-notifications.ts b/src/main/services/mail-agent-notifications.ts new file mode 100644 index 0000000..cdd81f1 --- /dev/null +++ b/src/main/services/mail-agent-notifications.ts @@ -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 + +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 = new Map() + private readonly fallbackNotified: Set = new Set() + + 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 + } +} diff --git a/src/main/services/mail-agent-service.ts b/src/main/services/mail-agent-service.ts index b821fd2..2f21872 100644 --- a/src/main/services/mail-agent-service.ts +++ b/src/main/services/mail-agent-service.ts @@ -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 | 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 { 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 { 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 { + 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 { 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 diff --git a/src/renderer/src/components/AgentSettings.vue b/src/renderer/src/components/AgentSettings.vue index 8809b34..effae6f 100644 --- a/src/renderer/src/components/AgentSettings.vue +++ b/src/renderer/src/components/AgentSettings.vue @@ -23,6 +23,7 @@ async function save(): Promise { 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 { 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 {