diff --git a/server/src/api/v1.ts b/server/src/api/v1.ts index ba0cdbf..de24470 100644 --- a/server/src/api/v1.ts +++ b/server/src/api/v1.ts @@ -52,7 +52,7 @@ const batchAction = z.object({ const threadBatch = z.object({ threadIds: z.array(z.string().min(1)).min(1).max(500), - action: z.enum(['read', 'unread', 'star', 'unstar', 'archive', 'trash', 'delete']), + action: z.enum(['read', 'unread', 'star', 'unstar', 'archive', 'inbox', 'trash', 'delete']), }); const FLAG_ACTIONS = { @@ -73,7 +73,7 @@ async function body(c: { req: { json: () => Promise } }) { return c.req.json().catch(() => ({})); } -const VIEWS = new Set(['inbox', 'important', 'sent', 'starred', 'unread', 'all']); +const VIEWS = new Set(['inbox', 'important', 'sent', 'junk', 'starred', 'unread', 'all']); // 等回复是按会话算的,只给会话列表用 const THREAD_VIEWS = new Set([...VIEWS, 'waiting']); @@ -286,7 +286,7 @@ export const v1Routes = new Hono() let result: object; if (action in FLAG_ACTIONS) result = await setFlags(scope, ids, FLAG_ACTIONS[action as keyof typeof FLAG_ACTIONS]); else { - result = action === 'delete' ? await deleteMessages(scope, ids) : await moveMessages(scope, ids, action as 'archive' | 'trash'); + result = action === 'delete' ? await deleteMessages(scope, ids) : await moveMessages(scope, ids, action as 'archive' | 'inbox' | 'trash'); audit(actorOf(c.var.auth), `messages.${action}`, { detail: { ids, threadIds } }); } return c.json(result); diff --git a/server/src/services/actions.ts b/server/src/services/actions.ts index 129a2f1..8fd7aaa 100644 --- a/server/src/services/actions.ts +++ b/server/src/services/actions.ts @@ -267,11 +267,11 @@ export async function deleteMessages(scope: Scope, ids: number[]) { return { deleted }; } -export type ThreadAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'trash' | 'delete'; +export type ThreadAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'inbox' | 'trash' | 'delete'; /** * 按会话批量操作时,每个会话里实际要处理的邮件,和会话详情页按钮的语义一致: - * 已读处理所有未读;标未读、加星标只处理最新一封;归档只移收件箱里的;删除跳过已在废纸篓的;彻底删除只删废纸篓里的。 + * 已读处理所有未读;标未读、加星标只处理最新一封;归档只移收件箱里的;移回收件箱只移垃圾邮件里的;删除跳过已在废纸篓的;彻底删除只删废纸篓里的。 */ export async function threadMessageIds(scope: Scope, threadIds: string[], action: ThreadAction): Promise { if (!threadIds.length) return []; @@ -318,6 +318,9 @@ export async function threadMessageIds(scope: Scope, threadIds: string[], action case 'archive': ids.push(...list.filter((r) => r.specialUse === '\\Inbox' || r.path.toUpperCase() === 'INBOX').map((r) => r.id)); break; + case 'inbox': + ids.push(...list.filter((r) => r.specialUse === '\\Junk').map((r) => r.id)); + break; case 'trash': ids.push(...list.filter((r) => r.specialUse !== '\\Trash').map((r) => r.id)); break; diff --git a/server/src/services/mail.ts b/server/src/services/mail.ts index 4def646..c16bf54 100644 --- a/server/src/services/mail.ts +++ b/server/src/services/mail.ts @@ -15,7 +15,7 @@ import { completeMessage } from './message-source.js'; /** 访问范围:API Key 可以限定只能看某些账户,null 表示全部 */ export type Scope = { accountIds: number[] | null }; -export type View = 'inbox' | 'important' | 'sent' | 'starred' | 'unread' | 'all' | 'waiting'; +export type View = 'inbox' | 'important' | 'sent' | 'junk' | 'starred' | 'unread' | 'all' | 'waiting'; export type ListOptions = { scope: Scope; @@ -43,6 +43,8 @@ function isInbox() { return sql`(${folders.specialUse} = '\\Inbox' OR upper(${folders.path}) = 'INBOX')`; } +const onlyVerification = (categories: string[]) => categories.length > 0 && categories.every((c) => c === 'verification'); + function buildFilters(opts: ListOptions): SQL[] { const conds: SQL[] = []; const { scope } = opts; @@ -57,7 +59,10 @@ function buildFilters(opts: ListOptions): SQL[] { if (!hasFolderFilter) { if (view === 'inbox' || view === 'important') conds.push(isInbox()); else if (view === 'sent') conds.push(sql`${folders.specialUse} = '\\Sent'`); - // 跨文件夹的视图和搜索不含垃圾箱、垃圾邮件,要看用 folder:trash / folder:junk + else if (view === 'junk') conds.push(sql`${folders.specialUse} = '\\Junk'`); + // 跨文件夹的视图和搜索不含垃圾箱、垃圾邮件,要看用 folder:trash / folder:junk; + // 只看验证码分类时算上垃圾邮件,验证码常被误判进去 + else if (onlyVerification(q.category)) conds.push(sql`coalesce(${folders.specialUse}, '') <> '\\Trash'`); else conds.push(sql`coalesce(${folders.specialUse}, '') NOT IN ('\\Trash', '\\Junk')`); } if (view === 'starred') conds.push(eq(messages.flagged, true)); @@ -594,27 +599,30 @@ export async function getStats(scope: Scope) { `) ).rows : []; - // 各视图的数量,口径和 buildFilters 一致:跨文件夹的视图不含垃圾箱和垃圾邮件 + // 各视图的数量,口径和 buildFilters 一致:跨文件夹的视图不含垃圾箱和垃圾邮件,垃圾邮件单独计数 const [views] = ids.length ? ( - await db.execute<{ unread: string; starred: string; sent: string; total: string }>(sql` - SELECT count(*) FILTER (WHERE NOT m.seen) AS unread, - count(*) FILTER (WHERE m.flagged) AS starred, + await db.execute<{ unread: string; starred: string; sent: string; total: string; junk: string }>(sql` + SELECT count(*) FILTER (WHERE NOT junk AND NOT m.seen) AS unread, + count(*) FILTER (WHERE NOT junk AND m.flagged) AS starred, count(*) FILTER (WHERE f.special_use = '\\Sent') AS sent, - count(*) AS total - FROM messages m JOIN folders f ON f.id = m.folder_id - WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') NOT IN ('\\Trash', '\\Junk') + count(*) FILTER (WHERE NOT junk) AS total, + count(*) FILTER (WHERE junk) AS junk + FROM messages m JOIN folders f ON f.id = m.folder_id, + LATERAL (SELECT coalesce(f.special_use, '') = '\\Junk' AS junk) j + WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') <> '\\Trash' `) ).rows : []; - // AI 分类的数量,口径和点分类进去的列表一致(全部邮件视图,不含垃圾箱和垃圾邮件) + // AI 分类的数量,口径和点分类进去的列表一致(全部邮件视图,不含垃圾箱和垃圾邮件;验证码算上垃圾邮件) const categories = ids.length ? ( await db.execute<{ category: string; total: number; unread: number }>(sql` SELECT i.category, count(*)::int AS total, (count(*) FILTER (WHERE NOT m.seen))::int AS unread FROM messages m JOIN folders f ON f.id = m.folder_id JOIN message_insights i ON i.message_id = m.id - WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') NOT IN ('\\Trash', '\\Junk') + WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') <> '\\Trash' + AND (coalesce(f.special_use, '') <> '\\Junk' OR i.category = 'verification') GROUP BY i.category `) ).rows @@ -650,6 +658,7 @@ export async function getStats(scope: Scope) { unreadTotal: Number(views?.unread ?? 0), starredTotal: Number(views?.starred ?? 0), sentTotal: Number(views?.sent ?? 0), + junkTotal: Number(views?.junk ?? 0), allTotal: Number(views?.total ?? 0), waitingTotal: waiting, // 草稿、待发和发送失败的,不含待审批(单独提醒)和已发送 diff --git a/server/src/services/pipeline.ts b/server/src/services/pipeline.ts index a9e26a6..30e59b6 100644 --- a/server/src/services/pipeline.ts +++ b/server/src/services/pipeline.ts @@ -270,6 +270,9 @@ async function processMessage(m: Message, payload: Record, last } if (payload.analyzeOnly) return result; + // 垃圾邮件里的新邮件只为了不漏掉验证码:不执行规则,也只推送验证码,免得垃圾邮件触发动作、刷屏 + const junk = await inJunk(m.folderId); + // 2. 规则:移动、标记这些动作每个邮箱的副本各自执行;推送按渠道去重,同一封邮件只推一次 const notified = new Set(await notifiedForCopies(copies)); const already = new Set(notified); @@ -280,7 +283,7 @@ async function processMessage(m: Message, payload: Record, last db.query.accounts.findFirst({ columns: { email: true }, where: eq(accounts.id, m.accountId) }), ]); const mailbox = acc?.email; - for (const rule of (await listRules()).filter((r) => r.enabled)) { + for (const rule of junk ? [] : (await listRules()).filter((r) => r.enabled)) { if (!ruleMatches(rule, { message: m, insight, labelIds, knownLabels })) continue; const actions = await runActions(rule, m, insight, notified, mailbox); matched.push(`${rule.name}: ${actions.join(', ')}`); @@ -294,13 +297,15 @@ async function processMessage(m: Message, payload: Record, last if (matched.length) result.rules = matched; // 3. 订阅了事件的渠道:每个渠道只推送一次,取最具体的事件 - const events: EventName[] = ['message.received']; - if (insight?.priority === 'high') events.unshift('message.important'); + const events: EventName[] = junk ? [] : ['message.received']; + if (!junk && insight?.priority === 'high') events.unshift('message.important'); if (insight?.extracted.codes.length) events.unshift('message.verification'); - const subscribed = await db - .select({ id: channels.id, events: channels.events }) - .from(channels) - .where(and(eq(channels.enabled, true), arrayOverlaps(channels.events, events))); + const subscribed = events.length + ? await db + .select({ id: channels.id, events: channels.events }) + .from(channels) + .where(and(eq(channels.enabled, true), arrayOverlaps(channels.events, events))) + : []; for (const ch of subscribed) { if (notified.has(ch.id)) continue; const event = events.find((e) => ch.events.includes(e))!; @@ -318,7 +323,12 @@ async function processMessage(m: Message, payload: Record, last return result; } -/** 同步到新邮件时调用:只处理收件箱里的、近期的邮件(首次回溯和移回收件箱的旧邮件不触发) */ +async function inJunk(folderId: number) { + const f = await db.query.folders.findFirst({ columns: { specialUse: true }, where: eq(folders.id, folderId) }); + return f?.specialUse === '\\Junk'; +} + +/** 同步到新邮件时调用:只处理收件箱和垃圾邮件里的、近期的邮件(首次回溯和移回收件箱的旧邮件不触发) */ export async function onNewMessage(messageId: number, date: Date) { if (Date.now() - date.getTime() > 3 * 86400_000) return; await enqueue('process_message', { messageId }); diff --git a/server/src/sync/account-worker.ts b/server/src/sync/account-worker.ts index 4059e15..01d613b 100644 --- a/server/src/sync/account-worker.ts +++ b/server/src/sync/account-worker.ts @@ -16,6 +16,8 @@ import { isMessageDataError } from '../lib/db-errors.js'; const BATCH = 25; const TRUNCATED_BYTES = 2 * 1024 * 1024; const FLAG_WINDOW = 500; +// 垃圾邮件没有 IDLE 推送,每分钟用 STATUS 看一眼(验证码常被误判进垃圾邮件,不能等 pollInterval) +const JUNK_POLL_MS = 60_000; type SyncKind = 'none' | 'inbox' | 'all'; const rank: Record = { none: 0, inbox: 1, all: 2 }; @@ -30,6 +32,7 @@ function sleep(ms: number, signal: AbortSignal) { /** * 每个邮箱账户一个常驻 worker: * - 维持一条 IMAP 连接,选中 INBOX 后由 imapflow 自动 IDLE,收到 EXISTS 立即增量同步 + * - 垃圾邮件每分钟用 STATUS 检查一次,有新邮件和收件箱一样进入自动化流程 * - 其他文件夹按 pollInterval 轮询;断线指数退避重连 * - 同步连接全程以 EXAMINE(只读)打开文件夹;标记、移动、APPEND 等写操作走 imap-writer 的独立连接 */ @@ -39,7 +42,10 @@ export class AccountWorker { private pending: SyncKind = 'none'; private draining: Promise | null = null; private pollTimer: NodeJS.Timeout | null = null; + private junkTimer: NodeJS.Timeout | null = null; private inboxPath = 'INBOX'; + /** 上次同步垃圾邮件时的 UIDNEXT,STATUS 返回的值变了才去同步 */ + private junkUidNext: number | undefined; constructor(readonly accountId: number) { this.status = new StatusReporter(accountId); @@ -51,7 +57,7 @@ export class AccountWorker { async stop() { this.abort.abort(); - if (this.pollTimer) clearInterval(this.pollTimer); + this.clearTimers(); const client = this.client; this.client = null; if (client) await client.logout().catch(() => client.close()); @@ -65,6 +71,12 @@ export class AccountWorker { if (!this.draining && this.client?.usable) this.draining = this.drain().finally(() => (this.draining = null)); } + private clearTimers() { + if (this.pollTimer) clearInterval(this.pollTimer); + if (this.junkTimer) clearInterval(this.junkTimer); + this.pollTimer = this.junkTimer = null; + } + private setStatus(status: string, error: string | null = null) { return this.status.set(status, error); } @@ -105,13 +117,14 @@ export class AccountWorker { backoff = 0; this.requestSync('all'); this.pollTimer = setInterval(() => this.requestSync('all'), pollIntervalMsOf(account)); + this.junkTimer = setInterval(() => void this.pollJunk(), JUNK_POLL_MS); await closed; - if (this.pollTimer) clearInterval(this.pollTimer); + this.clearTimers(); if (!this.abort.signal.aborted) await this.setStatus('connecting', L('连接已断开,正在重连', 'Connection lost; reconnecting')); } catch (err) { const message = describeImapError(err); console.warn(`[sync:${this.accountId}] ${message}`); - if (this.pollTimer) clearInterval(this.pollTimer); + this.clearTimers(); this.client?.close(); if (!this.abort.signal.aborted) await this.setStatus('error', message); } @@ -157,9 +170,32 @@ export class AccountWorker { where: and(eq(folders.accountId, this.accountId), eq(folders.path, this.inboxPath)), }); if (inbox?.syncEnabled) await this.syncFolder(client, inbox, true); + const junk = await this.junkWithNewMail(client); + if (junk) await this.syncFolder(client, junk, false); await this.selectInbox(client); } + /** 垃圾邮件有新邮件时才排一次收件箱同步(会顺带同步垃圾邮件),没变化不切换「同步中」 */ + private async pollJunk() { + const client = this.client; + if (!client?.usable || this.draining) return; + try { + if (await this.junkWithNewMail(client)) this.requestSync('inbox'); + } catch (err) { + console.warn(`[sync:${this.accountId}] 检查垃圾邮件失败: ${describeImapError(err)}`); + } + } + + /** 用 STATUS 检查垃圾邮件文件夹的 UIDNEXT,变了就返回这个文件夹;首次回溯交给全量同步 */ + private async junkWithNewMail(client: ImapFlow): Promise { + const junk = await db.query.folders.findFirst({ + where: and(eq(folders.accountId, this.accountId), eq(folders.specialUse, '\\Junk')), + }); + if (!junk?.syncEnabled || junk.lastUid === 0) return null; + const st = await client.status(junk.path, { uidNext: true }); + return st && st.uidNext !== undefined && st.uidNext !== this.junkUidNext ? junk : null; + } + /** 让连接停在 INBOX 上,imapflow 空闲时会自动发 IDLE */ private async selectInbox(client: ImapFlow) { const lock = await client.getMailboxLock(this.inboxPath, { readOnly: true }); @@ -220,9 +256,9 @@ export class AccountWorker { uids = uids.filter((u) => u > lastUid); } const started = Date.now(); - // 只有收件箱的增量新邮件进入自动化流程;首次回溯、UIDVALIDITY 重建不触发 - const isInbox = folder.specialUse === '\\Inbox' || folder.path.toUpperCase() === 'INBOX'; - const done = await this.downloadNew(client, folder, uids, isInbox && lastUid !== 0); + // 只有收件箱和垃圾邮件的增量新邮件进入自动化流程;首次回溯、UIDVALIDITY 重建不触发 + const hot = folder.specialUse === '\\Inbox' || folder.specialUse === '\\Junk' || folder.path.toUpperCase() === 'INBOX'; + const done = await this.downloadNew(client, folder, uids, hot && lastUid !== 0); // 中途被停止时不推进 lastUid,下次从头补齐(已入库的会跳过) if (done) for (const u of uids) if (u > maxUid) maxUid = u; if (uids.length) { @@ -249,6 +285,8 @@ export class AccountWorker { lastSyncAt: new Date(), }) .where(eq(folders.id, folder.id)); + // 刚选中的文件夹 uidNext 是准的 + if (folder.specialUse === '\\Junk') this.junkUidNext = mb.uidNext; } finally { lock.release(); } diff --git a/server/src/sync/graph-worker.ts b/server/src/sync/graph-worker.ts index 527d9ce..d516cc8 100644 --- a/server/src/sync/graph-worker.ts +++ b/server/src/sync/graph-worker.ts @@ -1,4 +1,4 @@ -import { and, eq, isNull, notInArray, or } from 'drizzle-orm'; +import { and, eq, inArray, isNull, notInArray, or } from 'drizzle-orm'; import { config, pollIntervalMsOf } from '../config.js'; import { db } from '../db/index.js'; import { accounts, folders, messages, type Account, type Folder } from '../db/schema.js'; @@ -11,8 +11,10 @@ import { isDefaultSynced, nextUid, StatusReporter } from './status.js'; import { isMessageDataError } from '../lib/db-errors.js'; const TRUNCATED_BYTES = 2 * 1024 * 1024; -// Graph 没有 IDLE,收件箱靠轮询;其他文件夹按 pollInterval +// Graph 没有 IDLE,收件箱和垃圾邮件靠轮询(验证码常被误判进垃圾邮件,不能等 pollInterval);其他文件夹按 pollInterval const INBOX_POLL_MS = 60_000; +// 和收件箱一起高频同步、新邮件进自动化流程的文件夹 +const HOT_FOLDERS = ['\\Inbox', '\\Junk']; const WELL_KNOWN: Record = { inbox: '\\Inbox', @@ -45,7 +47,7 @@ function graphFlags(item: DeltaItem, answered = false) { * 微软 Graph 账户的同步 worker,对外接口和 IMAP 的 AccountWorker 一致: * - 文件夹用 mailFolders 列出,按 wellKnownName 识别收件箱、已发送等 * - 每个文件夹用 messages/delta 增量同步:新邮件取原始 MIME 走同一套入库流程,已读/旗标变化和删除直接改本地 - * - 收件箱每分钟轮询一次,其他文件夹按 pollInterval + * - 收件箱和垃圾邮件每分钟轮询一次,其他文件夹按 pollInterval */ export class GraphWorker { private abort = new AbortController(); @@ -125,11 +127,15 @@ export class GraphWorker { } } + /** 收件箱和垃圾邮件 */ private async syncInbox(account: Account) { - const inbox = await db.query.folders.findFirst({ - where: and(eq(folders.accountId, this.accountId), eq(folders.specialUse, '\\Inbox')), + const list = await db.query.folders.findMany({ + where: and(eq(folders.accountId, this.accountId), inArray(folders.specialUse, HOT_FOLDERS)), }); - if (inbox?.syncEnabled && inbox.remoteId) await this.syncFolder(account, inbox); + for (const f of list.sort((a, b) => HOT_FOLDERS.indexOf(a.specialUse!) - HOT_FOLDERS.indexOf(b.specialUse!))) { + if (this.abort.signal.aborted) return; + if (f.syncEnabled && f.remoteId) await this.syncFolder(account, f); + } } private async refreshFolders(account: Account): Promise { @@ -194,8 +200,8 @@ export class GraphWorker { private async syncFolder(account: Account, folder: Folder) { if (!folder.remoteId) return; const initial = !folder.deltaLink; - // 只有收件箱的增量新邮件进入自动化流程;首次回溯不触发 - const automate = folder.specialUse === '\\Inbox' && !initial; + // 只有收件箱和垃圾邮件的增量新邮件进入自动化流程;首次回溯不触发 + const automate = HOT_FOLDERS.includes(folder.specialUse ?? '') && !initial; let url: string | undefined = folder.deltaLink ?? this.initialDeltaUrl(folder); let deltaLink: string | undefined; let added = 0; diff --git a/server/test/junk-verification.test.ts b/server/test/junk-verification.test.ts new file mode 100644 index 0000000..37a582c --- /dev/null +++ b/server/test/junk-verification.test.ts @@ -0,0 +1,217 @@ +/** + * 验证码常被误判进垃圾邮件:垃圾邮件里的新邮件也做 AI 分析,只推送验证码、不执行规则; + * 「验证码」分类的数量和列表算上垃圾邮件,其他分类照旧不算。 + */ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { and, eq } from 'drizzle-orm'; +import { after, before, describe, test } from 'node:test'; +import { setup, type Env } from './helpers.js'; + +let env: Env; +let jobsMod: typeof import('../src/services/jobs.js'); +let mailMod: typeof import('../src/services/mail.js'); +let aiServer: http.Server; +let channelId: number; +let inboxId: number; +let junkId: number; + +// ---- 假 AI:主题里有 6 位数字就当验证码,否则当营销邮件 ---- +function startFakeAi() { + aiServer = http.createServer((req, res) => { + let body = ''; + req.on('data', (c) => (body += c)); + req.on('end', () => { + const code = body.match(/\b(\d{6})\b/)?.[1]; + const out = { + category: code ? 'verification' : 'marketing', + priority: 'high', + summary: code ? `验证码 ${code}` : '促销', + needs_reply: false, + verification_codes: code ? [code] : [], + amounts: [], + due_date: null, + tracking_numbers: [], + action_items: [], + labels: [], + }; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ choices: [{ message: { content: JSON.stringify(out) } }], usage: { prompt_tokens: 10, completion_tokens: 10 } })); + }); + }); + return new Promise((r) => aiServer.listen(0, '127.0.0.1', () => r((aiServer.address() as AddressInfo).port))); +} + +let uid = 2000; +async function addMessage(folderId: number, subject: string) { + const n = uid++; + const [m] = await env.db + .insert(env.schema.messages) + .values({ + accountId: env.accounts.work.id, + folderId, + uid: n, + threadId: `junk-t-${n}`, + messageId: ``, + subject, + fromAddress: 'no-reply@tiktok.example', + fromName: 'TikTok', + textBody: subject, + date: new Date(Date.now() - 60_000), + }) + .returning(); + return m!; +} + +async function processMessage(id: number) { + await jobsMod.enqueue('process_message', { messageId: id }); + const end = Date.now() + 15000; + while (Date.now() < end) { + const rows = await env.db + .select() + .from(env.schema.jobs) + .where(and(eq(env.schema.jobs.type, 'process_message'), eq(env.schema.jobs.status, 'done'))); + const job = rows.find((j) => Number(j.payload.messageId) === id); + if (job) return job.result as Record; + await new Promise((r) => setTimeout(r, 50)); + } + throw new Error(`等待超时:邮件 ${id} 处理完成`); +} + +const notifyEvents = async () => + (await env.db.select().from(env.schema.jobs).where(eq(env.schema.jobs.type, 'notify'))) + .filter((j) => Number(j.payload.channelId) === channelId) + .map((j) => (j.payload.notice as { event: string }).event); + +before(async () => { + env = await setup(); + const port = await startFakeAi(); + const aiMod = await import('../src/services/ai.js'); + jobsMod = await import('../src/services/jobs.js'); + mailMod = await import('../src/services/mail.js'); + await import('../src/services/pipeline.js'); + await aiMod.saveAiSettings({ + enabled: true, + channels: [ + { + id: 't', + name: 'fake', + provider: 'openai', + baseUrl: `http://127.0.0.1:${port}/v1`, + apiKey: 'x', + models: ['fake'], + modelsSyncedAt: null, + prices: {}, + priceRate: 1, + }, + ], + channelId: 't', + model: 'fake', + effort: 'low', + assistantChannelId: null, + assistantModel: null, + assistantEffort: null, + translateChannelId: null, + translateModel: null, + translateLanguage: '', + analysisEnabled: true, + accountIds: null, + }); + const { encryptChannelConfig } = await import('../src/services/notify.js'); + const [ch] = await env.db + .insert(env.schema.channels) + .values({ + name: 'test', + type: 'dingtalk', + configEnc: encryptChannelConfig({ webhook: 'http://127.0.0.1:9/robot' }), + events: ['message.verification', 'message.important', 'message.received'], + }) + .returning(); + channelId = ch!.id; + // 一条匹配所有 TikTok 邮件的规则(推送到另一个渠道,不碰 IMAP):垃圾邮件里不应执行 + const [ruleCh] = await env.db + .insert(env.schema.channels) + .values({ name: 'rule', type: 'dingtalk', configEnc: encryptChannelConfig({ webhook: 'http://127.0.0.1:9/robot' }), events: [] }) + .returning(); + await env.db.insert(env.schema.rules).values({ + name: 'tiktok', + conditions: [{ field: 'from', op: 'contains', value: 'tiktok' }], + actions: [{ type: 'notify', channelId: ruleCh!.id }], + }); + const inbox = await env.db.query.folders.findFirst({ where: (f, { eq }) => eq(f.accountId, env.accounts.work.id) }); + inboxId = inbox!.id; + const [junk] = await env.db + .insert(env.schema.folders) + .values({ accountId: env.accounts.work.id, path: 'Junk', name: 'Junk', specialUse: '\\Junk', syncEnabled: true }) + .returning(); + junkId = junk!.id; + await jobsMod.startJobs(); +}); + +after(async () => { + jobsMod?.stopJobs(); + aiServer?.close(); + await env?.close(); +}); + +describe('垃圾邮件里的验证码', () => { + test('垃圾邮件:分析出验证码只推送验证码,不执行规则', async () => { + const m = await addMessage(junkId, '837548 es tu código de verificación'); + const before = (await notifyEvents()).length; + const r = await processMessage(m.id); + assert.equal(r.category, 'verification'); + assert.equal(r.rules, undefined, '垃圾邮件不执行规则'); + assert.deepEqual(r.notified, [channelId]); + assert.deepEqual((await notifyEvents()).slice(before), ['message.verification']); + }); + + test('垃圾邮件:没有验证码的分析了也不推送', async () => { + const m = await addMessage(junkId, '限时促销,全场五折'); + const before = (await notifyEvents()).length; + const r = await processMessage(m.id); + assert.equal(r.category, 'marketing'); + assert.equal(r.rules, undefined); + assert.equal(r.notified, undefined); + assert.equal((await notifyEvents()).length, before); + }); + + test('收件箱照旧执行规则、推送', async () => { + const m = await addMessage(inboxId, '255953 es tu código de verificación'); + const r = await processMessage(m.id); + assert.ok(Array.isArray(r.rules) && r.rules.length === 1); + assert.ok((r.notified as number[]).includes(channelId)); + }); + + test('验证码分类的数量和列表算上垃圾邮件,其他分类不算', async () => { + const scope = { accountIds: null }; + const stats = await mailMod.getStats(scope); + assert.equal(stats.categories.verification?.total, 2, '收件箱 1 封 + 垃圾邮件 1 封'); + assert.equal(stats.categories.marketing, undefined, '垃圾邮件里的营销邮件不算'); + + const list = await mailMod.listThreads({ scope, view: 'all', q: 'category:verification' }); + assert.equal(list.items.length, 2); + const marketing = await mailMod.listThreads({ scope, view: 'all', q: 'category:marketing' }); + assert.equal(marketing.items.length, 0); + }); + + test('垃圾邮件视图集中列出所有邮箱的垃圾邮件,「全部邮件」不含', async () => { + const scope = { accountIds: null }; + const stats = await mailMod.getStats(scope); + assert.equal(stats.junkTotal, 2); + const junk = await mailMod.listThreads({ scope, view: 'junk' }); + assert.equal(junk.items.length, 2); + const all = await mailMod.listThreads({ scope, view: 'all' }); + const junkIds = new Set(junk.items.map((x) => x.threadId)); + assert.ok(all.items.every((x) => !junkIds.has(x.threadId))); + }); + + test('按会话移回收件箱只处理垃圾邮件里的邮件', async () => { + const { threadMessageIds } = await import('../src/services/actions.js'); + const scope = { accountIds: null }; + const junk = await addMessage(junkId, '111111 es tu código de verificación'); + const inbox = await addMessage(inboxId, '222222 es tu código de verificación'); + assert.deepEqual(await threadMessageIds(scope, [junk.threadId], 'inbox'), [junk.id]); + assert.deepEqual(await threadMessageIds(scope, [inbox.threadId], 'inbox'), []); + }); +}); diff --git a/web/src/api.ts b/web/src/api.ts index f76c5ef..1836e9e 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -539,7 +539,7 @@ export function attachmentUrl(messageId: number, index: number, inline = false) return `/api/v1/messages/${messageId}/attachments/${index}${inline ? '?inline=1' : ''}`; } -export type ThreadBatchAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'trash' | 'delete'; +export type ThreadBatchAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'inbox' | 'trash' | 'delete'; /** 按会话批量操作,服务端决定每个会话里具体处理哪些邮件 */ export function threadBatchAction(threadIds: string[], action: ThreadBatchAction) { diff --git a/web/src/components/AppLayout.tsx b/web/src/components/AppLayout.tsx index 27e1ea5..0333ae3 100644 --- a/web/src/components/AppLayout.tsx +++ b/web/src/components/AppLayout.tsx @@ -311,6 +311,8 @@ function Shell({ username }: { username: string }) { (f) => f.syncEnabled && f.path.toUpperCase() !== 'INBOX' && !['\\Inbox', '\\Sent', '\\Drafts', '\\Trash', '\\Junk'].includes(f.specialUse ?? ''), ); + const hasJunk = (folders.data ?? []).some((f) => f.syncEnabled && f.specialUse === '\\Junk'); + const selectedKey = useMemo(() => { if (location.pathname.startsWith('/settings') || location.pathname.startsWith('/ai/')) return location.pathname; if (location.pathname === '/outbox') return `/outbox?tab=${params.get('tab') ?? defaultDraftTab(pendingCount)}`; @@ -438,6 +440,8 @@ function Shell({ username }: { username: string }) { { key: 'view:starred', icon: , label: row(t.layout.mail.starred, count(st?.starredTotal ?? 0)) }, { key: 'view:sent', icon: , label: row(t.layout.mail.sent, count(st?.sentTotal ?? 0)) }, ...(hasExtraFolders ? [{ key: 'view:all', icon: , label: row(t.layout.mail.all, count(st?.allTotal ?? 0)) }] : []), + // 所有邮箱的垃圾邮件:「全部邮件」等视图不含垃圾邮件,误判进去的邮件在这里集中看 + ...(hasJunk ? [{ key: 'view:junk', icon: , label: row(t.layout.mail.junk, count(st?.junkTotal ?? 0)) }] : []), // AI 分类,默认收起,展开状态和邮箱一起记在本地 { key: 'cats', @@ -558,6 +562,7 @@ function Shell({ username }: { username: string }) { importantUnread, followUpsDue, hasExtraFolders, + hasJunk, labels.data, openKeys, selectedKey, @@ -608,7 +613,7 @@ function Shell({ username }: { username: string }) { if (!url || !value) return null; const st = stats.data; if (kind === 'view') { - if (value === 'sent' || value === 'waiting') return null; + if (value === 'sent' || value === 'waiting' || value === 'junk') return null; const unread: Record = { inbox: totalUnread, important: importantUnread, unread: st?.unreadTotal }; const name = t.layout.mail[value as 'inbox' | 'important' | 'unread' | 'starred' | 'all']; return { name, url, unreadFilter: value !== 'unread', markRead: { body: { view: value }, unread: unread[value] } }; diff --git a/web/src/components/MessageContextMenu.tsx b/web/src/components/MessageContextMenu.tsx index 7dfc0ec..cfa143f 100644 --- a/web/src/components/MessageContextMenu.tsx +++ b/web/src/components/MessageContextMenu.tsx @@ -1,6 +1,7 @@ import { ColumnHeightOutlined, ContainerOutlined, + InboxOutlined, CopyOutlined, DeleteOutlined, DownloadOutlined, @@ -83,6 +84,7 @@ export function MessageContextMenu({ { key: 'raw', label: t.reader.downloadEml, icon: }, { type: 'divider' }, ...(isInbox(m) ? [{ key: 'archive', label: t.reader.archive, icon: }] : []), + ...(m.folderSpecialUse === '\\Junk' ? [{ key: 'inbox', label: t.reader.moveToInbox, icon: }] : []), trashed || inTrash ? { key: 'delete', label: t.reader.deleteForever, icon: , danger: true } : { key: 'trash', label: t.threads.ctx.trashOne, icon: }, @@ -93,7 +95,7 @@ export function MessageContextMenu({ if (await act(action, [m.id])) message.success(done); }; // 归档 / 删除:会话只剩这一封时和顶栏按钮一样离开会话 - const remove = async (action: 'archive' | 'trash', done: string) => { + const remove = async (action: 'archive' | 'inbox' | 'trash', done: string) => { if (count === 1) await act(action, [m.id], done); else await quiet(action, done); }; @@ -106,6 +108,7 @@ export function MessageContextMenu({ if (key === 'unstar') return void quiet('unstar', t.reader.ctx.unstarred); if (key === 'expandAll' || key === 'collapseAll') return onExpandAll(key === 'expandAll'); if (key === 'archive') return void remove('archive', t.reader.archived); + if (key === 'inbox') return void remove('inbox', t.reader.movedToInbox); if (key === 'trash') return void remove('trash', t.reader.trashed); if (key === 'delete') return onPurge(m); if (key === 'raw') { diff --git a/web/src/components/ThreadContextMenu.tsx b/web/src/components/ThreadContextMenu.tsx index 487cda6..aa8f810 100644 --- a/web/src/components/ThreadContextMenu.tsx +++ b/web/src/components/ThreadContextMenu.tsx @@ -2,6 +2,7 @@ import { BellOutlined, CheckOutlined, ContainerOutlined, + InboxOutlined, CopyOutlined, DeleteOutlined, EyeInvisibleOutlined, @@ -38,12 +39,14 @@ const FOLLOW_UP_PRESETS = ['1', '3', '7'] as const; export function ThreadContextMenu({ target, inTrash, + inJunk, onClose, onOpen, runBatch, }: { target: ThreadMenuTarget | null; inTrash?: boolean; + inJunk?: boolean; onClose: () => void; onOpen: (threadId: string) => void; runBatch: (action: ThreadBatchAction, threadIds: string[]) => void; @@ -123,7 +126,9 @@ export function ThreadContextMenu({ ] : []), { type: 'divider' }, - { key: 'archive', label: t.threads.archive, icon: }, + inJunk + ? { key: 'inbox', label: t.threads.moveToInbox, icon: } + : { key: 'archive', label: t.threads.archive, icon: }, inTrash ? { key: 'delete', label: t.threads.deleteForever, icon: , danger: true } : { key: 'trash', label: t.threads.ctx.trashOne, icon: }, @@ -166,7 +171,7 @@ export function ThreadContextMenu({ const onClick = (key: string) => { if (key === 'open') return onOpen(one.threadId); if (key === 'reply' || key === 'replyAll' || key === 'forward') return compose({ mode: key, sourceMessageId: one.latestMessageId }); - if (['read', 'unread', 'star', 'unstar', 'archive', 'trash', 'delete'].includes(key)) return runBatch(key as ThreadBatchAction, ids); + if (['read', 'unread', 'star', 'unstar', 'archive', 'inbox', 'trash', 'delete'].includes(key)) return runBatch(key as ThreadBatchAction, ids); if (key === 'labels:manage') return navigate('/ai/labels'); if (key.startsWith('label:')) return void setLabel(Number(key.slice(6))); if (key.startsWith('fu:')) return void followUp(key.slice(3)); diff --git a/web/src/components/ThreadList.tsx b/web/src/components/ThreadList.tsx index fbdda20..956f66a 100644 --- a/web/src/components/ThreadList.tsx +++ b/web/src/components/ThreadList.tsx @@ -2,6 +2,7 @@ import { CheckOutlined, CloseOutlined, ContainerOutlined, + InboxOutlined, DeleteOutlined, EyeInvisibleOutlined, EyeOutlined, @@ -28,6 +29,8 @@ type Props = { folderId: string | null; /** 当前是「已删除」文件夹,删除按钮改为彻底删除 */ inTrash?: boolean; + /** 垃圾邮件文件夹或所有邮箱的垃圾邮件视图:归档换成「移回收件箱」 */ + inJunk?: boolean; q: string; selected: string | null; onSelect: (threadId: string) => void; @@ -59,7 +62,7 @@ function useElementHeight() { return [ref, height] as const; } -export function ThreadList({ view, accountId, folderId, inTrash, q, selected, onSelect, onRemoved, unreadOnly, onUnreadOnly }: Props) { +export function ThreadList({ view, accountId, folderId, inTrash, inJunk, q, selected, onSelect, onRemoved, unreadOnly, onUnreadOnly }: Props) { const { token } = theme.useToken(); const { message, modal } = App.useApp(); const qc = useQueryClient(); @@ -184,7 +187,7 @@ export function ThreadList({ view, accountId, folderId, inTrash, q, selected, on ]); const n = res.updated ?? res.moved ?? res.deleted ?? 0; message.success(t.threads.batchResult(t.threads.batchDone[action], res.destination, n)); - if (action === 'archive' || action === 'trash' || action === 'delete') { + if (action === 'archive' || action === 'inbox' || action === 'trash' || action === 'delete') { onRemoved?.(ids); setChecked((prev) => new Set([...prev].filter((id) => !ids.includes(id)))); } @@ -428,7 +431,7 @@ export function ThreadList({ view, accountId, folderId, inTrash, q, selected, on {t.threads.selected(checked.size)} - {batchButton('archive', t.threads.archive, )} + {inJunk ? batchButton('inbox', t.threads.moveToInbox, ) : batchButton('archive', t.threads.archive, )} {inTrash ? batchButton('delete', t.threads.deleteForever, , true) : batchButton('trash', t.threads.trash, )} {anyUnread ? batchButton('read', t.threads.markRead, ) : batchButton('unread', t.threads.markUnread, )} {anyUnstarred @@ -465,7 +468,7 @@ export function ThreadList({ view, accountId, folderId, inTrash, q, selected, on return ( {toolbar} - setMenu(null)} onOpen={onSelect} runBatch={(a, ids) => void runBatch(a, ids)} /> + setMenu(null)} onOpen={onSelect} runBatch={(a, ids) => void runBatch(a, ids)} />
{query.isPending ? ( diff --git a/web/src/components/ThreadView.tsx b/web/src/components/ThreadView.tsx index 53699a4..e620fe2 100644 --- a/web/src/components/ThreadView.tsx +++ b/web/src/components/ThreadView.tsx @@ -2,6 +2,7 @@ import { ArrowLeftOutlined, BellOutlined, ContainerOutlined, + InboxOutlined, DeleteOutlined, DownloadOutlined, EditOutlined, @@ -285,7 +286,7 @@ function ThreadDrafts({ threadId }: { threadId: string }) { } /** 阅读区的整会话操作,在全部邮箱视图里同样作用到其他邮箱里同一封邮件的会话 */ -const COPY_ACTIONS = new Set(['read', 'unread', 'star', 'unstar', 'archive', 'trash', 'delete']); +const COPY_ACTIONS = new Set(['read', 'unread', 'star', 'unstar', 'archive', 'inbox', 'trash', 'delete']); export function ThreadView({ threadId, @@ -379,6 +380,7 @@ export function ThreadView({ const last = messages[messages.length - 1]!; const starred = messages.some((m) => m.flagged) || (merged && !!query.data?.copiesFlagged); const inboxIds = messages.filter(isInbox).map((m) => m.id); + const junkIds = messages.filter((m) => m.folderSpecialUse === '\\Junk').map((m) => m.id); const trashIds = messages.filter((m) => m.folderSpecialUse !== '\\Trash').map((m) => m.id); const purgeIds = messages.filter((m) => m.folderSpecialUse === '\\Trash').map((m) => m.id); // 在「已删除」里打开,或整个会话都已在「已删除」里时,删除就是彻底删除 @@ -418,6 +420,11 @@ export function ThreadView({ {t.reader.messageCount(messages.length)} )} + {junkIds.length > 0 && ( + +