Merge branch 'feature/fix-notifications'

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
vodyanoysh 2026-04-16 20:26:42 +07:00
commit 5be387b034
6 changed files with 212 additions and 39 deletions

85
CLAUDE.md Normal file
View file

@ -0,0 +1,85 @@
# Aero Mail — Developer Notes
## Stack
Electron 35 + Vue 3 Composition API + Pinia + TypeScript + electron-vite.
IMAP (imapflow) for reading, SMTP (nodemailer) for sending.
No Gmail API / Exchange EWS — IMAP+SMTP only.
## Architecture
Three Electron processes: **main** / **preload** (contextBridge `window.api`) / **renderer** (Vue SPA).
IPC: type-safe `invoke` (Renderer→Main) + push events (Main→Renderer).
Types live in `src/shared/types/ipc.ts`.
Key files:
| File | Role |
|------|------|
| `src/main/index.ts` | Electron entry, window management |
| `src/main/services/account-manager.ts` | Provider map, IPC routing, auto-reconnect |
| `src/main/providers/imap.provider.ts` | IMAP+SMTP implementation |
| `src/renderer/src/stores/messages.store.ts` | Message list, LRU body cache, search |
| `src/renderer/src/stores/folders.store.ts` | Folder tree, unread counts |
| `src/shared/types/ipc.ts` | All IPC channels |
## IPC event listeners — required cleanup pattern
`window.api.on(channel, callback)` wraps `ipcRenderer.on` and returns an **unsubscribe function**.
If the component that registers a listener can be unmounted (i.e. it lives inside a `<router-view>`),
the unsubscribe **must** be called in `onUnmounted`, otherwise listeners accumulate on every remount.
```ts
// CORRECT
let unsub: (() => void) | null = null
onMounted(() => {
unsub = on('mail:new', handler)
})
onUnmounted(() => {
unsub?.()
})
```
```ts
// BUG — listener survives unmount, fires N times after N navigations
onMounted(() => {
on('mail:new', handler) // return value discarded
})
```
Pinia store setup functions run once (singleton) — `on()` calls inside them do not need cleanup.
Background: `NotificationContainer.vue` had this bug. It is mounted inside `MailView` which unmounts
on every route change (→ Settings, → Calendar). Each remount registered a new `mail:new` listener,
causing duplicate OS push notifications per incoming email.
Fixed in commit on branch `feature/fix-notifications`.
## New-mail notification flow
```
IMAP exists event
→ ImapProvider.pollSingleFolder()
└→ pollFolderTree() ← dedup via lastUnseenCount + notifiedUids (5 min TTL)
App.vue poll timer (autoCheckInterval)
→ messages:poll IPC
└→ AccountManager.pollNewMessages()
└→ ImapProvider.pollFolderTree() ← same dedup
Both paths → newMailCallback → main sends mail:new IPC → renderer
→ NotificationContainer: OS Notification + in-app toast
→ messages.store: insert envelope, update unread count
```
Dedup keys in `ImapProvider`: `"folderPath:uid"`, TTL 5 min. `lastUnseenCount` is updated
**before** acquiring the mailbox lock, so concurrent runs of `pollFolderTree` for the same folder
see the updated count and skip the second notification.
## Folder mute
`notifications.store.ts` stores muted folders in `localStorage` (`muted-folders` key).
Mute is per `accountId:folderId`, supports duration (ms) or permanent (`null`).
Mute check walks up the folder parent chain — muting a parent silences all children.

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

@ -1,12 +1,39 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue' import { onMounted, onUnmounted, watch } from 'vue'
import { useAccountsStore } from './stores/accounts.store' import { useAccountsStore } from './stores/accounts.store'
import { useSettingsStore } from './stores/settings.store'
import { useIpc } from './composables/useIpc'
const accountsStore = useAccountsStore() const accountsStore = useAccountsStore()
const settingsStore = useSettingsStore()
const { invoke } = useIpc()
onMounted(() => { onMounted(() => {
accountsStore.loadAccounts() accountsStore.loadAccounts()
}) })
// ── Глобальный таймер опроса новых писем ──────────────────
// Живёт на уровне App, не останавливается при смене вкладки
let pollTimer: ReturnType<typeof setInterval> | null = null
function pollAllAccounts(): void {
for (const acc of accountsStore.accounts) {
if (accountsStore.connectionStatus[acc.id]?.connected) {
invoke('messages:poll', { accountId: acc.id }).catch(() => {})
}
}
}
function restartPollTimer(): void {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
if (settingsStore.autoCheckInterval > 0) {
pollTimer = setInterval(pollAllAccounts, settingsStore.autoCheckInterval * 60_000)
}
}
watch(() => settingsStore.autoCheckInterval, restartPollTimer)
onMounted(restartPollTimer)
onUnmounted(() => { if (pollTimer) clearInterval(pollTimer) })
</script> </script>
<template> <template>

