diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b9e5b7c --- /dev/null +++ b/CLAUDE.md @@ -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 ``), +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. 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/App.vue b/src/renderer/src/App.vue index de269c6..a251bee 100644 --- a/src/renderer/src/App.vue +++ b/src/renderer/src/App.vue @@ -1,12 +1,39 @@