From a2105f3c8104dd3e2146f657564606639dfd1326 Mon Sep 17 00:00:00 2001 From: "r.rasputin" Date: Tue, 17 Nov 2026 17:43:08 +0700 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=B7=D0=B0=D0=B3=D0=BB=D1=83=D1=88=D1=91=D0=BD?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D0=BF=D0=B0=D0=BF=D0=BA=D0=B8=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D0=B0=D0=BD=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=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 | 5 ++ src/main/ipc/agent.handler.ts | 1 + src/main/services/mail-agent-service.ts | 40 +++++++++++-- src/renderer/src/components/AgentSettings.vue | 4 +- .../src/stores/notifications.store.ts | 9 +++ src/shared/types/ipc.ts | 1 + tests/mail-agent-realtime.test.ts | 57 ++++++++++++++++++- 7 files changed, 109 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3637650..a9e0de1 100644 --- a/README.md +++ b/README.md @@ -279,3 +279,8 @@ id; неполная или некорректная порция будет п в этом случае идут по минутному таймеру, а не на каждое новое событие. Проверка наблюдателя и фильтра повторов: `npm run test:realtime`. + +Если «Уведомлять о важных письмах в заглушённых папках» выключено, агент +не загружает письма для анализа в заглушённых папках и их подпапках. +Учитываются бессрочные и временные заглушки. Служебные статусы папок +по-прежнему запрашиваются для счётчиков и UID; обычная синхронизация почты продолжается. diff --git a/src/main/ipc/agent.handler.ts b/src/main/ipc/agent.handler.ts index d785798..4c3e907 100644 --- a/src/main/ipc/agent.handler.ts +++ b/src/main/ipc/agent.handler.ts @@ -2,6 +2,7 @@ import { registerHandler } from './registry' import type { MailAgentService } from '../services/mail-agent-service' export function registerAgentHandlers(agent: MailAgentService): void { + registerHandler('agent:muted-folders:set', async (folders) => agent.setMutedFolders(folders)) registerHandler('agent:reply', async (request) => agent.prepareReply(request)) registerHandler('agent:status:get', async () => agent.getStatus()) registerHandler('agent:progress:get', async () => agent.getProgress()) diff --git a/src/main/services/mail-agent-service.ts b/src/main/services/mail-agent-service.ts index 3faec56..31db519 100644 --- a/src/main/services/mail-agent-service.ts +++ b/src/main/services/mail-agent-service.ts @@ -28,6 +28,7 @@ import { ewsBodyToMarkdown } from '../lib/html-to-markdown' export interface AgentStoreSchema { settings: Omit processed: ProcessedMail + mutedFolders?: Record history?: AgentHistoryState checkpoints?: Record usage: AgentUsageStatistics @@ -79,6 +80,7 @@ function snapshotSignature(folders: Folder[]): string { type AgentEvent = IpcEventMap['agent:notification'] export class MailAgentService { + private readonly knownFolders: Map = new Map() private readonly queuedFolders: Map = new Map() private eventTimer: ReturnType | null = null private drainingEvents: boolean = false @@ -103,8 +105,31 @@ export class MailAgentService { private readonly history: AgentHistoryRepository ) {} + setMutedFolders(folders: Record): void { + if (!folders || typeof folders !== 'object' || Array.isArray(folders) || Object.values(folders).some((expiry) => expiry !== null && (typeof expiry !== 'number' || !Number.isFinite(expiry)))) { + throw new AgentSettingsError('Некорректные настройки заглушённых папок') + } + this.store.set('mutedFolders', { ...folders }) + this.notifications.discardMatching((event): boolean => !this.shouldAnalyzeFolder(event.accountId, event.folderId)) + } + + private shouldAnalyzeFolder(accountId: string, folderId: string): boolean { + if (this.getSettings().notifyMutedFolders) return true + const muted: Record = this.store.get('mutedFolders') ?? {} + const folders: Folder[] = flattenFolders(this.knownFolders.get(accountId) ?? []) + const visited: Set = new Set() + let current: string | null = folderId + while (current !== null && !visited.has(current)) { + visited.add(current) + const expiry: number | null | undefined = muted[`${accountId}:${current}`] + if (expiry === null || (expiry !== undefined && expiry > Date.now())) return false + current = folders.find((folder) => folder.id === current)?.parentId ?? null + } + return true + } + filterNotification(event: IncomingMail): boolean { - if (!this.getSettings().enabled) return false + if (!this.getSettings().enabled || !this.shouldAnalyzeFolder(event.accountId, event.folderId)) return false if (this.history.getDecision(getMailKey(event))) return true const baseline: FolderBaseline | undefined = this.getBaselines()[getFolderBaselineKey(event.accountId, event.folderId)] if (baseline && isExistingMessage(event.envelope.id, baseline)) return true @@ -112,7 +137,7 @@ export class MailAgentService { } enqueueNewMail(event: IncomingMail): void { - if (this.stopped || !this.getSettings().enabled || this.history.getDecision(getMailKey(event))) return + if (this.stopped || !this.getSettings().enabled || !this.shouldAnalyzeFolder(event.accountId, event.folderId) || this.history.getDecision(getMailKey(event))) return const uid: number = Number(event.envelope.id) if (!Number.isSafeInteger(uid) || uid < 1) { this.recordError(new AgentSettingsError('Некорректный UID нового письма'), 'Очередь ИИ'); return } const key: string = getFolderBaselineKey(event.accountId, event.folderId) @@ -146,6 +171,7 @@ export class MailAgentService { const target: QueuedAgentFolder | undefined = pending.find((item) => item.accountId === accountId && item.folderId === folder.id) return { ...folder, uidNext: target && folder.uidNext !== undefined ? Math.min(folder.uidNext, target.firstUid) : folder.uidNext, children: prepare(folder.children) } }) + this.knownFolders.set(accountId, folders) const previous: FolderBaselines = this.getBaselines() const next: FolderBaselines = captureFolderBaselines(accountId, prepare(folders), previous) if (next !== previous) this.store.set('baselines', next) @@ -170,6 +196,7 @@ export class MailAgentService { this.captureBaselines(accountId, result.folders, targets) const folders: Folder[] = flattenFolders(result.folders) for (const target of targets) { + if (!this.shouldAnalyzeFolder(accountId, target.folderId)) continue const folder: Folder | undefined = folders.find((item) => item.id === target.folderId) if (!folder) throw new AgentSettingsError(`Папка ${target.folderId} нового письма не найдена`) if (folder.statusError) throw new AgentSettingsError(folder.statusError) @@ -456,7 +483,9 @@ export class MailAgentService { for (const folder of folders) { if (revision !== this.revision || !this.getSettings().enabled) return this.progress = { ...this.progress, folder: folder.name, account: email } - if (folder.statusError) { + if (!this.shouldAnalyzeFolder(accountId, folder.id)) { + context.complete = false + } else if (folder.statusError) { context.complete = false this.recordError(new AgentSettingsError(folder.statusError), `Статус папки ${email} / ${folder.name}`) } else if (folder.totalCount > 0) { @@ -473,6 +502,7 @@ export class MailAgentService { let offset: number = 0 let checkpointBlocked: boolean = false while (revision === this.revision && this.getSettings().enabled) { + if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return } const settings: AgentSettings = this.getSettings() const inspectedBeforePage: number = this.progress.inspected const checkpointKey: string = getFolderBaselineKey(accountId, folder.id) @@ -491,6 +521,7 @@ export class MailAgentService { const seen: Set = new Set() const newKeys: Set = new Set() for (const envelope of page.messages) { + if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return } const event: IncomingMail = { accountId, folderId: folder.id, envelope } const key: string = getMailKey(event) context.observed.add(key) @@ -519,6 +550,7 @@ export class MailAgentService { const batches = splitIntoBatches(requests, settings.batchSize) this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length - requests.length } const tasks: (() => Promise)[] = batches.map((batch) => async (): Promise => { + if (!this.shouldAnalyzeFolder(accountId, folder.id)) { context.complete = false; return null } const decisions: AgentDecision[] | null = await this.analyzeBatch(batch.map((item) => item.request), revision) if (!decisions || revision !== this.revision) return null for (const [position, decision] of decisions.entries()) { @@ -542,7 +574,7 @@ export class MailAgentService { this.publishAnalysis({ ...event, decision }) if (decision.source === 'baseline') continue const shouldNotify: boolean = this.modelFailedInScan ? this.notifications.finish(event) : this.notifications.complete(event) - if (decision.notify && shouldNotify) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders }) + if (decision.notify && shouldNotify && this.shouldAnalyzeFolder(accountId, folder.id)) this.publish({ ...event, reason: decision.reason, allowMuted: settings.notifyMutedFolders }) } } this.progress = { ...this.progress, inspected: inspectedBeforePage + page.messages.length } diff --git a/src/renderer/src/components/AgentSettings.vue b/src/renderer/src/components/AgentSettings.vue index 9f713d0..ef1705a 100644 --- a/src/renderer/src/components/AgentSettings.vue +++ b/src/renderer/src/components/AgentSettings.vue @@ -173,10 +173,10 @@ async function removeApiKey(): Promise {