fix: восстановление уведомлений — реальные данные, дедупликация, все аккаунты

- exists-событие больше не шлёт фиктивный envelope (id:'', 'Новое письмо');
  вместо этого оно немедленно запускает pollSingleFolder, которая получает
  реальные данные сообщения — клик по тосту корректно открывает письмо
- UID-дедупликация (TTL 5 мин): одно и то же письмо не даёт два тоста,
  даже если exists + polling сработали почти одновременно
- pollFolderTree при ошибке STATUS не обнуляет сохранённый счётчик
  (lastUnseenCount), чтобы не потерять точку отсчёта
- refresh() опрашивает все подключённые аккаунты, а не только активный —
  пользователи с несколькими ящиками получают уведомления по каждому

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Aero Mail Dev 2026-04-16 05:43:55 +00:00
parent 4c3b14c7a9
commit 19f73efde2
2 changed files with 69 additions and 34 deletions

View file

@ -34,6 +34,9 @@ export class ImapProvider implements IEmailProvider {
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
// folderId → last known unseen count for polling // folderId → last known unseen count for polling
private lastUnseenCount = new Map<string, number>() private lastUnseenCount = new Map<string, number>()
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
private notifiedUids = new Map<string, number>()
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
constructor(private config: AccountConfig) { constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials const creds = config.credentials as ImapCredentials
@ -367,19 +370,9 @@ export class ImapProvider implements IEmailProvider {
this.newMailCallback = callback this.newMailCallback = callback
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => { this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо) // Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
if (this.newMailCallback && data.prevCount > 0 && data.count > data.prevCount) { if (data.prevCount > 0 && data.count > data.prevCount) {
this.newMailCallback(data.path, { // Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
id: '', this.pollSingleFolder(data.path).catch(() => {})
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: ''
})
} }
}) })
} }
@ -462,36 +455,55 @@ export class ImapProvider implements IEmailProvider {
try { try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] } const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.pollFolderTree(tree.folders ?? []) 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<void> {
if (!this.newMailCallback) return
try {
await this.pollFolderTree([{ name: folderPath, path: folderPath }])
} catch { /* ignore */ }
} }
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> { private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
for (const folder of folders) { for (const folder of folders) {
try { try {
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null
const unseen = status?.unseen ?? 0 // Если STATUS вернул null или упал — не трогаем сохранённый счётчик
const prev = this.lastUnseenCount.get(folder.path) if (status) {
this.lastUnseenCount.set(folder.path, unseen) 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) { if (prev !== undefined && unseen > prev && this.newMailCallback) {
// Получаем последнее непрочитанное письмо для уведомления // Получаем последнее непрочитанное письмо для уведомления
const lock = await this.client.getMailboxLock(folder.path) const lock = await this.client.getMailboxLock(folder.path)
try { try {
const uids = await this.client.search({ seen: false }, { uid: true }) as number[] const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (uids?.length) { if (uids?.length) {
const latestUid = Math.max(...uids).toString() const latestUid = Math.max(...uids).toString()
for await (const msg of this.client.fetch(latestUid, { const dedupKey = `${folder.path}:${latestUid}`
uid: true, envelope: true, flags: true if (!this.isRecentlyNotified(dedupKey)) {
}, { uid: true })) { for await (const msg of this.client.fetch(latestUid, {
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) uid: true, envelope: true, flags: true
break }, { 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) { if (folder.folders?.length) {
await this.pollFolderTree(folder.folders) 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 helpers ----
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] { private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {

View file

@ -214,8 +214,12 @@ function onExpandAfterLeave(el: Element): void {
// ── Refresh ─────────────────────────────────────────────── // ── Refresh ───────────────────────────────────────────────
async function refresh(): Promise<void> { async function refresh(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return 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 упадёт если папка залочена параллельно // Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0) await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId) await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)