Compare commits

...

2 commits

Author SHA1 Message Date
r.rasputin
80e6fdd523 Merge remote-tracking branch 'origin/master' into feature/cleaner 2026-07-31 14:27:07 +07:00
r.rasputin
5620eb827a Поиск писем по локальному индексу заголовков
Серверный IMAP SEARCH оказался ненадёжен (не находит не-ASCII имена,
на части полей отвечает некорректно). Вместо него — локальный индекс
заголовков (from/to/cc/subject/дата/флаги): фоновая полная синхронизация
через отдельное IMAP-соединение при подключении аккаунта, дальше индекс
держится в актуальном состоянии точечно (новое письмо, удаление,
retention-очистка) плюс периодическая дифф-синхронизация раз в 15 минут.
Поиск теперь мгновенный, по всей истории и не ходит в IMAP вовсе.
2026-07-31 12:39:01 +07:00
16 changed files with 627 additions and 156 deletions

View file

@ -4,17 +4,22 @@ import { statSync, mkdirSync, copyFileSync, writeFileSync, readdirSync, unlinkSy
import { homedir } from 'node:os' import { homedir } from 'node:os'
import { AccountManager } from './services/account-manager' import { AccountManager } from './services/account-manager'
import { RetentionService } from './services/retention-service' import { RetentionService } from './services/retention-service'
import { MailIndexer } from './services/mail-indexer'
import { registerAccountHandlers } from './ipc/accounts.handler' import { registerAccountHandlers } from './ipc/accounts.handler'
import { registerFolderHandlers } from './ipc/folders.handler' import { registerFolderHandlers } from './ipc/folders.handler'
import { registerMessageHandlers } from './ipc/messages.handler' import { registerMessageHandlers } from './ipc/messages.handler'
import { registerCalendarHandlers } from './ipc/calendar.handler' import { registerCalendarHandlers } from './ipc/calendar.handler'
import { registerUpdaterHandlers } from './ipc/updater.handler' import { registerUpdaterHandlers } from './ipc/updater.handler'
import { registerRetentionHandlers } from './ipc/retention.handler' import { registerRetentionHandlers } from './ipc/retention.handler'
import { registerSearchIndexHandlers } from './ipc/search-index.handler'
import { updater } from './services/updater' import { updater } from './services/updater'
import type { ComposeSession } from '@shared/types/message' import type { ComposeSession } from '@shared/types/message'
const accountManager = new AccountManager() const accountManager = new AccountManager()
const retentionService = new RetentionService(accountManager) const retentionService = new RetentionService(accountManager)
const mailIndexer = new MailIndexer()
accountManager.setMailIndexer(mailIndexer)
retentionService.setMailIndexer(mailIndexer)
// ── Compose windows ─────────────────────────────────────── // ── Compose windows ───────────────────────────────────────
// webContentsId → session, заполняется до loadURL, читается окном при монтировании // webContentsId → session, заполняется до loadURL, читается окном при монтировании
@ -99,6 +104,7 @@ function createWindow(): BrowserWindow {
accountManager.setMainWindow(mainWindow) accountManager.setMainWindow(mainWindow)
retentionService.setMainWindow(mainWindow) retentionService.setMainWindow(mainWindow)
mailIndexer.setMainWindow(mainWindow)
// Разрешаем Web Notifications API из renderer // Разрешаем Web Notifications API из renderer
mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => { mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => {
@ -201,12 +207,14 @@ app.whenReady().then(async () => {
// Register all IPC handlers // Register all IPC handlers
registerAccountHandlers(accountManager, retentionService) registerAccountHandlers(accountManager, retentionService)
registerFolderHandlers(accountManager) registerFolderHandlers(accountManager)
registerMessageHandlers(accountManager) registerMessageHandlers(accountManager, mailIndexer)
registerCalendarHandlers(accountManager) registerCalendarHandlers(accountManager)
registerUpdaterHandlers() registerUpdaterHandlers()
registerRetentionHandlers(retentionService) registerRetentionHandlers(retentionService)
registerSearchIndexHandlers(mailIndexer)
createWindow() createWindow()
mailIndexer.startPeriodicSync()
if (app.isPackaged) { if (app.isPackaged) {
setTimeout(() => updater.checkForUpdates(), 10_000) setTimeout(() => updater.checkForUpdates(), 10_000)
@ -227,4 +235,5 @@ app.on('window-all-closed', () => {
app.on('before-quit', () => { app.on('before-quit', () => {
retentionService.dispose() retentionService.dispose()
mailIndexer.dispose()
}) })

View file

@ -3,6 +3,7 @@ import { writeFile, access } from 'fs/promises'
import { join, extname, basename } from 'path' import { join, extname, basename } from 'path'
import { registerHandler } from './registry' import { registerHandler } from './registry'
import type { AccountManager } from '../services/account-manager' import type { AccountManager } from '../services/account-manager'
import type { MailIndexer } from '../services/mail-indexer'
function assertId(value: unknown, name: string): asserts value is string { function assertId(value: unknown, name: string): asserts value is string {
if (typeof value !== 'string' || value.length === 0) { if (typeof value !== 'string' || value.length === 0) {
@ -40,7 +41,7 @@ function sendProgress(attachmentId: string, stage: 'downloading' | 'saving' | 'd
win?.webContents.send('attachment:progress', { attachmentId, stage, progress, error }) win?.webContents.send('attachment:progress', { attachmentId, stage, progress, error })
} }
export function registerMessageHandlers(manager: AccountManager): void { export function registerMessageHandlers(manager: AccountManager, mailIndexer: MailIndexer): void {
registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => { registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
assertId(accountId, 'accountId') assertId(accountId, 'accountId')
assertId(folderId, 'folderId') assertId(folderId, 'folderId')
@ -64,7 +65,7 @@ export function registerMessageHandlers(manager: AccountManager): void {
registerHandler('messages:search', async ({ accountId, query, limit }) => { registerHandler('messages:search', async ({ accountId, query, limit }) => {
assertId(accountId, 'accountId') assertId(accountId, 'accountId')
return manager.searchMessages(accountId, query, limit) return mailIndexer.search(accountId, query, limit)
}) })
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => { registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {

View file

@ -0,0 +1,8 @@
import { registerHandler } from './registry'
import type { MailIndexer } from '../services/mail-indexer'
export function registerSearchIndexHandlers(mailIndexer: MailIndexer): void {
registerHandler('search:status', async ({ accountId }) => {
return mailIndexer.getStatus(accountId)
})
}

View file

@ -0,0 +1,64 @@
import type { MessageEnvelope, Address } from '@shared/types/message'
// imapflow BodyStructure type
export interface ImapBodyPart {
part?: string
type?: string
subtype?: string
disposition?: string
parameters?: Record<string, string>
id?: string
encoding?: string
childNodes?: ImapBodyPart[]
}
interface ImapFetchedMessage {
uid: number
envelope?: {
subject?: string
from?: Array<{ name?: string; address?: string }>
to?: Array<{ name?: string; address?: string }>
cc?: Array<{ name?: string; address?: string }>
date?: Date
messageId?: string
inReplyTo?: string
}
flags?: Set<string>
bodyStructure?: ImapBodyPart
}
function addressesFrom(list?: Array<{ name?: string; address?: string }>): Address[] {
return (list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' }))
}
function messageHasAttachments(node?: ImapBodyPart): boolean {
if (!node) return false
if (node.disposition === 'attachment') return true
if (node.childNodes) return node.childNodes.some((c) => messageHasAttachments(c))
return false
}
export function convertImapMessage(msg: unknown, folderId: string): MessageEnvelope {
const m = msg as ImapFetchedMessage
const flags = m.flags ?? new Set<string>()
return {
id: String(m.uid),
folderId,
subject: m.envelope?.subject ?? '(no subject)',
from: addressesFrom(m.envelope?.from)[0] ?? { name: '', email: '' },
to: addressesFrom(m.envelope?.to),
cc: addressesFrom(m.envelope?.cc),
date: m.envelope?.date?.toISOString() ?? new Date().toISOString(),
flags: {
seen: flags.has('\\Seen'),
flagged: flags.has('\\Flagged'),
answered: flags.has('\\Answered'),
deleted: flags.has('\\Deleted')
},
hasAttachments: messageHasAttachments(m.bodyStructure),
snippet: '',
messageId: m.envelope?.messageId ?? undefined,
inReplyTo: m.envelope?.inReplyTo ?? undefined,
}
}

View file

@ -2,12 +2,13 @@ import { ImapFlow } from 'imapflow'
import { simpleParser } from 'mailparser' import { simpleParser } from 'mailparser'
import nodemailer from 'nodemailer' import nodemailer from 'nodemailer'
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider' import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, InlineImage, Attachment } from '@shared/types/message' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message'
import { SpecialFolderRole } from '@shared/types/folder' import { SpecialFolderRole } from '@shared/types/folder'
import type { Folder } from '@shared/types/folder' import type { Folder } from '@shared/types/folder'
import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { AccountConfig, ImapCredentials } from '@shared/types/account'
import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention' import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention'
import { sanitizeHtml } from '../lib/html-sanitizer' import { sanitizeHtml } from '../lib/html-sanitizer'
import { convertImapMessage } from '../lib/imap-message-mapper'
// imapflow MailboxObject type // imapflow MailboxObject type
interface ImapMailbox { interface ImapMailbox {
@ -17,18 +18,6 @@ interface ImapMailbox {
folders?: ImapMailbox[] folders?: ImapMailbox[]
} }
// imapflow BodyStructure type
interface BodyPart {
part?: string
type?: string
subtype?: string
disposition?: string
parameters?: Record<string, string>
id?: string
encoding?: string
childNodes?: BodyPart[]
}
export class ImapProvider implements IEmailProvider { export class ImapProvider implements IEmailProvider {
private client: ImapFlow private client: ImapFlow
private connected = false private connected = false
@ -148,7 +137,7 @@ export class ImapProvider implements IEmailProvider {
flags: true, flags: true,
bodyStructure: true bodyStructure: true
})) { })) {
messages.push(this.convertMessage(msg, options.folderId)) messages.push(convertImapMessage(msg, options.folderId))
} }
// Newest first // Newest first
@ -179,7 +168,7 @@ export class ImapProvider implements IEmailProvider {
flags: true, flags: true,
bodyStructure: true bodyStructure: true
}, { uid: true })) { }, { uid: true })) {
messages.push(this.convertMessage(msg, options.folderId)) messages.push(convertImapMessage(msg, options.folderId))
} }
// Fetch returns ascending order → reverse to newest first // Fetch returns ascending order → reverse to newest first
messages.sort((a, b) => Number(b.id) - Number(a.id)) messages.sort((a, b) => Number(b.id) - Number(a.id))
@ -328,8 +317,8 @@ export class ImapProvider implements IEmailProvider {
if (effectiveLimit !== null) { if (effectiveLimit !== null) {
try { try {
const deletedCount = await this.trimFolder(folder.id, effectiveLimit) const deletedUids = await this.trimFolder(folder.id, effectiveLimit)
if (deletedCount > 0) results.push({ folderId: folder.id, deletedCount }) if (deletedUids.length > 0) results.push({ folderId: folder.id, deletedCount: deletedUids.length, deletedUids })
} catch (err) { } catch (err) {
console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message) console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message)
} }
@ -344,21 +333,22 @@ export class ImapProvider implements IEmailProvider {
// Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number — // Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number —
// тот же порядок "старое → новое", что используется в listMessages. // тот же порядок "старое → новое", что используется в listMessages.
private async trimFolder(folderId: string, maxMessages: number): Promise<number> { // Возвращает UID удалённых писем — вызывающий код убирает их из локального поискового индекса.
private async trimFolder(folderId: string, maxMessages: number): Promise<string[]> {
const lock = await this.client.getMailboxLock(folderId) const lock = await this.client.getMailboxLock(folderId)
try { try {
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0 const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
const excess = total - maxMessages const excess = total - maxMessages
if (excess <= 0) return 0 if (excess <= 0) return []
const uidsToDelete: number[] = [] const uidsToDelete: number[] = []
for await (const msg of this.client.fetch(`1:${excess}`, { uid: true })) { for await (const msg of this.client.fetch(`1:${excess}`, { uid: true })) {
uidsToDelete.push((msg as { uid: number }).uid) uidsToDelete.push((msg as { uid: number }).uid)
} }
if (uidsToDelete.length === 0) return 0 if (uidsToDelete.length === 0) return []
await this.client.messageDelete(uidsToDelete.join(','), { uid: true }) await this.client.messageDelete(uidsToDelete.join(','), { uid: true })
return uidsToDelete.length return uidsToDelete.map(String)
} finally { } finally {
lock.release() lock.release()
} }
@ -501,74 +491,6 @@ export class ImapProvider implements IEmailProvider {
this.client.removeAllListeners('exists') this.client.removeAllListeners('exists')
} }
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
const results: MessageEnvelope[] = []
// Не ловим ошибки здесь — они должны попасть в withAutoReconnect (AccountManager)
// для переподключения при NoConnection и прочих сетевых сбоях
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.searchFolderTree(tree.folders ?? [], query, limit, results)
return results
}
private shouldSkipFolder(folder: ImapMailbox): boolean {
const n = folder.name.toLowerCase()
const p = (folder.path ?? '').toLowerCase()
return (
n === 'trash' || n === 'deleted items' || n === 'deleted messages' ||
n === 'spam' || n === 'junk' || n === 'junk e-mail' ||
p.includes('[gmail]/trash') || p.includes('[gmail]/spam')
)
}
private async searchFolderTree(
folders: ImapMailbox[],
query: string,
limit: number,
results: MessageEnvelope[]
): Promise<void> {
for (const folder of folders) {
if (results.length >= limit) break
if (this.shouldSkipFolder(folder)) {
if (folder.folders?.length && results.length < limit) {
await this.searchFolderTree(folder.folders, query, limit, results)
}
continue
}
let lock: Awaited<ReturnType<typeof this.client.getMailboxLock>> | null = null
try {
lock = await this.client.getMailboxLock(folder.path)
// SUBJECT + FROM — серверный поиск (быстрее, чем TEXT по телу)
const rawSubject = await this.client.search({ subject: query }, { uid: true })
const rawFrom = await this.client.search({ from: query }, { uid: true })
const subjectUids = Array.isArray(rawSubject) ? rawSubject : []
const fromUids = Array.isArray(rawFrom) ? rawFrom : []
// Объединяем UIDs без дублей
const merged = [...new Set([...subjectUids, ...fromUids])]
if (merged.length) {
const remaining = limit - results.length
const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining)
for await (const msg of this.client.fetch(sorted.join(','), {
uid: true, envelope: true, flags: true, bodyStructure: true
}, { uid: true })) {
results.push(this.convertMessage(msg, folder.path))
}
}
} catch (e) {
console.error('[IMAP:search] folder error:', folder?.path, e)
}
finally {
lock?.release()
}
if (folder.folders?.length && results.length < limit) {
await this.searchFolderTree(folder.folders, query, limit, results)
}
}
}
async pollNewMessages(): Promise<void> { async pollNewMessages(): Promise<void> {
if (!this.newMailCallback) return if (!this.newMailCallback) return
try { try {
@ -610,7 +532,7 @@ export class ImapProvider implements IEmailProvider {
uid: true, envelope: true, flags: true uid: true, envelope: true, flags: true
}, { uid: true })) { }, { uid: true })) {
this.markNotified(dedupKey) this.markNotified(dedupKey)
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path)) this.newMailCallback(folder.path, convertImapMessage(msg, folder.path))
break break
} }
} }
@ -685,48 +607,6 @@ export class ImapProvider implements IEmailProvider {
return SpecialFolderRole.None return SpecialFolderRole.None
} }
private convertMessage(msg: unknown, folderId: string): MessageEnvelope {
const m = msg as {
uid: number
envelope: {
subject?: string
from?: Array<{ name?: string; address?: string }>
to?: Array<{ name?: string; address?: string }>
cc?: Array<{ name?: string; address?: string }>
date?: Date
messageId?: string
inReplyTo?: string
}
flags: Set<string>
bodyStructure?: BodyPart
}
const addr = (list?: Array<{ name?: string; address?: string }>): Address[] =>
(list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' }))
const flags = m.flags ?? new Set<string>()
return {
id: String(m.uid),
folderId,
subject: m.envelope?.subject ?? '(no subject)',
from: addr(m.envelope?.from)[0] ?? { name: '', email: '' },
to: addr(m.envelope?.to),
cc: addr(m.envelope?.cc),
date: m.envelope?.date?.toISOString() ?? new Date().toISOString(),
flags: {
seen: flags.has('\\Seen'),
flagged: flags.has('\\Flagged'),
answered: flags.has('\\Answered'),
deleted: flags.has('\\Deleted')
},
hasAttachments: this.hasAttachments(m.bodyStructure),
snippet: '',
messageId: m.envelope?.messageId ?? undefined,
inReplyTo: m.envelope?.inReplyTo ?? undefined,
}
}
/** /**
* Конвертирует plain text в минимальный HTML (параграфы + переносы строк). * Конвертирует plain text в минимальный HTML (параграфы + переносы строк).
*/ */
@ -801,11 +681,4 @@ export class ImapProvider implements IEmailProvider {
.replace(/\n{3,}/g, '\n\n') .replace(/\n{3,}/g, '\n\n')
.trim() .trim()
} }
private hasAttachments(node?: BodyPart): boolean {
if (!node) return false
if (node.disposition === 'attachment') return true
if (node.childNodes) return node.childNodes.some((c) => this.hasAttachments(c))
return false
}
} }

View file

@ -2,12 +2,13 @@ import { BrowserWindow } from 'electron'
import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { AccountConfig, ImapCredentials } from '@shared/types/account'
import { AccountType } from '@shared/types/account' import { AccountType } from '@shared/types/account'
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider' import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData } from '@shared/types/message' import type { MessageBody, MessageFlags, ComposeData } from '@shared/types/message'
import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar'
import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention' import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention'
import { ImapProvider } from '../providers/imap.provider' import { ImapProvider } from '../providers/imap.provider'
import { CalDavProvider } from '../providers/caldav.provider' import { CalDavProvider } from '../providers/caldav.provider'
import { CredentialStore } from './credential-store' import { CredentialStore } from './credential-store'
import type { MailIndexer } from './mail-indexer'
import Store from 'electron-store' import Store from 'electron-store'
interface AccountStoreSchema { interface AccountStoreSchema {
@ -23,6 +24,7 @@ export class AccountManager {
private store: Store<AccountStoreSchema> private store: Store<AccountStoreSchema>
private credentialStore: CredentialStore private credentialStore: CredentialStore
private mainWindow: BrowserWindow | null = null private mainWindow: BrowserWindow | null = null
private mailIndexer: MailIndexer | null = null
constructor() { constructor() {
this.store = new Store<AccountStoreSchema>({ this.store = new Store<AccountStoreSchema>({
@ -36,6 +38,10 @@ export class AccountManager {
this.mainWindow = win this.mainWindow = win
} }
setMailIndexer(indexer: MailIndexer): void {
this.mailIndexer = indexer
}
async initialize(): Promise<void> { async initialize(): Promise<void> {
await this.credentialStore.load() await this.credentialStore.load()
} }
@ -62,6 +68,9 @@ export class AccountManager {
this.providers.set(config.id, provider) this.providers.set(config.id, provider)
this.setupNewMailListener(config.id, provider) this.setupNewMailListener(config.id, provider)
this.mailIndexer?.onAccountConnected(config.id, config).catch((err) => {
console.warn(`[AccountManager] index sync failed for ${config.id}:`, (err as Error).message)
})
return { success: true } return { success: true }
} catch (error) { } catch (error) {
@ -78,6 +87,7 @@ export class AccountManager {
} }
this.calendarProviders.delete(accountId) this.calendarProviders.delete(accountId)
await this.credentialStore.remove(accountId) await this.credentialStore.remove(accountId)
this.mailIndexer?.removeAccount(accountId)
const accounts = this.store.get('accounts', []) const accounts = this.store.get('accounts', [])
this.store.set('accounts', accounts.filter((a) => a.id !== accountId)) this.store.set('accounts', accounts.filter((a) => a.id !== accountId))
@ -120,6 +130,9 @@ export class AccountManager {
await provider.connect() await provider.connect()
this.providers.set(accountId, provider) this.providers.set(accountId, provider)
this.setupNewMailListener(accountId, provider) this.setupNewMailListener(accountId, provider)
this.mailIndexer?.onAccountConnected(accountId, config).catch((err) => {
console.warn(`[AccountManager] index sync failed for ${accountId}:`, (err as Error).message)
})
return { success: true } return { success: true }
} catch (error) { } catch (error) {
@ -149,14 +162,6 @@ export class AccountManager {
) )
} }
async searchMessages(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
return this.withAutoReconnect(accountId, () => {
const provider = this.providers.get(accountId)
if (!provider) return Promise.resolve([])
return provider.searchMessages(query, limit)
})
}
async listMessages( async listMessages(
accountId: string, accountId: string,
folderId: string, folderId: string,
@ -206,9 +211,10 @@ export class AccountManager {
folderId: string, folderId: string,
messageIds: string[] messageIds: string[]
): Promise<void> { ): Promise<void> {
return this.withAutoReconnect(accountId, () => await this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).deleteMessages(folderId, messageIds) this.getProvider(accountId).deleteMessages(folderId, messageIds)
) )
this.mailIndexer?.removeMessages(accountId, folderId, messageIds)
} }
async markAllRead(accountId: string, folderId: string): Promise<void> { async markAllRead(accountId: string, folderId: string): Promise<void> {
@ -398,6 +404,9 @@ export class AccountManager {
await newProvider.connect() await newProvider.connect()
this.providers.set(config.id, newProvider) this.providers.set(config.id, newProvider)
this.setupNewMailListener(config.id, newProvider) this.setupNewMailListener(config.id, newProvider)
this.mailIndexer?.onAccountConnected(config.id, configWithCreds).catch((err) => {
console.warn(`[AccountManager] index sync failed for ${config.id}:`, (err as Error).message)
})
} }
return { success: true } return { success: true }
@ -408,6 +417,7 @@ export class AccountManager {
private setupNewMailListener(accountId: string, provider: IEmailProvider): void { private setupNewMailListener(accountId: string, provider: IEmailProvider): void {
provider.onNewMail((folderId, envelope) => { provider.onNewMail((folderId, envelope) => {
this.mailIndexer?.indexEnvelope(accountId, envelope)
if (this.mainWindow && !this.mainWindow.isDestroyed()) { if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope }) this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
} }

View file

@ -0,0 +1,220 @@
import { ImapFlow } from 'imapflow'
import type { BrowserWindow } from 'electron'
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
import type { MessageEnvelope } from '@shared/types/message'
import type { IndexSyncStatus } from '@shared/types/search-index'
import { convertImapMessage } from '../lib/imap-message-mapper'
import { SearchIndexStore } from './search-index-store'
interface ImapMailboxNode {
name: string
path: string
folders?: ImapMailboxNode[]
}
const FETCH_BATCH_SIZE = 500
const PERIODIC_SYNC_INTERVAL_MS = 15 * 60_000
// Держит локальный индекс заголовков писем в актуальном состоянии:
// - при подключении аккаунта — полная синхронизация (если индекса ещё нет) либо дифф-синхронизация
// - на новое письмо (onNewMail в AccountManager) — точечная индексация без похода по всей папке
// - на удаление (messages:delete, retention) — точечное удаление из индекса
// - раз в PERIODIC_SYNC_INTERVAL_MS — фоновая дифф-синхронизация всех подключённых аккаунтов
// (подстраховка: внешние действия в другом почтовом клиенте, пропущенные события и т.п.)
export class MailIndexer {
private store = new SearchIndexStore()
private accounts = new Map<string, AccountConfig>()
private syncing = new Set<string>()
private progress = new Map<string, IndexSyncStatus>()
private periodicTimer: ReturnType<typeof setInterval> | null = null
private mainWindow: BrowserWindow | null = null
setMainWindow(win: BrowserWindow): void {
this.mainWindow = win
}
startPeriodicSync(): void {
if (this.periodicTimer) return
this.periodicTimer = setInterval(() => {
for (const [accountId, config] of this.accounts) {
if (this.syncing.has(accountId)) continue
this.differentialSync(accountId, config).catch((err) => {
console.warn(`[MailIndexer] periodic sync failed for ${accountId}:`, (err as Error).message)
})
}
}, PERIODIC_SYNC_INTERVAL_MS)
}
dispose(): void {
if (this.periodicTimer) {
clearInterval(this.periodicTimer)
this.periodicTimer = null
}
}
async onAccountConnected(accountId: string, config: AccountConfig): Promise<void> {
this.accounts.set(accountId, config)
if (this.syncing.has(accountId)) return
await this.store.load(accountId)
if (this.store.hasData(accountId)) {
await this.differentialSync(accountId, config)
} else {
await this.fullSync(accountId, config)
}
}
removeAccount(accountId: string): void {
this.accounts.delete(accountId)
this.progress.delete(accountId)
this.store.removeAccount(accountId)
}
async search(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
await this.store.load(accountId)
return this.store.search(accountId, query, limit)
}
async getStatus(accountId: string): Promise<IndexSyncStatus> {
await this.store.load(accountId)
const cached = this.progress.get(accountId)
if (cached) return cached
const stats = this.store.getStats(accountId)
return { accountId, state: stats.indexed > 0 ? 'ready' : 'idle', indexed: stats.indexed, total: stats.indexed }
}
// Индексирует одно только что пришедшее письмо — без похода по всей папке
indexEnvelope(accountId: string, envelope: MessageEnvelope): void {
this.store.upsertMany(accountId, [envelope])
}
removeMessages(accountId: string, folderId: string, uids: string[]): void {
this.store.remove(accountId, folderId, uids)
}
private async fullSync(accountId: string, config: AccountConfig): Promise<void> {
this.syncing.add(accountId)
this.updateProgress(accountId, { state: 'syncing', indexed: 0, total: 0 })
const client = this.createClient(config)
try {
await client.connect()
const folders = await this.listFolderPaths(client)
const totals = new Map<string, number>()
let total = 0
for (const path of folders) {
const status = await client.status(path, { messages: true }) as { messages?: number } | null
const count = status?.messages ?? 0
totals.set(path, count)
total += count
}
this.updateProgress(accountId, { state: 'syncing', indexed: 0, total })
let indexed = 0
for (const path of folders) {
const count = totals.get(path) ?? 0
if (count === 0) continue
const lock = await client.getMailboxLock(path)
try {
for (let start = 1; start <= count; start += FETCH_BATCH_SIZE) {
const end = Math.min(start + FETCH_BATCH_SIZE - 1, count)
const batch: MessageEnvelope[] = []
for await (const msg of client.fetch(`${start}:${end}`, {
uid: true, envelope: true, flags: true, bodyStructure: true
})) {
batch.push(convertImapMessage(msg, path))
}
this.store.upsertMany(accountId, batch)
indexed += batch.length
this.updateProgress(accountId, { state: 'syncing', indexed, total })
}
} finally {
lock.release()
}
}
await this.store.flush(accountId)
this.updateProgress(accountId, { state: 'ready', indexed, total })
} catch (err) {
this.updateProgress(accountId, { state: 'error', indexed: 0, total: 0, error: (err as Error).message })
} finally {
this.syncing.delete(accountId)
await client.logout().catch(() => {})
}
}
// Лёгкая синхронизация: SEARCH ALL по каждой папке (без фильтра по содержимому — этому критерию
// серверы не отказывают в поддержке), сравниваем с уже проиндексированными UID и подтягиваем/
// удаляем только разницу. Ловит и новые письма, и удалённые/перемещённые внешними клиентами.
private async differentialSync(accountId: string, config: AccountConfig): Promise<void> {
this.syncing.add(accountId)
const client = this.createClient(config)
try {
await client.connect()
const folders = await this.listFolderPaths(client)
for (const path of folders) {
const lock = await client.getMailboxLock(path)
try {
const raw = await client.search({ all: true }, { uid: true })
const serverUids = new Set((Array.isArray(raw) ? raw : []).map(String))
const indexedUids = this.store.getFolderUidSet(accountId, path)
const missing = [...serverUids].filter((uid) => !indexedUids.has(uid))
const stale = [...indexedUids].filter((uid) => !serverUids.has(uid))
if (stale.length) this.store.remove(accountId, path, stale)
if (missing.length) {
const batch: MessageEnvelope[] = []
for await (const msg of client.fetch(missing.join(','), {
uid: true, envelope: true, flags: true, bodyStructure: true
}, { uid: true })) {
batch.push(convertImapMessage(msg, path))
}
this.store.upsertMany(accountId, batch)
}
} finally {
lock.release()
}
}
await this.store.flush(accountId)
const stats = this.store.getStats(accountId)
this.updateProgress(accountId, { state: 'ready', indexed: stats.indexed, total: stats.indexed })
} catch (err) {
console.warn(`[MailIndexer] differential sync failed for ${accountId}:`, (err as Error).message)
} finally {
this.syncing.delete(accountId)
await client.logout().catch(() => {})
}
}
private async listFolderPaths(client: ImapFlow): Promise<string[]> {
const tree = await client.listTree() as { folders?: ImapMailboxNode[] }
const flatten = (nodes: ImapMailboxNode[]): string[] =>
nodes.flatMap((n) => [n.path, ...flatten(n.folders ?? [])])
return flatten(tree.folders ?? [])
}
private createClient(config: AccountConfig): ImapFlow {
const creds = config.credentials as ImapCredentials
return new ImapFlow({
host: creds.host,
port: creds.port,
secure: creds.secure,
auth: { user: creds.username, pass: creds.password },
logger: false
})
}
private updateProgress(accountId: string, partial: Omit<IndexSyncStatus, 'accountId'>): void {
const status: IndexSyncStatus = { accountId, ...partial }
this.progress.set(accountId, status)
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('search:indexProgress', status)
}
}
}

View file

@ -3,12 +3,14 @@ import { join } from 'node:path'
import type { BrowserWindow } from 'electron' import type { BrowserWindow } from 'electron'
import type { FolderRetentionRule } from '@shared/types/retention' import type { FolderRetentionRule } from '@shared/types/retention'
import type { AccountManager } from './account-manager' import type { AccountManager } from './account-manager'
import type { MailIndexer } from './mail-indexer'
import { RetentionStore } from './retention-store' import { RetentionStore } from './retention-store'
export class RetentionService { export class RetentionService {
private worker: Worker private worker: Worker
private store = new RetentionStore() private store = new RetentionStore()
private mainWindow: BrowserWindow | null = null private mainWindow: BrowserWindow | null = null
private mailIndexer: MailIndexer | null = null
private checking = false private checking = false
constructor(private accountManager: AccountManager) { constructor(private accountManager: AccountManager) {
@ -29,6 +31,10 @@ export class RetentionService {
this.mainWindow = win this.mainWindow = win
} }
setMailIndexer(indexer: MailIndexer): void {
this.mailIndexer = indexer
}
setCheckInterval(minutes: number): void { setCheckInterval(minutes: number): void {
this.worker.postMessage({ type: 'setInterval', intervalMinutes: minutes }) this.worker.postMessage({ type: 'setInterval', intervalMinutes: minutes })
} }
@ -65,6 +71,9 @@ export class RetentionService {
try { try {
const results = await this.accountManager.enforceRetention(accountId, rules) const results = await this.accountManager.enforceRetention(accountId, rules)
const cleaned = results.filter((r) => r.deletedCount > 0) const cleaned = results.filter((r) => r.deletedCount > 0)
for (const result of cleaned) {
this.mailIndexer?.removeMessages(accountId, result.folderId, result.deletedUids)
}
if (cleaned.length > 0 && this.mainWindow && !this.mainWindow.isDestroyed()) { if (cleaned.length > 0 && this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('retention:cleaned', { accountId, results: cleaned }) this.mainWindow.webContents.send('retention:cleaned', { accountId, results: cleaned })
} }

View file

@ -0,0 +1,161 @@
import { app } from 'electron'
import { existsSync, mkdirSync } from 'node:fs'
import { readFile, writeFile, unlink } from 'node:fs/promises'
import { join } from 'node:path'
import type { MessageEnvelope, Address } from '@shared/types/message'
// Поле, к которому сужен поиск через префикс "from:"/"to:"/"cc:"/"subject:" (null — по всем сразу)
export type SearchField = 'from' | 'to' | 'cc' | 'subject'
export interface SearchQuery {
field: SearchField | null
term: string
}
export function parseSearchQuery(raw: string): SearchQuery {
const match = raw.match(/^\s*(from|to|cc|subject)\s*:\s*(.+)$/i)
if (!match) return { field: null, term: raw.trim() }
return { field: match[1].toLowerCase() as SearchField, term: match[2].trim() }
}
const SAVE_DEBOUNCE_MS = 2000
// Локальный индекс заголовков писем (без тела) — one file per account в userData,
// в памяти держим Map для мгновенного поиска. Так поиск работает по всей истории
// письма и не зависит от корректности серверного IMAP SEARCH.
export class SearchIndexStore {
// accountId → (folderId + ':' + uid) → письмо
private indices = new Map<string, Map<string, MessageEnvelope>>()
private saveTimers = new Map<string, ReturnType<typeof setTimeout>>()
private dir: string
constructor() {
this.dir = join(app.getPath('userData'), 'search-index')
}
async load(accountId: string): Promise<void> {
if (this.indices.has(accountId)) return
const map = new Map<string, MessageEnvelope>()
this.indices.set(accountId, map)
try {
const raw = await readFile(this.filePath(accountId), 'utf-8')
const messages = JSON.parse(raw) as MessageEnvelope[]
for (const msg of messages) {
map.set(this.key(msg.folderId, msg.id), msg)
}
} catch {
// индекса ещё нет — начинаем с пустого
}
}
hasData(accountId: string): boolean {
return (this.indices.get(accountId)?.size ?? 0) > 0
}
getStats(accountId: string): { indexed: number } {
return { indexed: this.indices.get(accountId)?.size ?? 0 }
}
getFolderUidSet(accountId: string, folderId: string): Set<string> {
const result = new Set<string>()
const map = this.indices.get(accountId)
if (!map) return result
for (const msg of map.values()) {
if (msg.folderId === folderId) result.add(msg.id)
}
return result
}
upsertMany(accountId: string, messages: MessageEnvelope[]): void {
if (messages.length === 0) return
const map = this.indices.get(accountId) ?? new Map<string, MessageEnvelope>()
this.indices.set(accountId, map)
for (const msg of messages) {
map.set(this.key(msg.folderId, msg.id), msg)
}
this.scheduleSave(accountId)
}
remove(accountId: string, folderId: string, uids: string[]): void {
const map = this.indices.get(accountId)
if (!map || uids.length === 0) return
for (const uid of uids) {
map.delete(this.key(folderId, uid))
}
this.scheduleSave(accountId)
}
removeAccount(accountId: string): void {
this.indices.delete(accountId)
const timer = this.saveTimers.get(accountId)
if (timer) {
clearTimeout(timer)
this.saveTimers.delete(accountId)
}
unlink(this.filePath(accountId)).catch(() => {})
}
search(accountId: string, rawQuery: string, limit: number): MessageEnvelope[] {
const map = this.indices.get(accountId)
if (!map) return []
const query = parseSearchQuery(rawQuery)
if (!query.term) return []
const lowerTerm = query.term.toLowerCase()
const matches: MessageEnvelope[] = []
for (const msg of map.values()) {
if (this.matches(msg, query.field, lowerTerm)) matches.push(msg)
}
matches.sort((a, b) => (a.date < b.date ? 1 : -1))
return matches.slice(0, limit)
}
async flush(accountId: string): Promise<void> {
const timer = this.saveTimers.get(accountId)
if (timer) {
clearTimeout(timer)
this.saveTimers.delete(accountId)
}
await this.persist(accountId)
}
private matches(msg: MessageEnvelope, field: SearchField | null, lowerTerm: string): boolean {
const matchesAddress = (addr: Address): boolean =>
addr.name.toLowerCase().includes(lowerTerm) || addr.email.toLowerCase().includes(lowerTerm)
const matchesAddressList = (list: Address[]): boolean => list.some(matchesAddress)
const matchesSubject = (): boolean => msg.subject.toLowerCase().includes(lowerTerm)
switch (field) {
case 'from': return matchesAddress(msg.from)
case 'to': return matchesAddressList(msg.to)
case 'cc': return matchesAddressList(msg.cc)
case 'subject': return matchesSubject()
default:
return matchesSubject() || matchesAddress(msg.from) || matchesAddressList(msg.to) || matchesAddressList(msg.cc)
}
}
private scheduleSave(accountId: string): void {
const existing = this.saveTimers.get(accountId)
if (existing) clearTimeout(existing)
const timer = setTimeout(() => {
this.saveTimers.delete(accountId)
this.persist(accountId).catch((err) => console.warn('[SearchIndexStore] save failed:', err))
}, SAVE_DEBOUNCE_MS)
this.saveTimers.set(accountId, timer)
}
private async persist(accountId: string): Promise<void> {
const map = this.indices.get(accountId)
if (!map) return
if (!existsSync(this.dir)) mkdirSync(this.dir, { recursive: true })
await writeFile(this.filePath(accountId), JSON.stringify([...map.values()]), 'utf-8')
}
private filePath(accountId: string): string {
return join(this.dir, `${accountId}.json`)
}
private key(folderId: string, uid: string): string {
return `${folderId}:${uid}`
}
}

View file

@ -62,6 +62,10 @@ function onSearchKeydown(e: KeyboardEvent): void {
async function selectSearchResult(envelope: MessageEnvelope): Promise<void> { async function selectSearchResult(envelope: MessageEnvelope): Promise<void> {
foldersStore.setActiveFolder(envelope.folderId) foldersStore.setActiveFolder(envelope.folderId)
// Смена activeFolderId запускает watcher в messages.store, который сбрасывает
// selectedMessageId/messageBody (обычная навигация по папкам). Ждём его отработки —
// иначе он затирает выбор письма, который мы выставляем ниже, и превью не открывается.
await nextTick()
await messagesStore.selectMessage(envelope.id) await messagesStore.selectMessage(envelope.id)
} }
@ -94,6 +98,15 @@ onUnmounted(() => {
if (searchDebounce) clearTimeout(searchDebounce) if (searchDebounce) clearTimeout(searchDebounce)
}) })
const isIndexBuilding = computed(() => messagesStore.indexStatus?.state === 'syncing')
const indexProgressText = computed(() => {
const status = messagesStore.indexStatus
if (!status || status.state !== 'syncing') return ''
return status.total > 0
? `Идёт индексация писем: ${status.indexed} из ${status.total}`
: 'Идёт индексация писем…'
})
const folderName = computed(() => foldersStore.activeFolder?.name ?? '') const folderName = computed(() => foldersStore.activeFolder?.name ?? '')
const hasSelected = computed(() => messagesStore.selectedIds.size > 0) const hasSelected = computed(() => messagesStore.selectedIds.size > 0)
const activeUnread = computed(() => { const activeUnread = computed(() => {
@ -401,13 +414,18 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
:class="{ 'search-pill--open': searchOpen }" :class="{ 'search-pill--open': searchOpen }"
@click="!searchOpen && openSearch()" @click="!searchOpen && openSearch()"
> >
<span class="search-pill-icon"> <span
class="search-pill-icon"
v-tooltip="isIndexBuilding
? indexProgressText + ' — результаты пока могут быть неполными'
: 'Поиск по теме/отправителю/получателю. Сузить: from:, to:, cc:, subject:'"
>
<AppIcon name="search" :size="13" /> <AppIcon name="search" :size="13" />
</span> </span>
<input <input
ref="searchInputEl" ref="searchInputEl"
class="search-pill-input" class="search-pill-input"
placeholder="Поиск по письмам..." placeholder="Поиск (from:, to:, subject:)"
v-model="localSearchQuery" v-model="localSearchQuery"
tabindex="-1" tabindex="-1"
@keydown="onSearchKeydown" @keydown="onSearchKeydown"
@ -448,6 +466,10 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
<!-- Результаты поиска --> <!-- Результаты поиска -->
<template v-if="messagesStore.isSearchActive"> <template v-if="messagesStore.isSearchActive">
<div v-if="isIndexBuilding" class="index-progress-banner">
<div class="spinner-sm" />
<span>{{ indexProgressText }} — результаты пока могут быть неполными</span>
</div>
<div v-if="messagesStore.searchLoading && messagesStore.searchResults.length === 0" class="loading-state"> <div v-if="messagesStore.searchLoading && messagesStore.searchResults.length === 0" class="loading-state">
<div class="spinner" /> <div class="spinner" />
<span>Поиск...</span> <span>Поиск...</span>
@ -1283,6 +1305,26 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
letter-spacing: 0.02em; letter-spacing: 0.02em;
} }
.index-progress-banner {
display: flex;
align-items: center;
gap: 8px;
margin: 6px 8px 0;
padding: 8px 12px;
border-radius: 10px;
font-size: 11.5px;
color: var(--text-secondary);
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.08);
}
html[data-design='material3'] .index-progress-banner {
background: var(--md-sys-color-surface-container);
border: 1px solid var(--md-sys-color-outline-variant);
border-radius: var(--md-sys-shape-corner-small);
color: var(--md-sys-color-on-surface-variant);
}
.search-result-item { .search-result-item {
margin: 2px 5px; margin: 2px 5px;
padding: 9px 11px 8px; padding: 9px 11px 8px;

View file

@ -40,6 +40,10 @@ const ownRetentionRule = computed(() => {
if (!accountsStore.activeAccountId) return null if (!accountsStore.activeAccountId) return null
return retentionStore.getOwnRule(accountsStore.activeAccountId, props.folder.id) return retentionStore.getOwnRule(accountsStore.activeAccountId, props.folder.id)
}) })
const effectiveRetentionRule = computed(() => {
if (!accountsStore.activeAccountId) return null
return retentionStore.getEffectiveRule(accountsStore.activeAccountId, props.folder.id)
})
const folderIcon = computed((): IconName => { const folderIcon = computed((): IconName => {
switch (props.folder.role) { switch (props.folder.role) {
@ -132,6 +136,13 @@ function handleSaveRetention(maxMessages: number, recursive: boolean): void {
<span v-else class="expand-spacer" /> <span v-else class="expand-spacer" />
<AppIcon :name="folderIcon" :size="14" class="folder-icon" /> <AppIcon :name="folderIcon" :size="14" class="folder-icon" />
<span
v-if="effectiveRetentionRule"
class="retention-icon-wrap"
:title="`Хранится последних сообщений: ${effectiveRetentionRule.maxMessages}`"
>
<AppIcon name="trash" :size="14" class="retention-icon" />
</span>
<span class="folder-name truncate">{{ folder.name }}</span> <span class="folder-name truncate">{{ folder.name }}</span>
<AppIcon v-if="isMuted" name="bell-off" :size="11" class="muted-icon" /> <AppIcon v-if="isMuted" name="bell-off" :size="11" class="muted-icon" />
<span v-if="unreadCount > 0" class="unread-badge" :class="{ muted: isMuted }"> <span v-if="unreadCount > 0" class="unread-badge" :class="{ muted: isMuted }">
@ -224,6 +235,18 @@ function handleSaveRetention(maxMessages: number, recursive: boolean): void {
transition: color var(--transition-fast); transition: color var(--transition-fast);
} }
/* ── Иконка «включена очистка» — яркая корзина рядом с иконкой папки ── */
.retention-icon-wrap {
display: inline-flex;
flex-shrink: 0;
}
.retention-icon {
flex-shrink: 0;
color: var(--danger);
filter: drop-shadow(0 0 4px color-mix(in srgb, var(--danger) 55%, transparent));
}
.folder-item:hover .folder-icon { .folder-item:hover .folder-icon {
color: var(--text-secondary); color: var(--text-secondary);
} }
@ -368,6 +391,11 @@ html[data-design='material3'] .folder-item.active .folder-icon {
color: var(--md-sys-color-on-secondary-container); color: var(--md-sys-color-on-secondary-container);
} }
html[data-design='material3'] .retention-icon {
color: var(--md-sys-color-error);
filter: none;
}
html[data-design='material3'] .folder-name { html[data-design='material3'] .folder-name {
font-size: var(--md-sys-typescale-label-large-size); font-size: var(--md-sys-typescale-label-large-size);
line-height: var(--md-sys-typescale-label-large-line); line-height: var(--md-sys-typescale-label-large-line);

View file

@ -1,6 +1,7 @@
import { ref, computed, watch } from 'vue' import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import type { MessageEnvelope, MessageBody } from '@shared/types/message' import type { MessageEnvelope, MessageBody } from '@shared/types/message'
import type { IndexSyncStatus } from '@shared/types/search-index'
import { useAccountsStore } from './accounts.store' import { useAccountsStore } from './accounts.store'
import { useFoldersStore } from './folders.store' import { useFoldersStore } from './folders.store'
import { useIpc } from '../composables/useIpc' import { useIpc } from '../composables/useIpc'
@ -62,6 +63,29 @@ export const useMessagesStore = defineStore('messages', () => {
const searchLoading = ref(false) const searchLoading = ref(false)
const isSearchActive = computed(() => searchQuery.value.trim().length > 0) const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
// Состояние локального индекса писем (см. MailIndexer) — используется для показа
// прогресса первичной синхронизации в UI поиска
const indexStatus = ref<IndexSyncStatus | null>(null)
async function refreshIndexStatus(accountId: string): Promise<void> {
indexStatus.value = await invoke('search:status', { accountId })
}
on('search:indexProgress', (status) => {
if (status.accountId === accountsStore.activeAccountId) {
indexStatus.value = status
}
})
watch(
() => accountsStore.activeAccountId,
(accountId) => {
if (accountId) refreshIndexStatus(accountId)
else indexStatus.value = null
},
{ immediate: true }
)
const filteredMessages = computed(() => const filteredMessages = computed(() =>
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
) )
@ -388,8 +412,14 @@ export const useMessagesStore = defineStore('messages', () => {
} }
) )
// Поиск теперь может выполняться заметно дольше (полный обход папок с фолбэком),
// поэтому старый запрос может завершиться позже нового и затереть его результат —
// применяем ответ только если это всё ещё самый свежий запрос
let searchRequestSeq = 0
async function search(query: string): Promise<void> { async function search(query: string): Promise<void> {
searchQuery.value = query searchQuery.value = query
const requestId = ++searchRequestSeq
if (!query.trim()) { if (!query.trim()) {
searchResults.value = [] searchResults.value = []
return return
@ -402,12 +432,14 @@ export const useMessagesStore = defineStore('messages', () => {
query: query.trim(), query: query.trim(),
limit: 50 limit: 50
}) })
if (requestId !== searchRequestSeq) return
searchResults.value = Array.isArray(results) ? results : [] searchResults.value = Array.isArray(results) ? results : []
} catch (e) { } catch (e) {
if (requestId !== searchRequestSeq) return
console.error('[search] invoke error:', e) console.error('[search] invoke error:', e)
searchResults.value = [] searchResults.value = []
} finally { } finally {
searchLoading.value = false if (requestId === searchRequestSeq) searchLoading.value = false
} }
} }
@ -444,6 +476,7 @@ export const useMessagesStore = defineStore('messages', () => {
searchResults, searchResults,
searchLoading, searchLoading,
isSearchActive, isSearchActive,
indexStatus,
search, search,
clearSearch, clearSearch,
loadMessages, loadMessages,

View file

@ -3,6 +3,7 @@ import type { FolderListResult, MessageListResult } from './provider'
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, ComposeSession } from './message' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, ComposeSession } from './message'
import type { CalendarInfo, CalendarEvent } from './calendar' import type { CalendarInfo, CalendarEvent } from './calendar'
import type { FolderRetentionRule, RetentionCleanupResult } from './retention' import type { FolderRetentionRule, RetentionCleanupResult } from './retention'
import type { IndexSyncStatus } from './search-index'
export interface IpcChannelMap { export interface IpcChannelMap {
'accounts:list': [void, AccountConfig[]] 'accounts:list': [void, AccountConfig[]]
@ -73,6 +74,8 @@ export interface IpcChannelMap {
'retention:set': [FolderRetentionRule, void] 'retention:set': [FolderRetentionRule, void]
'retention:remove': [{ accountId: string; folderId: string }, void] 'retention:remove': [{ accountId: string; folderId: string }, void]
'retention:setCheckInterval': [{ minutes: number }, void] 'retention:setCheckInterval': [{ minutes: number }, void]
'search:status': [{ accountId: string }, IndexSyncStatus]
} }
export interface IpcEventMap { export interface IpcEventMap {
@ -85,6 +88,7 @@ export interface IpcEventMap {
'update:downloaded': Record<string, never> 'update:downloaded': Record<string, never>
'update:error': { error: string } 'update:error': { error: string }
'retention:cleaned': { accountId: string; results: RetentionCleanupResult[] } 'retention:cleaned': { accountId: string; results: RetentionCleanupResult[] }
'search:indexProgress': IndexSyncStatus
} }
export type IpcChannel = keyof IpcChannelMap export type IpcChannel = keyof IpcChannelMap

View file

@ -33,7 +33,6 @@ export interface IEmailProvider {
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
offNewMail(): void offNewMail(): void
pollNewMessages(): Promise<void> pollNewMessages(): Promise<void>
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
sendMessage(compose: ComposeData): Promise<void> sendMessage(compose: ComposeData): Promise<void>
enforceRetention(rules: FolderRetentionRule[]): Promise<RetentionCleanupResult[]> enforceRetention(rules: FolderRetentionRule[]): Promise<RetentionCleanupResult[]>
} }

View file

@ -11,4 +11,5 @@ export interface FolderRetentionRule {
export interface RetentionCleanupResult { export interface RetentionCleanupResult {
folderId: string folderId: string
deletedCount: number deletedCount: number
deletedUids: string[]
} }

View file

@ -0,0 +1,9 @@
export type IndexSyncState = 'idle' | 'syncing' | 'ready' | 'error'
export interface IndexSyncStatus {
accountId: string
state: IndexSyncState
indexed: number
total: number
error?: string
}