From 19f73efde2de8119d7bdcf9fa48b746806587106 Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 05:43:55 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=B2=D0=BE=D1=81=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=83=D0=B2?= =?UTF-8?q?=D0=B5=D0=B4=D0=BE=D0=BC=D0=BB=D0=B5=D0=BD=D0=B8=D0=B9=20?= =?UTF-8?q?=E2=80=94=20=D1=80=D0=B5=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5,=20=D0=B4=D0=B5=D0=B4?= =?UTF-8?q?=D1=83=D0=BF=D0=BB=D0=B8=D0=BA=D0=B0=D1=86=D0=B8=D1=8F,=20?= =?UTF-8?q?=D0=B2=D1=81=D0=B5=20=D0=B0=D0=BA=D0=BA=D0=B0=D1=83=D0=BD=D1=82?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - exists-событие больше не шлёт фиктивный envelope (id:'', 'Новое письмо'); вместо этого оно немедленно запускает pollSingleFolder, которая получает реальные данные сообщения — клик по тосту корректно открывает письмо - UID-дедупликация (TTL 5 мин): одно и то же письмо не даёт два тоста, даже если exists + polling сработали почти одновременно - pollFolderTree при ошибке STATUS не обнуляет сохранённый счётчик (lastUnseenCount), чтобы не потерять точку отсчёта - refresh() опрашивает все подключённые аккаунты, а не только активный — пользователи с несколькими ящиками получают уведомления по каждому Co-Authored-By: Claude Sonnet 4.6 --- src/main/providers/imap.provider.ts | 95 ++++++++++++------- .../src/components/messages/MessageList.vue | 8 +- 2 files changed, 69 insertions(+), 34 deletions(-) diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index 97a5436..9275984 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -34,6 +34,9 @@ export class ImapProvider implements IEmailProvider { private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null // folderId → last known unseen count for polling private lastUnseenCount = new Map() + // uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message + private notifiedUids = new Map() + private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes constructor(private config: AccountConfig) { const creds = config.credentials as ImapCredentials @@ -367,19 +370,9 @@ export class ImapProvider implements IEmailProvider { this.newMailCallback = callback this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => { // Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо) - if (this.newMailCallback && data.prevCount > 0 && data.count > data.prevCount) { - this.newMailCallback(data.path, { - id: '', - folderId: data.path, - subject: 'Новое сообщение', - from: { name: 'Новое письмо', email: '' }, - to: [], - cc: [], - date: new Date().toISOString(), - flags: { seen: false, flagged: false, answered: false, deleted: false }, - hasAttachments: false, - snippet: '' - }) + if (data.prevCount > 0 && data.count > data.prevCount) { + // Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения + this.pollSingleFolder(data.path).catch(() => {}) } }) } @@ -462,36 +455,55 @@ export class ImapProvider implements IEmailProvider { try { const tree = await this.client.listTree() as { folders?: ImapMailbox[] } await this.pollFolderTree(tree.folders ?? []) - } catch { /* ignore poll errors */ } + } catch (err) { + console.warn('[IMAP] pollNewMessages error:', (err as Error).message) + } + } + + // Немедленная проверка одной папки — вызывается из exists-события + private async pollSingleFolder(folderPath: string): Promise { + if (!this.newMailCallback) return + try { + await this.pollFolderTree([{ name: folderPath, path: folderPath }]) + } catch { /* ignore */ } } private async pollFolderTree(folders: ImapMailbox[]): Promise { for (const folder of folders) { try { const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null - const unseen = status?.unseen ?? 0 - const prev = this.lastUnseenCount.get(folder.path) - this.lastUnseenCount.set(folder.path, unseen) + // Если STATUS вернул null или упал — не трогаем сохранённый счётчик + if (status) { + const unseen = status.unseen ?? 0 + const prev = this.lastUnseenCount.get(folder.path) + this.lastUnseenCount.set(folder.path, unseen) - if (prev !== undefined && unseen > prev && this.newMailCallback) { - // Получаем последнее непрочитанное письмо для уведомления - const lock = await this.client.getMailboxLock(folder.path) - try { - const uids = await this.client.search({ seen: false }, { uid: true }) as number[] - if (uids?.length) { - const latestUid = Math.max(...uids).toString() - for await (const msg of this.client.fetch(latestUid, { - uid: true, envelope: true, flags: true - }, { uid: true })) { - this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) - break + if (prev !== undefined && unseen > prev && this.newMailCallback) { + // Получаем последнее непрочитанное письмо для уведомления + const lock = await this.client.getMailboxLock(folder.path) + try { + const uids = await this.client.search({ seen: false }, { uid: true }) as number[] + if (uids?.length) { + const latestUid = Math.max(...uids).toString() + const dedupKey = `${folder.path}:${latestUid}` + if (!this.isRecentlyNotified(dedupKey)) { + for await (const msg of this.client.fetch(latestUid, { + uid: true, envelope: true, flags: true + }, { uid: true })) { + this.markNotified(dedupKey) + this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) + break + } + } } + } finally { + lock.release() } - } finally { - lock.release() } } - } catch { /* некоторые папки не поддерживают STATUS */ } + } catch (err) { + console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message) + } if (folder.folders?.length) { await this.pollFolderTree(folder.folders) @@ -499,6 +511,25 @@ export class ImapProvider implements IEmailProvider { } } + private isRecentlyNotified(key: string): boolean { + const expiry = this.notifiedUids.get(key) + if (expiry === undefined) return false + if (Date.now() < expiry) return true + this.notifiedUids.delete(key) + return false + } + + private markNotified(key: string): void { + // Чистим старые записи при росте кэша + if (this.notifiedUids.size > 200) { + const now = Date.now() + for (const [k, exp] of this.notifiedUids) { + if (now >= exp) this.notifiedUids.delete(k) + } + } + this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS) + } + // ---- Private helpers ---- private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] { diff --git a/src/renderer/src/components/messages/MessageList.vue b/src/renderer/src/components/messages/MessageList.vue index 6fd735b..9187763 100644 --- a/src/renderer/src/components/messages/MessageList.vue +++ b/src/renderer/src/components/messages/MessageList.vue @@ -214,8 +214,12 @@ function onExpandAfterLeave(el: Element): void { // ── Refresh ─────────────────────────────────────────────── async function refresh(): Promise { if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return - // Проверяем новые письма во всех папках (для уведомлений) - invoke('messages:poll', { accountId: accountsStore.activeAccountId }).catch(() => {}) + // Проверяем новые письма во всех подключённых аккаунтах (не только активном) + for (const acc of accountsStore.accounts) { + if (accountsStore.connectionStatus[acc.id]?.connected) { + invoke('messages:poll', { accountId: acc.id }).catch(() => {}) + } + } // Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0) await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)