dsh-postbox 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/sync.js ADDED
@@ -0,0 +1,899 @@
1
+ // lib/sync.js — 常驻 watcher:水位 + 增量抓取 + 健康/退避 + 单实例锁 + 状态快照。
2
+ //
3
+ // 职责边界:只负责「把新邮件搬进 store 并推进水位」。通知由 onNewMessages 回调接
4
+ // (M3 接 notify.js),抓取深度由 store.flags(三档 archive.mode)决定。
5
+ //
6
+ // 水位语义(与 Python agent 的 alert/sync 一致):
7
+ // * 首轮只建水位,不抓取、不通知(D10:默认不回补;archive.backfill=true 才从最旧开始)
8
+ // * UIDVALIDITY 变更 → 水位作废、重建基线(避免把整个邮箱当新邮件刷屏)
9
+ // * 单封失败不阻断整轮:水位照推,失败计数进 health(last_error),避免永久卡住
10
+ //
11
+ // 单实例:watcher.lock(默认在 store.dir 下)。desktop/web 两个 profile 若共用同一个
12
+ // dataDir(绝对路径),这个锁就能阻止「双份提醒 + 双份归档」。
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { ImapClient } from "./imap.js";
17
+ import { parseMime } from "./mime.js";
18
+ import { modeFlags } from "./store.js";
19
+ import { cleanText, extractCode } from "./digest.js";
20
+ import { indexFields, textAttachments } from "./ft.js";
21
+ import { classifyError } from "./errors.js";
22
+
23
+ const SILENT = () => {};
24
+ /** snippet 只用于列表/通知预览。2026-11-26 由 200 提到 400:验证码常出现在问候语之后,
25
+ * 200 字经常「刚好切在验证码前面」,摘要里只剩客套话。 */
26
+ const SNIPPET_CHARS = 400;
27
+
28
+ /** 锁被别的实例持着时,tick 的警告日志最小间隔(tick 本身 60 秒一轮)。
29
+ * 不降频的话,「另一个 DSH 窗口开着」会一天刷 1440 条一模一样的 warn。 */
30
+ const LOCK_LOG_INTERVAL_MS = 10 * 60_000;
31
+
32
+ // ---------------------------------------------------------------- M5 索引重建
33
+ /** 从已归档的邮件重建倒排索引(**纯本地**,不发网络请求)。
34
+ * 升级到 M5 之后,老归档里一封词条都没有;`full` 模式顺手把 .eml 重解析一遍,
35
+ * 正文索引才补得回来。幂等:indexMessage 按封重写。
36
+ * 独立成函数是为了「watcher 没跑」时也能用(write.enabled=false / watcher.enabled=false)。 */
37
+ export function reindexArchive(store, { limit = 20000, log = SILENT } = {}) {
38
+ const withBody = !!(store?.flags?.raw);
39
+ const rows = store.listMessages({ limit });
40
+ let indexed = 0, failed = 0;
41
+ for (const row of rows) {
42
+ try {
43
+ let body = null, attachments = [];
44
+ if (withBody) {
45
+ const raw = store.readRaw(row);
46
+ if (raw) {
47
+ const parsed = parseMime(raw);
48
+ body = parsed.bodyText;
49
+ attachments = textAttachments(parsed.attachments);
50
+ }
51
+ }
52
+ store.indexMessage(row, indexFields(
53
+ { subject: row.subject, from: row.from_addr, to: row.to_addr, snippet: row.snippet, body, attachments },
54
+ { withBody },
55
+ ));
56
+ indexed++;
57
+ } catch (e) {
58
+ failed++;
59
+ log("warn", `重建索引失败 ${row.account}/${row.folder}/${row.uid}:${e?.message ?? e}`);
60
+ }
61
+ }
62
+ const mode = withBody ? "full" : (store?.flags?.metadata ? "metadata" : "online");
63
+ log("info", `倒排索引重建:扫描 ${rows.length} 封,索引 ${indexed} 封,失败 ${failed}(模式 ${mode})`);
64
+ return { scanned: rows.length, indexed, failed, mode, skipped: rows.length === 0 };
65
+ }
66
+
67
+ // ---------------------------------------------------------------- 单实例锁
68
+ function isPidAlive(pid) {
69
+ if (!Number.isFinite(pid) || pid <= 0) return false;
70
+ try { process.kill(pid, 0); return true; }
71
+ catch (e) { return e?.code === "EPERM"; } // 存在但无权限 → 视为活着
72
+ }
73
+
74
+ /** 拿锁。已有**活的且新鲜**的锁则失败;过期锁可接管。 */
75
+ export function acquireLock(lockPath, { pid = process.pid, now = Date.now(), staleMs = 5 * 60_000 } = {}) {
76
+ let cur = null;
77
+ try { cur = JSON.parse(fs.readFileSync(lockPath, "utf8")); } catch { /* 无锁或坏锁 */ }
78
+ if (cur && Number(cur.pid) !== pid) {
79
+ const fresh = Number.isFinite(Number(cur.updatedAt)) && now - Number(cur.updatedAt) < staleMs;
80
+ if (fresh && isPidAlive(Number(cur.pid))) return { ok: false, holder: cur };
81
+ }
82
+ const payload = { pid, startedAt: Number(cur?.pid) === pid ? cur.startedAt ?? now : now, updatedAt: now };
83
+ try {
84
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
85
+ fs.writeFileSync(lockPath, JSON.stringify(payload, null, 2));
86
+ } catch (e) {
87
+ return { ok: false, error: String(e?.message ?? e) };
88
+ }
89
+ return { ok: true, holder: payload };
90
+ }
91
+
92
+ export function touchLock(lockPath, { pid = process.pid, now = Date.now() } = {}) {
93
+ try {
94
+ const cur = JSON.parse(fs.readFileSync(lockPath, "utf8"));
95
+ if (Number(cur.pid) !== pid) return false;
96
+ fs.writeFileSync(lockPath, JSON.stringify({ ...cur, updatedAt: now }, null, 2));
97
+ return true;
98
+ } catch { return false; }
99
+ }
100
+
101
+ export function releaseLock(lockPath, { pid = process.pid } = {}) {
102
+ try {
103
+ const cur = JSON.parse(fs.readFileSync(lockPath, "utf8"));
104
+ if (Number(cur.pid) !== pid) return false; // 不是自己的锁,绝不删
105
+ fs.rmSync(lockPath, { force: true });
106
+ return true;
107
+ } catch { return false; }
108
+ }
109
+
110
+ /** 把 HTTP-date 转 epoch ms;解不出返回 null。 */
111
+ function toTs(dateStr) {
112
+ const t = Date.parse(dateStr ?? "");
113
+ return Number.isFinite(t) ? t : null;
114
+ }
115
+
116
+ /** "08:00" → 分钟数;非法 → null */
117
+ function parseHHMM(s) {
118
+ const m = /^\s*(\d{1,2}):(\d{2})\s*$/.exec(String(s ?? ""));
119
+ if (!m) return null;
120
+ const h = Number(m[1]), min = Number(m[2]);
121
+ if (h > 23 || min > 59) return null;
122
+ return h * 60 + min;
123
+ }
124
+
125
+ /** 仅凭信封头判断是否有附件(metadata 模式的近似);full 模式用 MIME 解析结果覆盖。 */
126
+ function guessHasAttachment(contentType) {
127
+ return /multipart\/mixed/i.test(String(contentType ?? ""));
128
+ }
129
+
130
+ export class Watcher {
131
+ constructor({
132
+ accounts = [], store, tokenProvider, imapFactory = null,
133
+ archive = {}, pollIntervalSeconds = 60, maxBackoffSeconds = 1800,
134
+ maxMessagesPerCycle = 20, log = SILENT, now = Date.now,
135
+ onNewMessages = null, lockPath = null, staleLockMs = null, pid = process.pid,
136
+ dailyDigest = null, onDailyDigest = null, onIngested = null,
137
+ } = {}) {
138
+ this.accounts = accounts;
139
+ this.store = store;
140
+ this.tokenProvider = tokenProvider;
141
+ this.imapFactory = imapFactory ?? ((acc, token) => new ImapClient(acc, token));
142
+ this.archive = { mode: "metadata", backfill: false, retentionDays: 0, maxBytes: 0, snippet: true, ...archive };
143
+ this.intervalMs = Math.max(5, Number(pollIntervalSeconds) || 60) * 1000;
144
+ this.maxBackoffMs = Math.max(this.intervalMs, (Number(maxBackoffSeconds) || 1800) * 1000);
145
+ this.maxMessagesPerCycle = Math.max(1, Number(maxMessagesPerCycle) || 20);
146
+ this.log = log;
147
+ this.now = now;
148
+ this.onNewMessages = onNewMessages;
149
+ this.onIngested = onIngested; // M7:每入库一封的语义钩子(**同步返回、内部自己排队**)
150
+ this.dailyDigest = dailyDigest; // { enabled, at: "08:00" }
151
+ this.onDailyDigest = onDailyDigest; // async ({items, now, store}) => { ok }
152
+ this.pid = pid;
153
+ this.lockPath = lockPath ?? path.join(store.dir, "watcher.lock");
154
+ this.statePath = path.join(store.dir, "state.json");
155
+ this.backoffMs = this.intervalMs;
156
+ this.lastTick = null;
157
+ // M3.3:watcher.enabled=false 的运行时语义 = **暂停**(保留锁/快照/日报,只是不抓邮件)
158
+ this.paused = false;
159
+ // B6:是否真正拿到了单实例锁(start() 里置位)。没拿到时 tick() 会拒绝抓取。
160
+ this.lockHeld = false;
161
+ // 第二轮小修:锁被别人持着时,tick 每 60 秒打一条 warn 会把日志冲掉(一天 1440 条)。
162
+ // 只记「上次提示时间 + 那个持有者的 pid」:同一持有者 10 分钟才提醒一次。
163
+ this.lockRefusedAt = 0;
164
+ this.lockRefusedPid = 0;
165
+ }
166
+
167
+ // ------------------------------------------------------------ 单文件夹
168
+ async runFolder(acc, folder, { now = this.now(), session = null } = {}) {
169
+ // B5(2026-11-30):同账号的多个文件夹复用同一条 IMAP 连接。以前是「每文件夹
170
+ // connect/open/close」—— 监控 3 个文件夹就是 3 次 TLS 握手 + 3 次 XOAUTH2,
171
+ // 一轮 60s 里可能光握手就吃掉十几秒,还更容易被服务器限流。
172
+ const token = session ? session.token : await this.tokenProvider(acc);
173
+ const client = session ? session.client : this.imapFactory(acc, token);
174
+ try {
175
+ // 必须先建立 TLS + XOAUTH2 认证;少了这一步只会在 open() 时报 "not connected"
176
+ // (离线假客户端不需要连接,所以这条只有实盘才暴露 —— 实测踩过)
177
+ if (!session) await client.connect();
178
+ // open() 同时给出 EXISTS / UIDVALIDITY / UIDNEXT,省一次 STATUS 往返
179
+ const info = await client.open(folder);
180
+ // M6.7:顺手在同一条连接上再 STATUS 一把,拿「服务器实时」的总数/未读。
181
+ // 用户 2026-10-30 拍板:浮动栏/状态桥的计数**以服务器为准** —— 尤其 online
182
+ // 模式(不落库)下本地归档永远停旧,这是唯一可信的数字源。STATUS 在已 SELECT
183
+ // 的邮箱上服务器一般也接受;万一拒绝/抖动 → 退回 SELECT 的 EXISTS(总数),
184
+ // 未读置 null,绝不让计数失败拖垮本轮抓取。
185
+ let live = { total: Number(info.messages ?? 0), unread: null, at: now };
186
+ try {
187
+ const st = await client.status(folder);
188
+ live = {
189
+ total: Number(st.messages ?? info.messages ?? 0),
190
+ unread: Number.isFinite(Number(st.unseen)) ? Number(st.unseen) : null,
191
+ at: now,
192
+ };
193
+ } catch (e) {
194
+ this.log("warn", `[${acc.email}/${folder}] 服务器计数(STATUS)失败,退回 EXISTS(不影响抓取): ${e?.message ?? e}`);
195
+ }
196
+ const uidv = Number(info.uidValidity ?? 0);
197
+ const saved = this.store.getSyncState(acc.email, folder);
198
+ // 大小写身份统一(2026-10-31):Outlook 邮箱名不分大小写,水位行用哪种书写形式
199
+ // (INBOX/Inbox),后续落库/通知/水位读写就沿用哪种 —— 防止同一邮箱分裂成两套
200
+ // 身份(双轮询/重复通知/计数分裂)。open/status 仍用配置原样(服务器端等价)。
201
+ const folderKey = saved?.folder ?? folder;
202
+ const baselineUid = Math.max(0, Number(info.uidNext ?? 1) - 1);
203
+ let lastUid = Number(saved?.last_uid ?? 0);
204
+ let baseline = false;
205
+ let note = "";
206
+
207
+ if (!saved || !Number(saved.uidvalidity)) {
208
+ baseline = true;
209
+ note = "首次运行,只建水位(不回补历史)";
210
+ } else if (Number(saved.uidvalidity) !== uidv) {
211
+ baseline = true;
212
+ note = `UIDVALIDITY ${saved.uidvalidity} → ${uidv},水位作废并重建基线`;
213
+ }
214
+ if (baseline && this.archive.backfill) {
215
+ baseline = false;
216
+ lastUid = 0;
217
+ note = "archive.backfill=true:从最旧开始回补";
218
+ }
219
+
220
+ if (baseline) {
221
+ // 与下面的成功轮次同理:baseline 也是**成功**,别写 lastError(null) ——
222
+ // 那会把上一轮的失败原因抹掉(2026-10-17 实测的"19 轮失败事后不可考"就走这条)。
223
+ this.store.setSyncState(acc.email, folderKey, {
224
+ uidvalidity: uidv, lastUid: baselineUid, health: "ok", lastOkAt: now,
225
+ });
226
+ // UIDVALIDITY 变了 = 服务器重排过 uid,旧的回填截止标记已失效,清掉防误拦新邮件。
227
+ if (typeof this.store.clearBackfillMark === "function") {
228
+ try { this.store.clearBackfillMark(acc.email, folderKey); } catch { /* 清不掉就留着,下轮再清 */ }
229
+ }
230
+ this.log("info", `[${acc.email}/${folderKey}] ${note}(水位 ${baselineUid})`);
231
+ return { account: acc.email, folder: folderKey, baseline: true, fetched: 0, errors: 0, lastUid: baselineUid, uidvalidity: uidv, note, live };
232
+ }
233
+
234
+ // 回填截止标记(resetSyncState 写入):uid ≤ mark = 重置前就见过的历史邮件,
235
+ // 只入库/建索引,**不通知、不进语义钩子**(否则回填一次 = 灌一次通知风暴)。
236
+ const mark = typeof this.store.backfillMark === "function"
237
+ ? this.store.backfillMark(acc.email, folderKey)
238
+ : null;
239
+
240
+ const uids = await client.searchUidsSince(lastUid, this.maxMessagesPerCycle);
241
+ const items = [];
242
+ let errors = 0;
243
+
244
+ for (const uid of uids) {
245
+ try {
246
+ const env = (await client.fetchEnvelopes([uid]))[0];
247
+ // 抓取过程中消失(UID 空洞 / 刚被别的客户端移走):跳过,不算错误。
248
+ if (!env) continue;
249
+ if (env.error) throw new Error(env.error);
250
+
251
+ const row = {
252
+ account: acc.email, folder: folderKey, uid,
253
+ messageId: env.message_id ?? null,
254
+ subject: env.subject ?? null,
255
+ from: env.from ?? null,
256
+ to: env.to ?? null,
257
+ dateTs: toTs(env.date),
258
+ seen: !!env.seen,
259
+ flags: env.flags ?? [],
260
+ hasAttachment: guessHasAttachment(env.content_type),
261
+ snippet: null,
262
+ importance: null,
263
+ };
264
+
265
+ // 摘要需要正文。是否**落盘**由 store.flags.raw 决定(full 才落);
266
+ // archive.snippet(默认 true)时,即使 metadata/online 也抓一次正文抽 snippet(不落盘),
267
+ // 这样通知里出现的才是「这封信要你干什么」,而不是把标题再抄一遍。
268
+ const wantSnippet = this.store.flags.raw || this.archive.snippet;
269
+ let rawBytes = null;
270
+ let bodyText = null;
271
+ let attachments = [];
272
+ if (wantSnippet) {
273
+ rawBytes = await client.fetchFull(uid);
274
+ const parsed = parseMime(rawBytes);
275
+ bodyText = String(parsed.bodyText ?? "");
276
+ // 先洗 HTML 再截断:很多 2FA 邮件的 text/plain 里塞的就是 HTML,
277
+ // 不清洗的话 snippet 会以 `<h3> Hi …` 开头,推送里既难读又挤掉真正的验证码。
278
+ const flat = cleanText(bodyText);
279
+ row.snippet = flat.replace(/\s+/g, " ").trim().slice(0, SNIPPET_CHARS) || null;
280
+ // 验证码在入库这一刻就抽好(v7 列):通知/日报/列表都能直接读,不必重算,
281
+ // 也不依赖 400 字的截断位置。
282
+ const hit = extractCode(flat, { subject: env.subject ?? "" });
283
+ row.otp = hit?.code ?? null;
284
+ row.otpTtl = hit?.ttlMinutes ?? null;
285
+ row.hasAttachment = parsed.attachments.length > 0;
286
+ attachments = parsed.attachments;
287
+ }
288
+
289
+ const res = this.store.upsertMessage(row);
290
+ // writeRaw 是 UPDATE messages,必须在 upsertMessage 之后调用,
291
+ // 否则行还不存在、eml_path 会丢(实测踩过)。
292
+ if (rawBytes && this.store.flags.raw) this.store.writeRaw({ account: acc.email, folder: folderKey, uid }, rawBytes);
293
+
294
+ // ---- M5:同一轮里补倒排索引 ----
295
+ // **正文只在 full 模式入索引**(metadata 下把正文切成词条存库 = 变相落正文,
296
+ // 与"metadata 不落正文"自相矛盾);subject/from/to 三档都入,所以
297
+ // metadata 也能按标题/发件人检索。
298
+ if (!res?.skipped) {
299
+ try {
300
+ this.store.indexMessage({ account: acc.email, folder: folderKey, uid }, indexFields(
301
+ { ...row, body: bodyText, attachments: textAttachments(attachments) },
302
+ { withBody: this.store.flags.raw },
303
+ ));
304
+ } catch (e) {
305
+ // 索引失败只是"搜不到这一封",绝不能让整轮抓取失败(下一轮会重建)
306
+ this.log("warn", `[${acc.email}/${folderKey}] uid ${uid} 建索引失败(不影响归档):${e?.message ?? e}`);
307
+ }
308
+ }
309
+
310
+ // ---- M7 入口:**不 await** ----
311
+ // LLM 摘要是秒级外网调用,放进抓取循环会把一轮拉长到分钟级。
312
+ // onIngested 自己负责排队/限流/超时/降级,这里只保证"绝不因为语义能力失败而丢邮件"。
313
+ // 回填期(uid ≤ mark)的历史邮件**不进语义钩子**(烧外呼配额没有意义)。
314
+ if (this.onIngested && !res?.skipped && (mark == null || uid > mark)) {
315
+ try { this.onIngested({ account: acc.email, folder: folderKey, uid }, { ...row, body: bodyText }); }
316
+ catch (e) { this.log("warn", `[${acc.email}/${folderKey}] uid ${uid} 语义钩子异常(忽略):${e?.message ?? e}`); }
317
+ }
318
+ items.push({ uid, envelope: env, row, duplicate: !!res.duplicate });
319
+ } catch (e) {
320
+ errors++;
321
+ this.log("warn", `[${acc.email}/${folder}] uid ${uid} 处理失败(跳过,水位照推): ${e?.message ?? e}`);
322
+ }
323
+ lastUid = uid; // 无论成功失败都推进,避免单封坏邮件永久卡住整条流水线
324
+ }
325
+
326
+ // ---- 服务器→本地 状态回同步(其他端已读/移走/删除的动作落到本地镜像与通知留痕)。
327
+ // 包在 try 里:回同步失败只 warn,绝不能拖垮本轮抓取/通知/水位。
328
+ let stateSynced = { seen: 0, acked: 0, gone: 0 };
329
+ try {
330
+ stateSynced = await this.reconcileFolderState({ acc, folderKey, client, uidv });
331
+ } catch (e) {
332
+ this.log("warn", `[${acc.email}/${folderKey}] 状态回同步失败(忽略,不影响抓取): ${e?.message ?? e}`);
333
+ }
334
+
335
+ // 通知**先于**水位提交:投递失败时不推进水位,下轮重发(宁可重复提醒,不可漏提醒)。
336
+ // 回填期只把 > mark 的新邮件交给通知器(uid ≤ mark 的历史只入库,防通知风暴)。
337
+ const notifyItems = mark == null ? items : items.filter((it) => it.uid > mark);
338
+ const prevUid = Number(saved?.last_uid ?? 0);
339
+ let notifyFailed = false;
340
+ let notifyResult = null;
341
+ if (notifyItems.length && this.onNewMessages) {
342
+ try {
343
+ // ⚠️ 传 acc.email(字符串),**不要**传 acc 对象:
344
+ // 通知器把它用于文本标题与「留痕」(SQLite 绑定),传对象会写成 [object Object]
345
+ // 并让 notices 写入直接失败(2026-10-16 实测:WARN … 不能绑定 SQLite 参数 3)。
346
+ notifyResult = await this.onNewMessages({ account: acc.email, folder: folderKey, items: notifyItems, uidvalidity: uidv, now });
347
+ if (notifyResult && notifyResult.ok === false) notifyFailed = true;
348
+ } catch (e) {
349
+ notifyFailed = true;
350
+ this.log("warn", `[${acc.email}/${folderKey}] 通知异常(水位不推进): ${e?.message ?? e}`);
351
+ }
352
+ }
353
+
354
+ const advanceTo = notifyFailed ? prevUid : lastUid;
355
+ const problems = [];
356
+ if (errors) problems.push(`${errors} 封处理失败`);
357
+ if (notifyFailed) problems.push("通知投递失败(下轮重发)");
358
+ // ⚠️ 成功轮次**不要**写 lastError:setSyncState 是"给了才覆盖"的合并语义
359
+ // (store.js: patch.lastError !== undefined ? patch.lastError : cur.last_error)。
360
+ // 以前这里固定写 null,于是「19 轮抓取失败」的真实原因在下一轮成功时被抹掉,
361
+ // 事后完全查不出来(2026-10-17 实测:日志只剩"失败 1",sync_state.last_error 已 null)。
362
+ // 现在 last_error 留作**最近一次失败**的痕迹,health=ok 表示已恢复。
363
+ const syncPatch = {
364
+ uidvalidity: uidv, lastUid: advanceTo,
365
+ health: problems.length ? "warn" : "ok",
366
+ lastOkAt: now,
367
+ };
368
+ if (problems.length) syncPatch.lastError = problems.join(";");
369
+ this.store.setSyncState(acc.email, folderKey, syncPatch);
370
+
371
+ // 回填窗口走完(水位越过 mark)→ 清标记,之后的邮件恢复正常通知。
372
+ if (mark != null && advanceTo >= mark) {
373
+ try { this.store.clearBackfillMark(acc.email, folderKey); } catch { /* 下轮再清 */ }
374
+ this.log("info", `[${acc.email}/${folderKey}] 回填完成(≤${mark} 的历史只入库不通知)`);
375
+ }
376
+
377
+ return {
378
+ account: acc.email, folder: folderKey, baseline: false, fetched: items.length, errors,
379
+ lastUid: advanceTo, uidvalidity: uidv, notifyFailed, notify: notifyResult, live,
380
+ backfilled: mark == null ? 0 : Math.max(0, items.length - notifyItems.length),
381
+ stateSynced,
382
+ };
383
+ } catch (e) {
384
+ try {
385
+ // 这里只记「最近一次失败」的痕迹;health 交给分类:网络抖动这类可重试错误不动
386
+ // 健康标记(否则一次 ECONNRESET 就把账号长期标红,R3/R4 之后由 tick 统一定性)。
387
+ const info = classifyError(e);
388
+ const patch = { lastError: String(e?.message ?? e).slice(0, 200) };
389
+ // 可重试的暂时性失败标 warn(还在重试),不可重试的才标 error(auth/throttled 单独区分)。
390
+ patch.health = !info.retryable ? (info.kind === "auth" ? "auth-error" : info.kind === "throttled" ? "throttled" : "error") : "warn";
391
+ this.store.setSyncState(acc.email, folder, patch);
392
+ } catch { /* 记账失败也不能掩盖原错 */ }
393
+ throw e;
394
+ } finally {
395
+ // 复用的连接由 tick() 在账号循环结束后统一关,这里只管自己开的那条
396
+ if (!session) { try { client.close(); } catch { /* 已断 */ } }
397
+ }
398
+ }
399
+
400
+ /** B5:开一条可跨文件夹复用的连接(失败由调用方退回逐文件夹连接)。 */
401
+ async openSession(acc) {
402
+ const token = await this.tokenProvider(acc);
403
+ const client = this.imapFactory(acc, token);
404
+ await client.connect();
405
+ return {
406
+ client,
407
+ token,
408
+ close: async () => { try { await client.close(); } catch { /* 已断 */ } },
409
+ };
410
+ }
411
+
412
+ // ------------------------------------------------- 服务器→本地 状态回同步
413
+ /** 2026-10-31 用户需求:「dock 里的邮件记录是本地存储的,有些可能已经通过其他方式
414
+ * 已读或处理,希望把这些动作同步过来」。每轮抓取顺手在同一连接上做三件事:
415
+ * ① UID FETCH FLAGS(本地已知 uid,封顶 500)→ 把其他端的已读/未读翻转到本地行;
416
+ * ② 新变已读的 uid → 自动确认对应通知留痕(与手点「已看」同语义,徽标不再死咬);
417
+ * ③ 本地有、服务器已无的 uid → gone=1(移走/删除),明细/计数/统计不再计入。
418
+ * 前提:UIDVALIDITY 与本地水位一致(服务器重排过 uid 时不碰本地,防误标)。
419
+ * 任何异常由调用方吞掉 —— 状态回同步绝不能拖垮主抓取。 */
420
+ async reconcileFolderState({ acc, folderKey, client, uidv }) {
421
+ const store = this.store;
422
+ if (typeof store.listLocalUids !== "function") return { seen: 0, acked: 0, gone: 0 };
423
+ const saved = store.getSyncState(acc.email, folderKey);
424
+ if (!saved || Number(saved.uidvalidity) !== uidv) return { seen: 0, acked: 0, gone: 0 };
425
+ const local = store.listLocalUids(acc.email, folderKey, 500);
426
+ if (!local.length) return { seen: 0, acked: 0, gone: 0 };
427
+
428
+ const remote = await client.fetchFlags(local.map((r) => r.uid));
429
+ const byUid = new Map((remote ?? []).map((f) => [Number(f.uid), f]));
430
+ const changed = [];
431
+ for (const l of local) {
432
+ const f = byUid.get(l.uid);
433
+ if (!f) continue; // 缺席的统一按「服务器已无」处理(见下)
434
+ if (!!f.seen !== !!l.seen) changed.push({ uid: l.uid, seen: !!f.seen });
435
+ }
436
+
437
+ let seen = 0, acked = 0, gone = 0;
438
+ if (changed.length) {
439
+ const res = store.syncSeenFlags(acc.email, folderKey, changed);
440
+ seen = Number(res?.changed ?? 0);
441
+ const became = Array.isArray(res?.becameSeen) ? res.becameSeen : [];
442
+ if (became.length && typeof store.autoAckNoticesForUids === "function") {
443
+ acked = Number(store.autoAckNoticesForUids(acc.email, folderKey, became)?.acked ?? 0);
444
+ }
445
+ }
446
+ if ((remote ?? []).length < local.length) {
447
+ const remoteUids = new Set((remote ?? []).map((f) => Number(f.uid)));
448
+ const vanished = local.filter((l) => !remoteUids.has(l.uid)).map((l) => l.uid);
449
+ if (vanished.length && typeof store.markGoneUids === "function") {
450
+ gone = Number(store.markGoneUids(acc.email, folderKey, vanished) ?? 0);
451
+ // 邮件被移走/删除 = 服务器上已处理过,对应留痕同样该消(以前只有 gone 计数,徽标还亮着)
452
+ if (typeof store.autoAckNoticesForUids === "function") {
453
+ acked += Number(store.autoAckNoticesForUids(acc.email, folderKey, vanished)?.acked ?? 0);
454
+ }
455
+ }
456
+ }
457
+ // ---- 2026-11-26 修复「在其他客户端读过,留痕却一直不消」----
458
+ // 上面那段只在**本轮拍到未读→已读翻转**时 ack;可通知是本轮 notify 之后才创建的,
459
+ // 等下一轮已经没有翻转了 → 那条 notice 永远没人 ack。
460
+ // 所以每轮再按本地**当前**状态扫一遍:一封不剩全部已读/已移走,就把留痕清掉。
461
+ // 幂等(只处理 seen_at IS NULL),所以跑在 flags 没变动的轮次也安全。
462
+ if (typeof store.ackNoticesForSeen === "function") {
463
+ acked += Number(store.ackNoticesForSeen(acc.email, folderKey)?.acked ?? 0);
464
+ }
465
+ if (seen || acked || gone) {
466
+ this.log("info", `[${acc.email}/${folderKey}] 已同步服务器状态:已读 ${seen} · 自动确认提示 ${acked} · 服务器已无(移走/删除) ${gone}`);
467
+ }
468
+ return { seen, acked, gone };
469
+ }
470
+
471
+ /**
472
+ * 按需刷新「服务器已读状态」(2026-11-26)。用户在其他客户端读完邮件后,
473
+ * 不必等下一轮 60s 轮询,也不必动水位/抓新信 —— 只重取 FLAGS 并清留痕。
474
+ * @param {{ account?: string|null, folder?: string|null }} [opts] 省略 = 全部账户的全部监听文件夹
475
+ */
476
+ async syncStateNow({ account = null, folder = null } = {}) {
477
+ const out = { ok: true, checked: 0, seen: 0, acked: 0, gone: 0, errors: [], results: [] };
478
+ const accounts = (this.accounts ?? []).filter((a) => !account || a.email === account || a.alias === account);
479
+ if (!accounts.length) return { ...out, ok: false, errors: [`未找到账户 ${account}`] };
480
+ for (const acc of accounts) {
481
+ const folders = folder ? [folder] : (acc.folders?.length ? acc.folders : [acc.defaultFolder]);
482
+ for (const f of folders) {
483
+ if (!f) continue;
484
+ out.checked++;
485
+ let client = null;
486
+ try {
487
+ const token = await this.tokenProvider(acc);
488
+ client = this.imapFactory(acc, token);
489
+ await client.connect();
490
+ const info = await client.open(f);
491
+ const saved = this.store.getSyncState(acc.email, f);
492
+ const folderKey = saved?.folder ?? f;
493
+ const uidv = Number(info?.uidvalidity ?? saved?.uidvalidity ?? 0);
494
+ const r = await this.reconcileFolderState({ acc, folderKey, client, uidv });
495
+ out.seen += Number(r?.seen ?? 0);
496
+ out.acked += Number(r?.acked ?? 0);
497
+ out.gone += Number(r?.gone ?? 0);
498
+ out.results.push({ account: acc.email, folder: folderKey, ...r });
499
+ } catch (e) {
500
+ const reason = String(e?.message ?? e).slice(0, 300);
501
+ out.ok = false;
502
+ out.errors.push(`${acc.email}/${f}: ${reason}`);
503
+ this.log("warn", `[${acc.email}/${f}] 手动刷新已读状态失败: ${reason}`);
504
+ } finally {
505
+ try { await client?.close(); } catch { /* 关闭失败不影响结果 */ }
506
+ }
507
+ }
508
+ }
509
+ if (out.seen || out.acked || out.gone) {
510
+ this.log("info", `按需刷新已读状态:已读 ${out.seen} · 自动确认提示 ${out.acked} · 服务器已无 ${out.gone}`);
511
+ }
512
+ return out;
513
+ }
514
+
515
+ // ------------------------------------------------------------ 每日汇总
516
+ /** 到点且今天还没发过 → 组装并投递「日报」(低优先缓冲)。投递失败不标记已发,下轮重试。 */
517
+ async maybeDailyDigest({ now = this.now() } = {}) {
518
+ if (!this.dailyDigest?.enabled || typeof this.onDailyDigest !== "function") return { sent: false, reason: "disabled" };
519
+ const at = parseHHMM(this.dailyDigest.at ?? "08:00");
520
+ if (at === null) return { sent: false, reason: "bad-time" };
521
+
522
+ const d = new Date(now);
523
+ const dayKey = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
524
+ if (d.getHours() * 60 + d.getMinutes() < at) return { sent: false, reason: "before-time" };
525
+ if (this.store.getMeta("last_digest_day") === dayKey) return { sent: false, reason: "already-today" };
526
+
527
+ const items = this.store.listDigestQueue({ limit: 500 });
528
+ if (!items.length) {
529
+ // 今天没有低优先邮件:仍然记账,让"日报"保持每天一次的事件语义
530
+ this.store.setMeta("last_digest_day", dayKey);
531
+ return { sent: false, reason: "empty" };
532
+ }
533
+
534
+ const res = await this.onDailyDigest({ items, now, store: this.store });
535
+ if (res && res.ok === false) {
536
+ this.log("warn", `日报投递失败(${items.length} 封),下轮重试: ${res.error ?? ""}`);
537
+ return { sent: false, reason: "deliver-failed", count: items.length, error: res.error ?? null };
538
+ }
539
+ // ⚠️ 2026-10-16 修复:没有 IM 投递目标时**不能清队列**(清了就再也发不出去)。
540
+ // 保留条目、只记"今天已汇总过",避免每分钟重试刷日志;配置好目标后下一次汇总一起发出。
541
+ if (res && res.noChannel) {
542
+ this.store.setMeta("last_digest_day", dayKey);
543
+ this.log("info", `日报未发送(没有可用的 IM 投递目标):${items.length} 封保留在队列,配置目标后于下次汇总发送`);
544
+ return { sent: false, reason: "no-channel", count: items.length };
545
+ }
546
+ this.store.clearDigestQueue();
547
+ this.store.setMeta("last_digest_day", dayKey);
548
+ this.log("info", `日报已发:${items.length} 封低优先`);
549
+ return { sent: true, count: items.length };
550
+ }
551
+
552
+ // ------------------------------------------------- 按账号退避(R3,2026-11-30)
553
+ /** 账号的运行期状态:失败次数、下次可尝试时间、失败类别。只存在内存里 ——
554
+ * 重启后重新试一次是对的(用户可能在重启之间重新授权了)。 */
555
+ _acctState(email) {
556
+ if (!this.acctStates) this.acctStates = new Map();
557
+ const key = String(email ?? "");
558
+ let st = this.acctStates.get(key);
559
+ if (!st) {
560
+ st = { failures: 0, nextAt: 0, kind: null, lastError: null, authLoggedAt: 0 };
561
+ this.acctStates.set(key, st);
562
+ }
563
+ return st;
564
+ }
565
+
566
+ /** 记账一次失败并决定这个账号多久以后再试。
567
+ * 只有 **auth / throttled** 会被停泊(它们重试再多也没用、或者会加重限流);
568
+ * 网络抖动这类可重试错误仍然按原样每轮重试 —— 否则一次断网会让账号静默半小时。 */
569
+ _noteAccountFailure(email, info, { now, folder }) {
570
+ const st = this._acctState(email);
571
+ const kind = info?.kind ?? "unknown";
572
+ const retryable = info?.retryable !== false;
573
+ if (!retryable || kind === "throttled") {
574
+ st.failures += 1;
575
+ const base = kind === "auth" ? Math.max(this.maxBackoffMs, 30 * 60_000) : this.intervalMs;
576
+ const ms = Math.min(base * 2 ** Math.max(0, st.failures - 1), Math.max(this.maxBackoffMs, 30 * 60_000));
577
+ st.nextAt = now + ms;
578
+ st.kind = kind;
579
+ st.lastError = String(info?.message ?? "").slice(0, 200);
580
+ try {
581
+ // health 用三种值区分「为什么停」:auth-error(要人去授权)/ throttled(被限流)/
582
+ // error(其余不可重试:文件夹不存在、TLS、服务商怪癖)。仪表盘据此给不同提示。
583
+ const health = kind === "auth" ? "auth-error" : kind === "throttled" ? "throttled" : "error";
584
+ this.store.setSyncState(email, folder ?? "", { health, lastError: st.lastError });
585
+ } catch { /* 记账失败不能掩盖原错 */ }
586
+ // 认证失效只提醒一次(否则每轮一条,日志会被刷满)
587
+ if (kind === "auth" && now - st.authLoggedAt > 6 * 3600_000) {
588
+ st.authLoggedAt = now;
589
+ this.log("error", `[${email}] 授权已失效,暂停该账号 ${Math.round(ms / 60_000)} 分钟:请运行 mailbox_auth action=device 重新授权`);
590
+ }
591
+ return;
592
+ }
593
+ // 可重试的偶发错误:不改变调度,只留痕
594
+ st.kind = kind;
595
+ st.lastError = String(info?.message ?? "").slice(0, 200);
596
+ }
597
+
598
+ // ---------------------------------------------------------------- 一轮
599
+ /** B6:锁被**另一个活着的进程**持着吗?是就返回那条锁记录(供 tick 拒绝跑)。 */
600
+ _lockHeldByOther(now = this.now(), staleMs = 5 * 60_000) {
601
+ if (this.lockHeld) return null;
602
+ let cur = null;
603
+ try { cur = JSON.parse(fs.readFileSync(this.lockPath, "utf8")); } catch { return null; }
604
+ const pid = Number(cur?.pid ?? 0);
605
+ if (!Number.isFinite(pid) || pid <= 0 || pid === this.pid) return null;
606
+ const fresh = Number.isFinite(Number(cur.updatedAt)) && now - Number(cur.updatedAt) < staleMs;
607
+ return fresh && isPidAlive(pid) ? cur : null;
608
+ }
609
+
610
+ async tick({ now = this.now(), force = false } = {}) {
611
+ // B6:没拿到锁的实例**连手动 tick 也要拒绝** —— 以前浮动栏的「立刻检查」会绕过锁,
612
+ // 于是两个 DSH 窗口同时抓同一批信:重复入库、重复推送、水位互相打架。
613
+ // 注意:测试里从不 start(),也不会有锁文件,所以这条只在真有第二实例时触发。
614
+ const other = this._lockHeldByOther(now);
615
+ if (other) {
616
+ this.backoffMs = this.intervalMs;
617
+ this.lastTick = {
618
+ now, results: [], failures: 0, total: 0, digest: null, skipped: [],
619
+ refused: "lock-held-by-other", holder: { pid: Number(other.pid), startedAt: other.startedAt ?? null },
620
+ nextDelayMs: this.backoffMs,
621
+ };
622
+ // 同一个持有者只提示一次,之后每 10 分钟一条 —— 别让「另一个窗口开着」把日志刷满。
623
+ const pid = Number(other.pid);
624
+ const firstTime = this.lockRefusedPid !== pid || !this.lockRefusedAt;
625
+ if (firstTime || now - this.lockRefusedAt >= LOCK_LOG_INTERVAL_MS) {
626
+ this.log("warn", firstTime
627
+ ? `跳过本轮:归档正被另一个实例抓取(pid ${pid}),本实例不重复抓;同一个人再占着就每 ${LOCK_LOG_INTERVAL_MS / 60_000} 分钟提示一次`
628
+ : `仍在跳过:归档仍被另一个实例占着(pid ${pid},已 ${Math.round((now - this.lockRefusedAt) / 60_000)} 分钟),本实例继续不抓`);
629
+ this.lockRefusedPid = pid;
630
+ this.lockRefusedAt = now;
631
+ }
632
+ return this.lastTick;
633
+ }
634
+ const results = [];
635
+ const skipped = [];
636
+ let failures = 0;
637
+ let total = 0;
638
+
639
+ // 日报与 IMAP 无关(数据在本地缓冲里),所以放在文件夹循环之前
640
+ let digest = null;
641
+ try { digest = await this.maybeDailyDigest({ now }); }
642
+ catch (e) { this.log("warn", `日报检查异常: ${e?.message ?? e}`); }
643
+
644
+ if (this.archive.retentionDays > 0 || this.archive.maxBytes > 0) {
645
+ try {
646
+ const p = this.store.pruneRaw({ retentionDays: this.archive.retentionDays, maxBytes: this.archive.maxBytes, now });
647
+ if (p.removed) this.log("info", `保留策略:修剪 ${p.removed} 份原文,释放 ${p.freedBytes} 字节`);
648
+ } catch (e) {
649
+ this.log("warn", `保留策略执行失败: ${e?.message ?? e}`);
650
+ }
651
+ }
652
+
653
+ // B7(2026-11-30):元数据维护。pruneRaw 只删 .eml,消息行/倒排词条/通知只增不减,
654
+ // 库于是只涨不缩(倒排里还留着一堆服务器上早没了的 uid)。这里把「服务器上早已没有」
655
+ // 的行连同标签与词条一起清掉,顺手 VACUUM 把空间还给磁盘(所以必须在事务外单跑)。
656
+ // 默认 180 天;archive.maintenanceDays=0 关闭。
657
+ if (Number(this.archive.maintenanceDays ?? 0) > 0) {
658
+ try {
659
+ const g = this.store.purgeGone({ olderThanDays: this.archive.maintenanceDays, now });
660
+ const n = this.store.pruneNotices({ olderThanDays: this.archive.maintenanceDays, now });
661
+ if (g.purged || n) {
662
+ this.log("info", `维护:清掉 ${g.purged} 条已删除邮件的元数据(+${g.indexEntries} 条索引词条、${g.tagRows} 条标签)+ ${n} 条旧通知`);
663
+ const v = this.store.vacuum();
664
+ if (!v.ok) this.log("warn", `VACUUM 跳过(下次再试): ${v.error}`);
665
+ }
666
+ } catch (e) {
667
+ this.log("warn", `维护失败: ${e?.message ?? e}`);
668
+ }
669
+ }
670
+
671
+ // M3.3:运行时暂停 —— 不抓邮件,但锁/快照/日报照旧(用户随时可以再开)
672
+ if (this.paused) {
673
+ this.backoffMs = this.intervalMs;
674
+ touchLock(this.lockPath, { pid: this.pid, now });
675
+ this.lastTick = { now, results: [], failures: 0, total: 0, digest, paused: true, nextDelayMs: this.backoffMs };
676
+ try { this.writeSnapshot(); } catch (e) { this.log("warn", `写 state.json 失败: ${e?.message ?? e}`); }
677
+ return this.lastTick;
678
+ }
679
+
680
+ for (const acc of this.accounts) {
681
+ // R3(2026-11-30):按账号退避。一个账号令牌失效/被限流时,不能让它每轮都去
682
+ // 撞一次墙、把健康账号一起拖进全局退避(以前是「全部失败才退避」,于是坏账号
683
+ // 每轮都会重连失败,好账号的间隔也被拉到 30 分钟)。
684
+ const st = this._acctState(acc.email);
685
+ if (!force && st.nextAt > now) {
686
+ skipped.push(acc.email);
687
+ results.push({
688
+ account: acc.email, folder: null, skipped: true, reason: st.kind,
689
+ retryInMs: st.nextAt - now, lastError: st.lastError,
690
+ });
691
+ continue;
692
+ }
693
+ // B5:每个账号开一条连接、所有文件夹共用;建连接失败就退回逐文件夹连接,
694
+ // 让失败仍然按文件夹记录(与以前的可观测性一致)。
695
+ let session = null;
696
+ try {
697
+ session = await this.openSession(acc);
698
+ } catch (e) {
699
+ this.log("warn", `[${acc.email}] 复用连接建立失败,退回逐文件夹连接: ${e?.message ?? e}`);
700
+ session = null;
701
+ }
702
+ try {
703
+ for (const folder of (acc.folders?.length ? acc.folders : [acc.defaultFolder])) {
704
+ total++;
705
+ try {
706
+ results.push(await this.runFolder(acc, folder, { now, session }));
707
+ // 成功一次就把这个账号的退避清零(同账号多文件夹时不必等全部成功)
708
+ if (st.failures || st.nextAt) {
709
+ st.failures = 0; st.nextAt = 0; st.kind = null; st.lastError = null;
710
+ }
711
+ } catch (e) {
712
+ failures++;
713
+ const info = classifyError(e);
714
+ const reason = String(e?.message ?? e).slice(0, 300);
715
+ // 失败必须**留下原因**:以前这里只累加计数、不打日志,日志里只有"失败 1",
716
+ // 连 IMAP 报错(如 A0002 NO: User is authenticated but not connected.)都看不到,
717
+ // 用户只能看到"没收到信"(2026-10-17 实测:19 轮失败,0 条 ERROR,原因不可考)。
718
+ this.log("warn", `[${acc.email}/${folder}] 抓取失败(${info.kind}): ${reason}`);
719
+ results.push({ account: acc.email, folder, error: reason, errorKind: info.kind, retryable: info.retryable });
720
+ this._noteAccountFailure(acc.email, info, { now, folder });
721
+ // 连接本身可能已经坏了:后续文件夹别再往上撞,本轮直接收尾
722
+ if (session && (info.kind === "auth" || info.kind === "network")) {
723
+ try { await session.close(); } catch { /* 已断 */ }
724
+ session = null;
725
+ break;
726
+ }
727
+ }
728
+ }
729
+ } finally {
730
+ if (session) { try { await session.close(); } catch { /* 已断 */ } }
731
+ }
732
+ }
733
+
734
+ // 全部失败才退避(部分失败按正常间隔重试);被停泊的账号单独决定下一轮间隔
735
+ const parked = results.filter((r) => r?.skipped);
736
+ if (total === 0 && parked.length) {
737
+ // 所有账号都还在退避窗口里:按最近的那个恢复时间排下一轮,别空转
738
+ this.backoffMs = Math.min(
739
+ Math.max(...parked.map((r) => Number(r.retryInMs) || this.intervalMs), this.intervalMs),
740
+ this.maxBackoffMs,
741
+ );
742
+ } else {
743
+ this.backoffMs = total > 0 && failures === total
744
+ ? Math.min(Math.max(this.backoffMs, this.intervalMs) * 2, this.maxBackoffMs)
745
+ : this.intervalMs;
746
+ }
747
+
748
+ touchLock(this.lockPath, { pid: this.pid, now });
749
+ // 状态回同步合计(其他端已读/移走/删除在本轮落到本地的量),供 state.json/浮动栏观测
750
+ const stateSynced = results.reduce((a, r) => ({
751
+ seen: a.seen + Number(r?.stateSynced?.seen ?? 0),
752
+ acked: a.acked + Number(r?.stateSynced?.acked ?? 0),
753
+ gone: a.gone + Number(r?.stateSynced?.gone ?? 0),
754
+ }), { seen: 0, acked: 0, gone: 0 });
755
+ this.lastTick = { now, results, failures, total, digest, nextDelayMs: this.backoffMs, stateSynced, skipped };
756
+ try { this.writeSnapshot(); } catch (e) { this.log("warn", `写 state.json 失败: ${e?.message ?? e}`); }
757
+ return this.lastTick;
758
+ }
759
+
760
+ /** 运行时设置热应用(M3.3):由 lib/settings.js 的 diffLive() 给差异,
761
+ * **下一轮生效,不用重启**。notify.* 不归这里管(见 index.js 的通知器)。
762
+ * @param {{path:string, value:any}[]} patch
763
+ * @returns {string[]} 实际生效的字段路径 */
764
+ applyRuntimeSettings(patch = []) {
765
+ if (!Array.isArray(patch) || !patch.length) return [];
766
+ const applied = [];
767
+ for (const entry of patch) {
768
+ const p = entry?.path, value = entry?.value;
769
+ try {
770
+ if (p === "watcher.pollIntervalSeconds") {
771
+ this.intervalMs = Math.max(5, Number(value) || 60) * 1000;
772
+ this.maxBackoffMs = Math.max(this.intervalMs, this.maxBackoffMs);
773
+ this.backoffMs = this.intervalMs; // 改完立刻按新间隔排下一轮
774
+ applied.push(p);
775
+ } else if (p === "watcher.enabled") {
776
+ this.paused = value === false;
777
+ this.log("info", value === false ? "watcher 已暂停(锁/快照/日报保留,随时可恢复)" : "watcher 已恢复轮询");
778
+ applied.push(p);
779
+ } else if (p === "archive.mode") {
780
+ // 存储开关必须同步改,否则 mode 变了但 store 还按旧模式写/不写
781
+ Object.assign(this.store.flags, modeFlags(value));
782
+ this.archive.mode = value;
783
+ this.log("info", `归档模式已切换为 ${value}(下一轮起生效)`);
784
+ applied.push(p);
785
+ } else if (p === "archive.snippet" || p === "archive.retentionDays" || p === "archive.maxBytes" || p === "archive.maintenanceDays") {
786
+ this.archive[p.split(".")[1]] = value;
787
+ applied.push(p);
788
+ }
789
+ } catch (e) {
790
+ this.log("warn", `应用运行时设置 ${p} 失败: ${e?.message ?? e}`);
791
+ }
792
+ }
793
+ return applied;
794
+ }
795
+
796
+ /** 运行时热更账号列表(配置页免重启添加/删除账号时调用)。
797
+ * 下一轮 tick() 会直接用新列表,不用重启 watcher。 */
798
+ setAccounts(accounts = []) {
799
+ this.accounts = Array.isArray(accounts) ? accounts : [];
800
+ this.backoffMs = this.intervalMs; // 改完立刻按正常间隔排下一轮
801
+ this.log("info", `watcher 账号列表已更新(${this.accounts.length} 个账号)`);
802
+ }
803
+
804
+ /** M5:从已归档的邮件重建倒排索引(见文件头 `reindexArchive` 的说明)。 */
805
+ reindex(opts = {}) {
806
+ return reindexArchive(this.store, { log: (l, m) => this.log(l, m), ...opts });
807
+ }
808
+
809
+ /** 供未来浮动栏/工具读的健康快照。原子写。 */
810
+ snapshot() {
811
+ const sync = this.store.listSyncState();
812
+ return {
813
+ version: 1,
814
+ updatedAt: this.now(),
815
+ pid: this.pid,
816
+ pollIntervalSeconds: Math.round(this.intervalMs / 1000),
817
+ paused: this.paused,
818
+ backoffMs: this.backoffMs,
819
+ archiveMode: this.archive.mode,
820
+ accounts: this.accounts.map((a) => ({
821
+ email: a.email,
822
+ folders: sync.filter((s) => s.account === a.email).map((s) => ({
823
+ folder: s.folder, uidvalidity: s.uidvalidity, lastUid: s.last_uid,
824
+ health: s.health, lastOkAt: s.last_ok_at, lastError: s.last_error,
825
+ })),
826
+ })),
827
+ stats: this.store.stats(),
828
+ // 给输入框浮动栏用的「待看通知」与日报积压
829
+ digestQueue: (() => { try { return this.store.digestQueueSize(); } catch { return 0; } })(),
830
+ notices: (() => {
831
+ try {
832
+ return this.store.listNotices({ limit: 5, unseenOnly: true })
833
+ .map((n) => ({ id: n.id, kind: n.kind, createdAt: n.created_at, title: n.title, body: n.body, deliveredAt: n.delivered_at }));
834
+ } catch { return []; }
835
+ })(),
836
+ };
837
+ }
838
+
839
+ writeSnapshot() {
840
+ const p = this.statePath;
841
+ const tmp = p + ".tmp";
842
+ fs.writeFileSync(tmp, JSON.stringify(this.snapshot(), null, 2));
843
+ fs.renameSync(tmp, p);
844
+ return p;
845
+ }
846
+
847
+ /** 用宿主定时器起常驻循环。scheduler = { timeout(fn, ms) → disposer }。
848
+ * 返回 { stop(), locked, holder? }:拿不到锁时不启动(返回 locked:false)。 */
849
+ start(scheduler, { firstDelayMs = 2000, now = this.now(), staleMs = null } = {}) {
850
+ const lock = acquireLock(this.lockPath, { pid: this.pid, now, staleMs: staleMs ?? 5 * 60_000 });
851
+ if (!lock.ok) {
852
+ // B6(2026-11-30):以前这里只 warn 一句就过去了,用户看到的是"邮箱不动了"却毫无线索;
853
+ // 而且手动「立刻检查」还会绕过锁直接 tick(两个实例同时抓同一批信 → 重复通知)。
854
+ // 现在:日志升级为 error 并给出处置办法;同时把 lockHeld 置 false,让 tick() 也拒绝跑。
855
+ this.lockHeld = false;
856
+ const holder = lock.holder ?? null;
857
+ const since = Number.isFinite(Number(holder?.startedAt)) ? new Date(Number(holder.startedAt)).toISOString() : "?";
858
+ this.log("error", lock.error
859
+ ? `watcher 未启动:锁文件写入失败(${lock.error});目录权限?锁文件:${this.lockPath}`
860
+ : `watcher 未启动:另一个实例正持锁(pid ${holder?.pid ?? "?"},自 ${since})。` +
861
+ `同一份归档只能有一个实例在抓信 —— 关掉那个 DSH 窗口即可;若它其实已经死了,` +
862
+ `删除 ${this.lockPath} 后重启本窗口`);
863
+ return { locked: false, holder, stop() {} };
864
+ }
865
+ this.lockHeld = true;
866
+
867
+ // 注意:返回的 stop() 是**普通对象的方法**,里面的 this 指向那个对象而不是 watcher。
868
+ // 必须先把锁路径与 pid 捕获成局部量,否则 releaseLock(undefined) 会静默失败、锁永不释放。
869
+ const lockPath = this.lockPath;
870
+ const pid = this.pid;
871
+ let stopped = false;
872
+ let handle = null;
873
+ const loop = async () => {
874
+ if (stopped) return;
875
+ try {
876
+ const r = await this.tick();
877
+ const okCount = r.results.filter((x) => !x.error && !x.baseline).length;
878
+ const fetched = r.results.reduce((n, x) => n + (x.fetched ?? 0), 0);
879
+ if (fetched || r.failures) {
880
+ this.log("info", `watcher:${okCount}/${r.total} 个文件夹有变化,取到 ${fetched} 封,失败 ${r.failures}`);
881
+ }
882
+ } catch (e) {
883
+ this.log("error", `watcher 轮次异常: ${e?.message ?? e}`);
884
+ }
885
+ if (!stopped) handle = scheduler.timeout(loop, this.backoffMs);
886
+ };
887
+
888
+ handle = scheduler.timeout(loop, firstDelayMs);
889
+ this.log("info", `watcher 已启动:每 ${Math.round(this.intervalMs / 1000)}s 一轮,锁 ${lockPath}`);
890
+ return {
891
+ locked: true,
892
+ stop() {
893
+ stopped = true;
894
+ try { handle?.(); } catch { /* 已触发 */ }
895
+ releaseLock(lockPath, { pid });
896
+ },
897
+ };
898
+ }
899
+ }