.
Some checks failed
Release / release (push) Failing after 5s

This commit is contained in:
vodyanoysh 2026-04-29 22:41:51 +07:00
parent 8917aba6d0
commit bb25b0616d
6 changed files with 180 additions and 54 deletions

View file

@ -1,5 +1,26 @@
# Aero Mail — Developer Notes # Aero Mail — Developer Notes
## Agent team
Sub-agents live in `.claude/agents/`. Use `claude --agent <name>` or mention the agent in your request.
| Agent | When to use |
|-------|-------------|
| `architect` | **First** for any complex/cross-cutting feature: designs IPC contract, data model, plan — before coding starts |
| `backend` | Main process: IMAP/SMTP, IPC handlers, account-manager, credential-store, CalDAV |
| `frontend` | Renderer: Vue components, Pinia stores, composables, CSS |
| `test` | Vitest setup, writing unit/integration tests |
| `review` | Security audit, code review, performance analysis |
| `devops` | Build, packaging, electron-builder, CI, auto-update |
**Routing heuristic**:
- New feature touching IPC or both processes → `architect` first, then `backend` + `frontend`
- Bug or small change only in `src/main/` → `backend` directly
- Bug or small change only in `src/renderer/` → `frontend` directly
- "write tests / fix tests" → `test`
- "review / audit / check for bugs" → `review`
- "build / package / CI" → `devops`
## Stack ## Stack
Electron 35 + Vue 3 Composition API + Pinia + TypeScript + electron-vite. Electron 35 + Vue 3 Composition API + Pinia + TypeScript + electron-vite.

View file

