parent
8917aba6d0
commit
bb25b0616d
6 changed files with 180 additions and 54 deletions
21
CLAUDE.md
21
CLAUDE.md
|
|
@ -1,5 +1,26 @@
|
|||
# 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
|
||||
|
||||
Electron 35 + Vue 3 Composition API + Pinia + TypeScript + electron-vite.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,18 @@ import { join, extname, basename } from 'path'
|
|||
import { registerHandler } from './registry'
|
||||
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> {
|
||||
const ext = extname(filename)
|
||||
const base = basename(filename, ext)
|
||||
|
|
@ -30,14 +42,18 @@ function sendProgress(attachmentId: string, stage: 'downloading' | 'saving' | 'd
|
|||
|
||||
export function registerMessageHandlers(manager: AccountManager): void {
|
||||
registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
assertId(folderId, 'folderId')
|
||||
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
|
||||
})
|
||||
|
||||
registerHandler('messages:poll', async ({ accountId }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
await manager.pollNewMessages(accountId)
|
||||
})
|
||||
|
||||
registerHandler('messages:send', async ({ accountId, compose }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
try {
|
||||
await manager.sendMessage(accountId, compose)
|
||||
return { success: true }
|
||||
|
|
@ -47,18 +63,28 @@ export function registerMessageHandlers(manager: AccountManager): void {
|
|||
})
|
||||
|
||||
registerHandler('messages:search', async ({ accountId, query, limit }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
return manager.searchMessages(accountId, query, limit)
|
||||
})
|
||||
|
||||
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
assertId(folderId, 'folderId')
|
||||
assertId(messageId, 'messageId')
|
||||
return manager.fetchMessageBody(accountId, folderId, messageId)
|
||||
})
|
||||
|
||||
registerHandler('messages:setFlags', async ({ accountId, folderId, messageIds, flags }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
assertId(folderId, 'folderId')
|
||||
assertIds(messageIds, 'messageIds')
|
||||
await manager.updateFlags(accountId, folderId, messageIds, flags)
|
||||
})
|
||||
|
||||
registerHandler('messages:delete', async ({ accountId, folderId, messageIds }) => {
|
||||
assertId(accountId, 'accountId')
|
||||
assertId(folderId, 'folderId')
|
||||
assertIds(messageIds, 'messageIds')
|
||||
await manager.deleteMessages(accountId, folderId, messageIds)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -55,10 +55,19 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.client.connect(), timeout])
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
})
|
||||
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
|
||||
// Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке
|
||||
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> {
|
||||
// TODO: имапфлоу поддерживает частичный download по part-номеру из BODYSTRUCTURE
|
||||
// (client.download(uid, '2', {uid:true})). Оптимизация требует хранить part в Attachment.id
|
||||
// и пробрасывать через IPC. Сейчас скачивается всё письмо целиком.
|
||||
const lock = await this.client.getMailboxLock(folderId)
|
||||
try {
|
||||
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
|
||||
: undefined
|
||||
|
||||
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
|
||||
smtpHost, smtpPort, smtpSecure, from, compose.to)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
|
||||
smtpHost, smtpPort, smtpSecure, from, compose.to)
|
||||
}
|
||||
|
||||
const info = await transporter.sendMail({
|
||||
from,
|
||||
|
|
|
|||
|
|
@ -83,13 +83,14 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
async testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
const provider = this.createProvider(config)
|
||||
try {
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
await provider.disconnect()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message }
|
||||
} finally {
|
||||
provider.disconnect().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -275,21 +276,23 @@ export class AccountManager {
|
|||
// ── Auto-reconnect ──────────────────────────────────────
|
||||
|
||||
private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
|
||||
let originalError: unknown
|
||||
try {
|
||||
return await fn()
|
||||
} catch (err) {
|
||||
originalError = err
|
||||
const code = (err as { code?: string }).code ?? ''
|
||||
if (!RECONNECT_CODES.has(code)) throw err
|
||||
|
||||
try {
|
||||
await this.reconnectAccount(accountId)
|
||||
} catch (reconnectErr) {
|
||||
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
|
||||
throw reconnectErr
|
||||
}
|
||||
|
||||
return await fn()
|
||||
}
|
||||
|
||||
try {
|
||||
await this.reconnectAccount(accountId)
|
||||
} catch (reconnectErr) {
|
||||
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
|
||||
throw new Error(`Reconnect failed: ${(reconnectErr as Error).message}`, { cause: originalError })
|
||||
}
|
||||
|
||||
return await fn()
|
||||
}
|
||||
|
||||
private async reconnectAccount(accountId: string): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
<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 { formatFullDate } from '../../utils/date'
|
||||
import AppIcon from '../AppIcon.vue'
|
||||
|
|
@ -47,6 +47,27 @@ function handleForward(): void {
|
|||
|
||||
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 ──────────────────────────────────────────
|
||||
|
||||
const activeContact = ref<Address | null>(null)
|
||||
|
|
@ -129,13 +150,27 @@ onUnmounted(() => {
|
|||
<span class="label">Кому:</span>
|
||||
<span class="value addr-list">
|
||||
<button
|
||||
v-for="addr in message.to"
|
||||
v-for="addr in visibleTo"
|
||||
:key="addr.email"
|
||||
class="addr-chip"
|
||||
@click="openContact(addr, $event)"
|
||||
>
|
||||
<span class="addr-name">{{ addr.name || addr.email }}</span>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
|
|
@ -144,13 +179,27 @@ onUnmounted(() => {
|
|||
<span class="label">Копия:</span>
|
||||
<span class="value addr-list">
|
||||
<button
|
||||
v-for="addr in message.cc"
|
||||
v-for="addr in visibleCc"
|
||||
:key="addr.email"
|
||||
class="addr-chip"
|
||||
@click="openContact(addr, $event)"
|
||||
>
|
||||
<span class="addr-name">{{ addr.name || addr.email }}</span>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
|
|
@ -369,6 +418,19 @@ onUnmounted(() => {
|
|||
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 {
|
||||
position: absolute;
|
||||
|
|
|
|||
|
|
@ -62,24 +62,6 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
const searchLoading = ref(false)
|
||||
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(() =>
|
||||
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
|
||||
)
|
||||
|
|
@ -96,7 +78,6 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
})
|
||||
|
||||
if (offset === 0) {
|
||||
detectNewMessages(accountId, folderId, result.messages)
|
||||
messages.value = result.messages
|
||||
if (unreadOnly.value) {
|
||||
// result.total — это точное число непрочитанных из SEARCH UNSEEN
|
||||
|
|
@ -110,7 +91,11 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
|
||||
// Предзагрузка тел первых 10 писем в фоне (только в обычном режиме)
|
||||
if (!unreadOnly.value) {
|
||||
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
|
||||
if ('requestIdleCallback' in window) {
|
||||
requestIdleCallback(() => prefetchBodies(accountId, folderId, 10), { timeout: 3000 })
|
||||
} else {
|
||||
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
messages.value.push(...result.messages)
|
||||
|
|
@ -126,17 +111,21 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
.slice(0, count)
|
||||
.filter((m) => !getCachedBody(`${accountId}:${folderId}:${m.id}`))
|
||||
|
||||
await Promise.all(
|
||||
toFetch.map(async (msg) => {
|
||||
const key = `${accountId}:${folderId}:${msg.id}`
|
||||
try {
|
||||
const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id })
|
||||
setCachedBody(key, body)
|
||||
} catch {
|
||||
// фоновая предзагрузка — ошибки не критичны
|
||||
}
|
||||
})
|
||||
)
|
||||
// Параллельность ограничена 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(
|
||||
batch.map(async (msg) => {
|
||||
const key = `${accountId}:${folderId}:${msg.id}`
|
||||
try {
|
||||
const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id })
|
||||
setCachedBody(key, body)
|
||||
} catch { /* фоновая предзагрузка — ошибки не критичны */ }
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
|
|
@ -340,7 +329,9 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
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(
|
||||
() => foldersStore.activeFolderId,
|
||||
(folderId) => {
|
||||
|
|
@ -350,8 +341,18 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
messages.value = []
|
||||
totalCount.value = 0
|
||||
unreadOnly.value = false
|
||||
if (folderLoadTimer !== null) {
|
||||
clearTimeout(folderLoadTimer)
|
||||
folderLoadTimer = null
|
||||
}
|
||||
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,
|
||||
loading,
|
||||
loadingBody,
|
||||
newArrivals,
|
||||
searchQuery,
|
||||
searchResults,
|
||||
searchLoading,
|
||||
|
|
|
|||
Loading…
Reference in a new issue