View file

@ -214,8 +214,6 @@ 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(() => {})
// Последовательно: 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)

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted } from 'vue' import { ref, onMounted, onUnmounted } from 'vue'
import NotificationToast from './NotificationToast.vue' import NotificationToast from './NotificationToast.vue'
import { useIpc } from '../../composables/useIpc' import { useIpc } from '../../composables/useIpc'
import { useAccountsStore } from '../../stores/accounts.store' import { useAccountsStore } from '../../stores/accounts.store'
@ -20,6 +20,7 @@ interface ToastItem {
const toasts = ref<ToastItem[]>([]) const toasts = ref<ToastItem[]>([])
const DURATION = 5000 const DURATION = 5000
let counter = 0 let counter = 0
let unsubscribeMailNew: (() => void) | null = null
const { on } = useIpc() const { on } = useIpc()
const accountsStore = useAccountsStore() const accountsStore = useAccountsStore()
@ -47,16 +48,48 @@ function handleClick(id: string): void {
removeToast(id) removeToast(id)
} }
function showOsNotification(from: string, subject: string, onClick: () => void): void {
if (!('Notification' in window)) return
const send = (): void => {
const n = new window.Notification(from, { body: subject, silent: false })
n.onclick = () => { onClick(); n.close() }
}
if (Notification.permission === 'granted') {
send()
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(p => { if (p === 'granted') send() })
}
}
onMounted(() => { onMounted(() => {
on('mail:new', ({ accountId, folderId, envelope }) => { // Запрашиваем разрешение заранее, чтобы не задерживать первое уведомление
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission()
}
unsubscribeMailNew = on('mail:new', ({ accountId, folderId, envelope }) => {
const account = accountsStore.accounts.find(a => a.id === accountId) const account = accountsStore.accounts.find(a => a.id === accountId)
if (!account) return if (!account) return
if (notificationsStore.isMuted(accountId, folderId)) return if (notificationsStore.isMuted(accountId, folderId)) return
const from = envelope.from.name || envelope.from.email
const from = envelope.from.name || envelope.from.email || 'Новое письмо'
const subject = envelope.subject || '(без темы)' const subject = envelope.subject || '(без темы)'
// Системное уведомление — показываем всегда; клик фокусирует окно и открывает письмо
showOsNotification(from, subject, () => {
accountsStore.setActive(accountId)
foldersStore.setActiveFolder(folderId)
messagesStore.selectMessage(envelope.id)
})
// In-app тост — дополнительная индикация внутри приложения
addToast({ from, subject, accountEmail: account.email, accountId, folderId, messageId: envelope.id }) addToast({ from, subject, accountEmail: account.email, accountId, folderId, messageId: envelope.id })
}) })
}) })
onUnmounted(() => {
unsubscribeMailNew?.()
})
</script> </script>
<template> <template>

View file

@ -64,7 +64,6 @@ export interface IpcEventMap {
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope } 'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope }
'account:status': { accountId: string; connected: boolean; error?: string } 'account:status': { accountId: string; connected: boolean; error?: string }
'attachment:progress': { attachmentId: string; stage: 'downloading' | 'saving' | 'done' | 'error'; progress: number; error?: string } 'attachment:progress': { attachmentId: string; stage: 'downloading' | 'saving' | 'done' | 'error'; progress: number; error?: string }
'notification:click': { accountId: string; folderId: string; messageId: string }
} }
export type IpcChannel = keyof IpcChannelMap export type IpcChannel = keyof IpcChannelMap