@ -4,6 +4,18 @@ 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'
function assertId(value: unknown, name: string): asserts value is string {
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`Invalid IPC argument: ${name} must be a non-empty string`)
}
}
function assertIds(value: unknown, name: string): asserts value is string[] {
if (!Array.isArray(value) || value.length === 0 || value.some((v) => typeof v !== 'string')) {
throw new Error(`Invalid IPC argument: ${name} must be a non-empty string array`)
}
}
async function resolveDownloadPath(folder: string, filename: string): Promise<string> { async function resolveDownloadPath(folder: string, filename: string): Promise<string> {
const ext = extname(filename) const ext = extname(filename)
const base = basename(filename, ext) const base = basename(filename, ext)
@ -30,14 +42,18 @@ function sendProgress(attachmentId: string, stage: 'downloading' | 'saving' | 'd
export function registerMessageHandlers(manager: AccountManager): void { export function registerMessageHandlers(manager: AccountManager): void {
registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => { registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
assertId(accountId, 'accountId')
assertId(folderId, 'folderId')
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false) return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
}) })
registerHandler('messages:poll', async ({ accountId }) => { registerHandler('messages:poll', async ({ accountId }) => {
assertId(accountId, 'accountId')
await manager.pollNewMessages(accountId) await manager.pollNewMessages(accountId)
}) })
registerHandler('messages:send', async ({ accountId, compose }) => { registerHandler('messages:send', async ({ accountId, compose }) => {
assertId(accountId, 'accountId')
try { try {
await manager.sendMessage(accountId, compose) await manager.sendMessage(accountId, compose)
return { success: true } return { success: true }
@ -47,18 +63,28 @@ export function registerMessageHandlers(manager: AccountManager): void {
}) })
registerHandler('messages:search', async ({ accountId, query, limit }) => { registerHandler('messages:search', async ({ accountId, query, limit }) => {
assertId(accountId, 'accountId')
return manager.searchMessages(accountId, query, limit) return manager.searchMessages(accountId, query, limit)
}) })
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => { registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
assertId(accountId, 'accountId')
assertId(folderId, 'folderId')
assertId(messageId, 'messageId')
return manager.fetchMessageBody(accountId, folderId, messageId) return manager.fetchMessageBody(accountId, folderId, messageId)
}) })
registerHandler('messages:setFlags', async ({ accountId, folderId, messageIds, flags }) => { registerHandler('messages:setFlags', async ({ accountId, folderId, messageIds, flags }) => {
assertId(accountId, 'accountId')
assertId(folderId, 'folderId')
assertIds(messageIds, 'messageIds')
await manager.updateFlags(accountId, folderId, messageIds, flags) await manager.updateFlags(accountId, folderId, messageIds, flags)
}) })
registerHandler('messages:delete', async ({ accountId, folderId, messageIds }) => { registerHandler('messages:delete', async ({ accountId, folderId, messageIds }) => {
assertId(accountId, 'accountId')
assertId(folderId, 'folderId')
assertIds(messageIds, 'messageIds')
await manager.deleteMessages(accountId, folderId, messageIds) await manager.deleteMessages(accountId, folderId, messageIds)
}) })

View file

@ -55,10 +55,19 @@ export class ImapProvider implements IEmailProvider {
} }
async connect(): Promise<void> { async connect(): Promise<void> {
const timeout = new Promise<never>((_, reject) => let timeoutId: ReturnType<typeof setTimeout> | undefined
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000) const timeoutPromise = new Promise<never>((_, reject) => {
) timeoutId = setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
await Promise.race([this.client.connect(), timeout]) })
try {
await Promise.race([this.client.connect(), timeoutPromise])
} catch (err) {
// Close any socket imapflow opened or is opening (timeout race case)
this.client.logout().catch(() => {})
throw err
} finally {
clearTimeout(timeoutId)
}
this.connected = true this.connected = true
// Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке // Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке
this.senderNamePromise = this.fetchSenderName().catch(() => null) this.senderNamePromise = this.fetchSenderName().catch(() => null)
@ -232,6 +241,9 @@ export class ImapProvider implements IEmailProvider {
} }
async downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise<Buffer> { async downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise<Buffer> {
// TODO: имапфлоу поддерживает частичный download по part-номеру из BODYSTRUCTURE
// (client.download(uid, '2', {uid:true})). Оптимизация требует хранить part в Attachment.id
// и пробрасывать через IPC. Сейчас скачивается всё письмо целиком.
const lock = await this.client.getMailboxLock(folderId) const lock = await this.client.getMailboxLock(folderId)
try { try {
const download = await this.client.download(messageId, undefined, { uid: true }) const download = await this.client.download(messageId, undefined, { uid: true })
@ -318,8 +330,10 @@ export class ImapProvider implements IEmailProvider {
? ImapProvider.textToHtml(compose.body) + compose.htmlBody ? ImapProvider.textToHtml(compose.body) + compose.htmlBody
: undefined : undefined
if (process.env.NODE_ENV !== 'production') {
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j', console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
smtpHost, smtpPort, smtpSecure, from, compose.to) smtpHost, smtpPort, smtpSecure, from, compose.to)
}
const info = await transporter.sendMail({ const info = await transporter.sendMail({
from, from,

View file

@ -83,13 +83,14 @@ export class AccountManager {
} }
async testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> { async testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
try {
const provider = this.createProvider(config) const provider = this.createProvider(config)
try {
await provider.connect() await provider.connect()
await provider.disconnect()
return { success: true } return { success: true }
} catch (error) { } catch (error) {
return { success: false, error: (error as Error).message } return { success: false, error: (error as Error).message }
} finally {
provider.disconnect().catch(() => {})
} }
} }
@ -275,22 +276,24 @@ export class AccountManager {
// ── Auto-reconnect ────────────────────────────────────── // ── Auto-reconnect ──────────────────────────────────────
private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> { private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
let originalError: unknown
try { try {
return await fn() return await fn()
} catch (err) { } catch (err) {
originalError = err
const code = (err as { code?: string }).code ?? '' const code = (err as { code?: string }).code ?? ''
if (!RECONNECT_CODES.has(code)) throw err if (!RECONNECT_CODES.has(code)) throw err
}
try { try {
await this.reconnectAccount(accountId) await this.reconnectAccount(accountId)
} catch (reconnectErr) { } catch (reconnectErr) {
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr) console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
throw reconnectErr throw new Error(`Reconnect failed: ${(reconnectErr as Error).message}`, { cause: originalError })
} }
return await fn() return await fn()
} }
}
private async reconnectAccount(accountId: string): Promise<void> { private async reconnectAccount(accountId: string): Promise<void> {
// Убиваем старый провайдер // Убиваем старый провайдер

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue' import { computed, ref, watch, onMounted, onUnmounted } from 'vue'
import type { MessageEnvelope, Address } from '@shared/types/message' import type { MessageEnvelope, Address } from '@shared/types/message'
import { formatFullDate } from '../../utils/date' import { formatFullDate } from '../../utils/date'
import AppIcon from '../AppIcon.vue' import AppIcon from '../AppIcon.vue'
@ -47,6 +47,27 @@ function handleForward(): void {
const dateDisplay = computed(() => formatFullDate(props.message.date)) const dateDisplay = computed(() => formatFullDate(props.message.date))
// ── Collapse recipients ────────────────────────────────────
const COLLAPSE_THRESHOLD = 10
const toExpanded = ref(false)
const ccExpanded = ref(false)
const visibleTo = computed(() =>
toExpanded.value ? props.message.to : props.message.to.slice(0, COLLAPSE_THRESHOLD)
)
const visibleCc = computed(() =>
ccExpanded.value ? props.message.cc : props.message.cc.slice(0, COLLAPSE_THRESHOLD)
)
const hiddenToCount = computed(() => Math.max(0, props.message.to.length - COLLAPSE_THRESHOLD))
const hiddenCcCount = computed(() => Math.max(0, props.message.cc.length - COLLAPSE_THRESHOLD))
watch(() => props.message.id, () => {
toExpanded.value = false
ccExpanded.value = false
})
// ── Contact popup ────────────────────────────────────────── // ── Contact popup ──────────────────────────────────────────
const activeContact = ref<Address | null>(null) const activeContact = ref<Address | null>(null)
@ -129,13 +150,27 @@ onUnmounted(() => {
<span class="label">Кому:</span> <span class="label">Кому:</span>
<span class="value addr-list"> <span class="value addr-list">
<button <button
v-for="addr in message.to" v-for="addr in visibleTo"
:key="addr.email" :key="addr.email"
class="addr-chip" class="addr-chip"
@click="openContact(addr, $event)" @click="openContact(addr, $event)"
> >
<span class="addr-name">{{ addr.name || addr.email }}</span> <span class="addr-name">{{ addr.name || addr.email }}</span>
</button> </button>
<button
v-if="hiddenToCount > 0 && !toExpanded"
class="addr-chip addr-chip--more"
@click="toExpanded = true"
>
<span class="addr-name">и ещё {{ hiddenToCount }}...</span>
</button>
<button
v-if="toExpanded && message.to.length > COLLAPSE_THRESHOLD"
class="addr-chip addr-chip--more"
@click="toExpanded = false"
>
<span class="addr-name">свернуть</span>
</button>
</span> </span>
</div> </div>
@ -144,13 +179,27 @@ onUnmounted(() => {
<span class="label">Копия:</span> <span class="label">Копия:</span>
<span class="value addr-list"> <span class="value addr-list">
<button <button
v-for="addr in message.cc" v-for="addr in visibleCc"
:key="addr.email" :key="addr.email"
class="addr-chip" class="addr-chip"
@click="openContact(addr, $event)" @click="openContact(addr, $event)"
> >
<span class="addr-name">{{ addr.name || addr.email }}</span> <span class="addr-name">{{ addr.name || addr.email }}</span>
</button> </button>
<button
v-if="hiddenCcCount > 0 && !ccExpanded"
class="addr-chip addr-chip--more"
@click="ccExpanded = true"
>
<span class="addr-name">и ещё {{ hiddenCcCount }}...</span>
</button>
<button
v-if="ccExpanded && message.cc.length > COLLAPSE_THRESHOLD"
class="addr-chip addr-chip--more"
@click="ccExpanded = false"
>
<span class="addr-name">свернуть</span>
</button>
</span> </span>
</div> </div>
@ -369,6 +418,19 @@ onUnmounted(() => {
white-space: nowrap; white-space: nowrap;
} }
.addr-chip--more {
color: var(--text-muted);
font-style: italic;
border-color: rgba(255, 255, 255, 0.07);
background: rgba(255, 255, 255, 0.03);
}
.addr-chip--more:hover {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 10%, transparent);
border-color: color-mix(in srgb, var(--accent) 30%, transparent);
}
/* ── Попап контакта ──────────────────────────────────────── */ /* ── Попап контакта ──────────────────────────────────────── */
.contact-popup { .contact-popup {
position: absolute; position: absolute;

View file

@ -62,24 +62,6 @@ 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)
// Отслеживание новых писем между обновлениями
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)
if (arrived.length > 0) {
newArrivals.value = arrived.map(envelope => ({ accountId, folderId, envelope }))
}
}
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
) )
@ -96,7 +78,6 @@ export const useMessagesStore = defineStore('messages', () => {
}) })
if (offset === 0) { if (offset === 0) {
detectNewMessages(accountId, folderId, result.messages)
messages.value = result.messages messages.value = result.messages
if (unreadOnly.value) { if (unreadOnly.value) {
// result.total — это точное число непрочитанных из SEARCH UNSEEN // result.total — это точное число непрочитанных из SEARCH UNSEEN
@ -110,8 +91,12 @@ export const useMessagesStore = defineStore('messages', () => {
// Предзагрузка тел первых 10 писем в фоне (только в обычном режиме) // Предзагрузка тел первых 10 писем в фоне (только в обычном режиме)
if (!unreadOnly.value) { if (!unreadOnly.value) {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => prefetchBodies(accountId, folderId, 10), { timeout: 3000 })
} else {
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600) setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
} }
}
} else { } else {
messages.value.push(...result.messages) messages.value.push(...result.messages)
} }
@ -126,18 +111,22 @@ export const useMessagesStore = defineStore('messages', () => {
.slice(0, count) .slice(0, count)
.filter((m) => !getCachedBody(`${accountId}:${folderId}:${m.id}`)) .filter((m) => !getCachedBody(`${accountId}:${folderId}:${m.id}`))
// Параллельность ограничена 2 — иначе 10 одновременных mailbox-lock запросов
// блокируют любое взаимодействие пользователя с IMAP на время предзагрузки
const CONCURRENCY = 2
for (let i = 0; i < toFetch.length; i += CONCURRENCY) {
const batch = toFetch.slice(i, i + CONCURRENCY)
await Promise.all( await Promise.all(
toFetch.map(async (msg) => { batch.map(async (msg) => {
const key = `${accountId}:${folderId}:${msg.id}` const key = `${accountId}:${folderId}:${msg.id}`
try { try {
const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id }) const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id })
setCachedBody(key, body) setCachedBody(key, body)
} catch { } catch { /* фоновая предзагрузка — ошибки не критичны */ }
// фоновая предзагрузка — ошибки не критичны
}
}) })
) )
} }
}
async function loadMore(): Promise<void> { async function loadMore(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
@ -340,7 +329,9 @@ export const useMessagesStore = defineStore('messages', () => {
selectedIds.value = new Set() selectedIds.value = new Set()
} }
// Auto-load messages when folder changes // Auto-load messages when folder changes (debounced 150ms — против дребезга при навигации клавишами)
let folderLoadTimer: ReturnType<typeof setTimeout> | null = null
watch( watch(
() => foldersStore.activeFolderId, () => foldersStore.activeFolderId,
(folderId) => { (folderId) => {
@ -350,8 +341,18 @@ export const useMessagesStore = defineStore('messages', () => {
messages.value = [] messages.value = []
totalCount.value = 0 totalCount.value = 0
unreadOnly.value = false unreadOnly.value = false
if (folderLoadTimer !== null) {
clearTimeout(folderLoadTimer)
folderLoadTimer = null
}
if (folderId && accountsStore.activeAccountId) { if (folderId && accountsStore.activeAccountId) {
loadMessages(accountsStore.activeAccountId, folderId) const snapAccountId = accountsStore.activeAccountId
folderLoadTimer = setTimeout(() => {
folderLoadTimer = null
if (foldersStore.activeFolderId === folderId && accountsStore.activeAccountId === snapAccountId) {
loadMessages(snapAccountId, folderId)
}
}, 150)
} }
} }
) )
@ -408,7 +409,6 @@ export const useMessagesStore = defineStore('messages', () => {
messageBody, messageBody,
loading, loading,
loadingBody, loadingBody,
newArrivals,
searchQuery, searchQuery,
searchResults, searchResults,
searchLoading, searchLoading,