feature/notifications: системные уведомления о новых письмах

- Electron Notification в main-process при срабатывании onNewMail
- Web Notification + in-app toast в NotificationContainer
- pollNewMessages: IMAP STATUS-polling по всем папкам
- Инициализация lastUnseenCount сразу после подключения аккаунта
- autoCheckTimer вызывает messages:poll при каждом refresh
- exists-event: защита от ложного срабатывания при SELECT (prevCount > 0)
- Fallback 'Новое письмо' для пустого from в нативном уведомлении

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
d.a.kolesov 2026-04-06 13:15:39 +07:00
parent f02a1abc88
commit 2122b169b8
14 changed files with 417 additions and 5 deletions

View file

@ -30,6 +30,11 @@ function createWindow(): BrowserWindow {
accountManager.setMainWindow(mainWindow)
// Разрешаем Web Notifications API из renderer
mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => {
callback(permission === 'notifications')
})
globalShortcut.register('F12', () => {
mainWindow.webContents.toggleDevTools()
})

View file

@ -33,6 +33,10 @@ export function registerMessageHandlers(manager: AccountManager): void {
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
})
registerHandler('messages:poll', async ({ accountId }) => {
await manager.pollNewMessages(accountId)
})
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
return manager.fetchMessageBody(accountId, folderId, messageId)
})

View file

@ -187,6 +187,8 @@ export class ExchangeProvider implements IEmailProvider {
}
}
async pollNewMessages(): Promise<void> { /* Exchange использует свой polling через onNewMail */ }
private detectRole(name: string): SpecialFolderRole {
const n = name.toLowerCase()
if (n === 'inbox') return SpecialFolderRole.Inbox

View file

@ -174,6 +174,8 @@ export class GmailProvider implements IEmailProvider {
}
}
async pollNewMessages(): Promise<void> { /* Gmail использует свой polling через onNewMail */ }
private detectRole(labelId: string): SpecialFolderRole {
switch (labelId) {
case 'INBOX': return SpecialFolderRole.Inbox

View file

@ -31,6 +31,8 @@ export class ImapProvider implements IEmailProvider {
private client: ImapFlow
private connected = false
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
// folderId → last known unseen count for polling
private lastUnseenCount = new Map<string, number>()
constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials
@ -159,7 +161,7 @@ export class ImapProvider implements IEmailProvider {
try {
// imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download) {
if (!download?.content) {
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
}
@ -251,12 +253,13 @@ export class ImapProvider implements IEmailProvider {
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
this.newMailCallback = callback
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
if (this.newMailCallback && data.count > data.prevCount) {
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
if (this.newMailCallback && data.prevCount > 0 && data.count > data.prevCount) {
this.newMailCallback(data.path, {
id: '',
folderId: data.path,
subject: 'New message',
from: { name: '', email: '' },
subject: 'Новое сообщение',
from: { name: 'Новое письмо', email: '' },
to: [],
cc: [],
date: new Date().toISOString(),
@ -273,6 +276,48 @@ export class ImapProvider implements IEmailProvider {
this.client.removeAllListeners('exists')
}
async pollNewMessages(): Promise<void> {
if (!this.newMailCallback) return
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.pollFolderTree(tree.folders ?? [])
} catch { /* ignore poll errors */ }
}
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
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)
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
}
}
} finally {
lock.release()
}
}
} catch { /* некоторые папки не поддерживают STATUS */ }
if (folder.folders?.length) {
await this.pollFolderTree(folder.folders)
}
}
}
// ---- Private helpers ----
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {

View file

@ -1,4 +1,5 @@
import { BrowserWindow } from 'electron'
import { BrowserWindow, Notification, nativeImage } from 'electron'
import { join } from 'node:path'
import type { AccountConfig } from '@shared/types/account'
import { AccountType } from '@shared/types/account'
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
@ -121,6 +122,11 @@ export class AccountManager {
return provider.listFolders()
}
async pollNewMessages(accountId: string): Promise<void> {
const provider = this.providers.get(accountId)
if (provider) await provider.pollNewMessages()
}
async listMessages(
accountId: string,
folderId: string,
@ -194,6 +200,29 @@ export class AccountManager {
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
}
if (Notification.isSupported()) {
const from = envelope.from.name || envelope.from.email || 'Новое письмо'
const subject = envelope.subject || '(без темы)'
const iconPath = join(__dirname, '../../resources/icon.png')
const icon = nativeImage.createFromPath(iconPath)
const n = new Notification({
title: from,
body: subject,
icon: icon.isEmpty() ? undefined : icon,
silent: false,
})
n.on('click', () => {
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.show()
this.mainWindow.focus()
this.mainWindow.webContents.send('notification:click', { accountId, folderId, messageId: envelope.id })
}
})
n.show()
}
})
}
}

View file

@ -5,6 +5,7 @@ import FolderTree from '../sidebar/FolderTree.vue'
import MessageList from '../messages/MessageList.vue'
import MessagePreview from '../preview/MessagePreview.vue'
import AddAccountDialog from '../accounts/AddAccountDialog.vue'
import NotificationContainer from '../notifications/NotificationContainer.vue'
import AppIcon from '../AppIcon.vue'
import { useAccountsStore } from '../../stores/accounts.store'
@ -79,6 +80,8 @@ function stopResize(): void {
@close="showAddAccount = false"
/>
<NotificationContainer />
<!-- Пустое состояние: нет аккаунтов -->
<div v-if="accountsStore.accounts.length === 0 && !accountsStore.loading && !showAddAccount" class="empty-state">
<div class="empty-content">

View file

@ -4,6 +4,7 @@ import { useMessagesStore } from '../../stores/messages.store'
import { useFoldersStore } from '../../stores/folders.store'
import { useAccountsStore } from '../../stores/accounts.store'
import { useSettingsStore, type SwipeAction } from '../../stores/settings.store'
import { useIpc } from '../../composables/useIpc'
import MessageListItem from './MessageListItem.vue'
import ThreadListItem from './ThreadListItem.vue'
import AppIcon from '../AppIcon.vue'
@ -13,6 +14,7 @@ const messagesStore = useMessagesStore()
const foldersStore = useFoldersStore()
const accountsStore = useAccountsStore()
const settingsStore = useSettingsStore()
const { invoke } = useIpc()
const selectMode = ref(false)
@ -137,6 +139,8 @@ function onExpandAfterLeave(el: Element): void {
// ── Refresh ───────────────────────────────────────────────
async function refresh(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
// Проверяем новые письма во всех папках (для уведомлений)
invoke('messages:poll', { accountId: accountsStore.activeAccountId }).catch(() => {})
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)

View file

@ -0,0 +1,138 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import NotificationToast from './NotificationToast.vue'
import { useIpc } from '../../composables/useIpc'
import { useAccountsStore } from '../../stores/accounts.store'
import { useFoldersStore } from '../../stores/folders.store'
import { useMessagesStore } from '../../stores/messages.store'
interface ToastItem {
id: string
from: string
subject: string
accountEmail: string
accountId: string
folderId: string
messageId: string
}
const toasts = ref<ToastItem[]>([])
const DURATION = 5000
let counter = 0
const { on } = useIpc()
const accountsStore = useAccountsStore()
const foldersStore = useFoldersStore()
const messagesStore = useMessagesStore()
function addToast(item: Omit<ToastItem, 'id'>): void {
const id = `toast-${++counter}`
toasts.value.push({ id, ...item })
setTimeout(() => removeToast(id), DURATION)
}
function removeToast(id: string): void {
const idx = toasts.value.findIndex(t => t.id === id)
if (idx !== -1) toasts.value.splice(idx, 1)
}
function handleClick(id: string): void {
const toast = toasts.value.find(t => t.id === id)
if (!toast) return
accountsStore.setActive(toast.accountId)
foldersStore.setActiveFolder(toast.folderId)
messagesStore.selectMessage(toast.messageId)
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(() => {
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission()
}
// Новые письма из любой папки (через pollNewMessages в main)
on('mail:new', ({ accountId, folderId, envelope }) => {
const account = accountsStore.accounts.find(a => a.id === accountId)
if (!account) return
const from = envelope.from.name || envelope.from.email
const subject = envelope.subject || '(без темы)'
addToast({ from, subject, accountEmail: account.email, accountId, folderId, messageId: envelope.id })
showOsNotification(from, subject, () => {
accountsStore.setActive(accountId)
foldersStore.setActiveFolder(folderId)
messagesStore.selectMessage(envelope.id)
})
})
on('notification:click', ({ accountId, folderId, messageId }) => {
accountsStore.setActive(accountId)
foldersStore.setActiveFolder(folderId)
messagesStore.selectMessage(messageId)
})
})
</script>
<template>
<Teleport to="body">
<div class="toast-container">
<TransitionGroup name="toast" tag="div" class="toast-list">
<NotificationToast
v-for="toast in toasts"
:key="toast.id"
v-bind="toast"
:on-close="removeToast"
:on-click="handleClick"
/>
</TransitionGroup>
</div>
</Teleport>
</template>
<style scoped>
.toast-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 99999;
pointer-events: none;
}
.toast-list {
display: flex;
flex-direction: column;
gap: 8px;
align-items: flex-end;
}
.toast-enter-active,
.toast-leave-active {
transition:
opacity 220ms ease,
transform 220ms cubic-bezier(0.34, 1.15, 0.64, 1);
}
.toast-enter-from {
opacity: 0;
transform: translateX(20px) scale(0.96);
}
.toast-leave-to {
opacity: 0;
transform: translateX(20px) scale(0.96);
}
</style>

View file

@ -0,0 +1,152 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AppIcon from '../AppIcon.vue'
const props = defineProps<{
id: string
from: string
subject: string
accountEmail: string
onClose: (id: string) => void
onClick: (id: string) => void
}>()
const visible = ref(false)
onMounted(() => {
requestAnimationFrame(() => { visible.value = true })
})
</script>
<template>
<div
class="toast"
:class="{ visible }"
@click="onClick(id)"
>
<div class="toast-icon">
<AppIcon name="envelope" :size="16" />
</div>
<div class="toast-body">
<div class="toast-from">{{ from }}</div>
<div class="toast-subject">{{ subject }}</div>
<div class="toast-account">{{ accountEmail }}</div>
</div>
<button class="toast-close" @click.stop="onClose(id)">
<svg width="9" height="9" viewBox="0 0 9 9" fill="none">
<line x1="1" y1="1" x2="8" y2="8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
<line x1="8" y1="1" x2="1" y2="8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</button>
</div>
</template>
<style scoped>
.toast {
display: flex;
align-items: flex-start;
gap: 10px;
width: 320px;
padding: 12px 14px;
border-radius: 14px;
cursor: pointer;
background:
linear-gradient(145deg, rgba(255,255,255,0.12) 0%, rgba(255,255,255,0.05) 100%),
rgba(12, 12, 22, 0.88);
backdrop-filter: blur(40px) saturate(2.0);
-webkit-backdrop-filter: blur(40px) saturate(2.0);
border: 1px solid rgba(255, 255, 255, 0.16);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.20),
0 8px 32px rgba(0, 0, 0, 0.50),
0 2px 8px rgba(0, 0, 0, 0.30);
opacity: 0;
transform: translateX(20px) scale(0.96);
transition:
opacity 220ms cubic-bezier(0.34, 1.15, 0.64, 1),
transform 220ms cubic-bezier(0.34, 1.15, 0.64, 1);
pointer-events: all;
}
.toast.visible {
opacity: 1;
transform: translateX(0) scale(1);
}
.toast:hover {
background:
linear-gradient(145deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.08) 100%),
rgba(14, 14, 24, 0.92);
border-color: rgba(255, 255, 255, 0.22);
}
.toast-icon {
flex-shrink: 0;
width: 28px;
height: 28px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
color: var(--accent);
background: color-mix(in srgb, var(--accent) 14%, transparent);
border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent);
margin-top: 1px;
}
.toast-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.toast-from {
font-size: 12.5px;
font-weight: 600;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.toast-subject {
font-size: 12px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.toast-account {
font-size: 10.5px;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-top: 2px;
}
.toast-close {
flex-shrink: 0;
width: 18px;
height: 18px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.09);
margin-top: 1px;
transition: background var(--transition-fast), color var(--transition-fast);
}
.toast-close:hover {
background: rgba(255, 255, 255, 0.12);
color: var(--text-secondary);
}
</style>

View file

@ -28,6 +28,11 @@ export const useAccountsStore = defineStore('accounts', () => {
connected: result.success,
error: result.error
}
// Инициализируем lastUnseenCount сразу после подключения —
// иначе первый autoCheckTimer только заполняет карту, а второй уже шлёт уведомления.
if (result.success) {
invoke('messages:poll', { accountId: acc.id }).catch(() => {})
}
}
if (accounts.value.length > 0 && !activeAccountId.value) {

View file

@ -47,6 +47,24 @@ export const useMessagesStore = defineStore('messages', () => {
// Unread filter
const unreadOnly = ref(false)
// Отслеживание новых писем между обновлениями
const knownIds = new Map<string, Set<string>>() // key = accountId:folderId
const newArrivals = ref<Array<{ accountId: string; folderId: string; envelope: MessageEnvelope }>>([])
function detectNewMessages(accountId: string, folderId: string, fresh: MessageEnvelope[]): void {
const key = `${accountId}:${folderId}`
const prev = knownIds.get(key)
const nextIds = new Set(fresh.map(m => m.id))
knownIds.set(key, nextIds)
if (!prev) return
const arrived = fresh.filter(m => !prev.has(m.id) && !m.flags.seen)
for (const envelope of arrived) {
newArrivals.value = [{ accountId, folderId, envelope }]
}
}
const filteredMessages = computed(() =>
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
)
@ -63,6 +81,7 @@ export const useMessagesStore = defineStore('messages', () => {
})
if (offset === 0) {
detectNewMessages(accountId, folderId, result.messages)
messages.value = result.messages
if (unreadOnly.value) {
// result.total — это точное число непрочитанных из SEARCH UNSEEN
@ -343,6 +362,7 @@ export const useMessagesStore = defineStore('messages', () => {
messageBody,
loading,
loadingBody,
newArrivals,
loadMessages,
loadMore,
selectMessage,

View file

@ -38,6 +38,7 @@ export interface IpcChannelMap {
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
'messages:poll': [{ accountId: string }, void]
'app:setZoom': [{ factor: number }, void]
}
@ -45,6 +46,7 @@ export interface IpcEventMap {
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope }
'account:status': { accountId: string; connected: boolean; 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

View file

@ -30,4 +30,5 @@ export interface IEmailProvider {
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
offNewMail(): void
pollNewMessages(): Promise<void>
}