dsh-fish-soul 0.19.1 → 0.19.4

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.19.1**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.4**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -164,7 +164,7 @@ async function handleOne(f, ctx) {
164
164
  * 把附件处理进消息正文:占位换成内容(或存下来的路径),处理不了的占位原样留着。
165
165
  * @param {string} text 原正文(里面有【文件:名字】占位)
166
166
  * @param {Array<{name?: string, path?: string, url?: string, size?: number}>} files 附件(顺序与占位一致)
167
- * @param {{readText?: boolean, saveBinary?: boolean, roots?: string[], dataDir?: string, messageId?: string, log?: (level: string, msg: string) => void}} opts
167
+ * @param {{readText?: boolean, saveBinary?: boolean, roots?: string[], dataDir?: string, messageId?: string, log?: (level: string, msg: string) => void, fetchFile?: (opts: any) => Promise<any>}} opts
168
168
  * @returns {{text: string, read: string[], saved: string[]}} read = 读进正文的附件名,saved = 落盘的绝对路径
169
169
  */
170
170
  export async function applyAttachments(text, files, opts = {}) {
package/lib/behavior.js CHANGED
@@ -290,18 +290,20 @@ export function normSentText(s) {
290
290
  }
291
291
 
292
292
  /**
293
- * 跨条复读守卫(纯逻辑):模型遇到相近的输入时偶尔把自己上一条消息一字不差地再发一遍
293
+ * 跨条复读守卫(纯逻辑):模型遇到相近的输入时偶尔把自己上一条消息一字不差或换个近义说法再发一遍
294
294
  * (2026-11-06 QQ 真实翻车:同一段内容隔 17 秒 / 43 秒各发了一次)。
295
295
  * history: [{ at, norm }](最近发出去的,norm 已规整化);paragraphs 里规整化后
296
- * ≥ minLen 字、且跟窗口 windowMs 内某条完全一致的,返回它们的下标。
296
+ * ≥ minLen 字、且跟窗口 windowMs 内某条完全一致或二元组相似度 ≥ threshold 的,返回它们的下标。
297
297
  * 短句允许重复("哈哈哈哈"这种不该误杀)。
298
298
  */
299
- export function findRepeatedParagraphs(history, paragraphs, { now = Date.now(), windowMs = 120000, minLen = 12 } = {}) {
299
+ export function findRepeatedParagraphs(history, paragraphs, { now = Date.now(), windowMs = 120000, minLen = 12, threshold = 0.8 } = {}) {
300
300
  const recent = (Array.isArray(history) ? history : []).filter((h) => now - Number(h?.at ?? 0) <= windowMs);
301
301
  const dups = [];
302
302
  (Array.isArray(paragraphs) ? paragraphs : []).forEach((p, i) => {
303
303
  const n = normSentText(p);
304
- if ([...n].length >= minLen && recent.some((h) => h.norm === n)) dups.push(i);
304
+ if ([...n].length >= minLen && recent.some((h) => h.norm === n || ([...String(h?.norm ?? '')].length >= minLen && bigramDice(h.norm, n) >= threshold))) {
305
+ dups.push(i);
306
+ }
305
307
  });
306
308
  return dups;
307
309
  }
@@ -621,15 +623,21 @@ export class DiaryWriter {
621
623
  const start = Date.parse(`${date}T00:00:00+08:00`);
622
624
  const end = start + DAY;
623
625
  const db = this.db;
624
- const eps = db.prepare(`SELECT m.content, p.display_name AS name FROM memory m LEFT JOIN person p ON ('user:' || p.canonical_id) = m.owner_id
625
- WHERE m.character_id = 'feiyu' AND m.kind = 'episode' AND m.status = 'active' AND m.created_at >= ? AND m.created_at < ? ORDER BY m.created_at LIMIT 20`).all(start, end);
626
+ const eps = db.prepare(`SELECT m.content, m.owner_id, p.display_name AS name FROM memory m LEFT JOIN person p ON ('user:' || p.canonical_id) = m.owner_id
627
+ WHERE m.character_id = 'feiyu' AND m.kind = 'episode' AND m.status = 'active' AND m.created_at >= ? AND m.created_at < ? ORDER BY m.created_at DESC LIMIT 20`).all(start, end).reverse();
626
628
  const self = db.prepare(`SELECT content FROM memory WHERE character_id = 'feiyu' AND owner_id = 'self' AND kind <> 'diary' AND status = 'active'
627
629
  AND created_at >= ? AND created_at < ? ORDER BY created_at LIMIT 10`).all(start, end);
628
630
  const recent = db.prepare(`SELECT content FROM memory WHERE character_id = 'feiyu' AND owner_id = 'self' AND kind = 'diary' AND status = 'active'
629
631
  AND created_at < ? ORDER BY created_at DESC LIMIT 3`).all(start).map((x) => x.content.replace(/^[\d-]+ 的日记:/, '').replace(/\s+/g, ' ').slice(0, 120));
630
632
  // 日记只写真实发生的事:自走排程是虚拟计划不是经历,不进日记材料(2026-11-06 主人反馈)。
631
633
  return {
632
- episodes: eps.map((e) => `${e.name ? `和${e.name}:` : ''}${e.content}`), self: self.map((s) => s.content), recent
634
+ episodes: eps.map((e) => `${e.name ? `和${e.name}:` : ''}${e.content}`), self: self.map((s) => s.content), recent,
635
+ // #217:今天真的跟她说过话的人(私聊小结的 owner 是人;群的 owner 是群,排除)。
636
+ // 日记要让模型挑「想跟谁聊」,以前压根没给名单,模型只能编称呼(「主人」「某UP主」),
637
+ // 和 display_name 永远对不上 ⇒ ownerId 恒为 null ⇒ 那一行永远注入不出来。
638
+ people: [...new Map(eps
639
+ .filter((e) => typeof e.owner_id === 'string' && e.owner_id.startsWith('user:') && e.name)
640
+ .map((e) => [e.owner_id, { ownerId: e.owner_id, name: e.name }])).values()]
633
641
  };
634
642
  }
635
643
 
@@ -662,7 +670,12 @@ export class DiaryWriter {
662
670
  `今天聊过的:\n${mat.episodes.map((e) => `- ${e}`).join('\n') || '(没怎么聊天)'}\n` +
663
671
  (mat.self.length ? `今天自己说过的事:\n${mat.self.map((e) => `- ${e}`).join('\n')}\n` : '') +
664
672
  '今天实在平淡,日记就写一两句平淡本身也行,不要硬凑。\n' +
665
- '再想想明天想主动跟谁聊点什么(最多 3 条,没有就空)。\n' +
673
+ (mat.people.length
674
+ ? `再想想明天想主动跟谁聊点什么(最多 3 条,没有就空)。只能挑今天真的跟你说过话的这些人:\n` +
675
+ `${mat.people.map((p) => `- ${p.name}`).join('\n')}\n` +
676
+ (mat.people.some((p) => p.ownerId === 'user:master') ? '上面第一个是你的主人。' : '') +
677
+ 'who 必须原样照抄上面的名字(连括号都不要加),不要自己编称呼。刷到的视频作者、群里没跟你说过话的路人都不算。\n'
678
+ : '') +
666
679
  '只输出 JSON:{"diary":"……","topics":[{"who":"对方的名字","topic":"想聊的事(一句话)"}]}';
667
680
  const reply = await this.callLlm(prompt, { maxTokens: 1500, thinkFallback: true });
668
681
  const parsed = parseJson(reply) ?? {};
@@ -677,9 +690,38 @@ export class DiaryWriter {
677
690
  }
678
691
  this.lastFail = '';
679
692
  insertMemory(this.db, this.worker, { ownerId: 'self', channel: 'self', channelId: '', kind: 'diary', content: `${date} 的日记:${diary}`, importance: 2, private: true }, now);
680
- const topics = (Array.isArray(parsed.topics) ? parsed.topics : []).slice(0, 3).map((x) => ({
693
+ const whoOwner = (who) => {
694
+ // 引号 / 书名号 / 括号注解都剥掉:模型常写成「主人」「主人(我的主人)」。
695
+ // S1:全角弯引号 “ ” ‘ ’ 和 【】 中文模型很爱用,不剥就认不出。
696
+ const n = String(who ?? '')
697
+ .replace(/^[「『"'“”‘’《【]+|[」』"'“”‘’》】]+$/g, '')
698
+ .replace(/[((][^(())]*[))]$/, '')
699
+ .trim();
700
+ if (n === '') return null;
701
+ const hit = mat.people.find((p) => p.name === n);
702
+ if (hit) return hit.ownerId;
703
+ // 模型常把主人写成「主人」而不是他的 QQ 昵称 —— 这个称呼有唯一确定的语义。
704
+ // 名单里没有 master(主人今天没在小结里出现)时要落到库里的 master 行,
705
+ // 不能直接返回 null:master 行的默认 display_name 就是「主人」,
706
+ // 那样会把 findOwnerByName 本来能认的人挡掉(回归)。
707
+ if (/^(主人|master)$/i.test(n)) {
708
+ return mat.people.find((p) => p.ownerId === 'user:master')?.ownerId
709
+ ?? (this.db.prepare("SELECT 1 FROM person WHERE canonical_id = 'master'").get() ? 'user:master' : null);
710
+ }
711
+ // 名单外:今天聊过但小结还没整理出来的人,按名字回查一次(查不到就是不在场的人)。
712
+ return this.findOwnerByName?.(n) ?? null;
713
+ };
714
+ const parsedTopics = (Array.isArray(parsed.topics) ? parsed.topics : []).map((x) => ({
681
715
  who: String(x?.who ?? '').trim().slice(0, 24), topic: String(x?.topic ?? '').trim().slice(0, 80)
682
- })).filter((x) => x.topic !== '').map((x) => ({ ...x, ownerId: x.who ? this.findOwnerByName?.(x.who) ?? null : null }));
716
+ })).filter((x) => x.topic !== '').map((x) => ({ ...x, ownerId: whoOwner(x.who) }));
717
+ // 认不出人的不存:topicsFor 是按 ownerId 精确匹配的(`x.ownerId === ownerId`),
718
+ // null 永远匹配不上任何人 ⇒ 存下来一次都注入不出来,只是面板里一条用不上的装饰
719
+ // (#217 里 3 条有 2 条是刷到的视频作者)。
720
+ // 配额在过滤之后再截:先截会把「认不出的」和「认得出的」一起砍,
721
+ // 3 条垃圾就能把合法的那条挤掉,而这条已经丢掉就彻底没了。
722
+ const topics = parsedTopics.filter((x) => x.ownerId !== null).slice(0, 3);
723
+ const dropped = parsedTopics.length - topics.length;
724
+ if (dropped > 0) this.log('info', `[fish-soul] 日记有 ${dropped} 条想聊的对象认不出是谁,没存`);
683
725
  setKv(this.db, 'diary.topics', { date, at: now, items: topics });
684
726
  setKv(this.db, 'diary.last', date);
685
727
  this.note?.('diary', { title: '日记', reason: '写了今天的日记', text: diary });
@@ -0,0 +1,488 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fishSoulDir, getKv, setKv } from '../db.js';
4
+ import { BROWSER_KINDS, detectBrowsers, pickBrowser } from '../browsers.js';
5
+ import { getBrowser } from './vendor/douyin-bridge/browser.mjs';
6
+ import { HOOK_SOURCE, setCacheFile, startCollector } from './vendor/douyin-bridge/douyin-api.mjs';
7
+ import { COMMENT_BRIDGE_SOURCE } from './vendor/douyin-bridge/douyin-comment.js';
8
+ import { checkLogin } from './vendor/douyin-bridge/douyin-dm.mjs';
9
+ import { PARK_LEFT, parkWindow, showWindow, ensurePanel } from './vendor/douyin-bridge/douyin-panel.mjs';
10
+ import { DOUYIN_HOME, errText } from './douyin-pure.js';
11
+
12
+ const DEFAULT_PORT = 47890;
13
+ const CRASH_RETRY_MS = 30_000;
14
+ const CRASH_MAX = 3;
15
+ const CRASH_WINDOW_MS = 10 * 60_000;
16
+ const LOCK_MAX_MS = 4 * 60_000;
17
+
18
+ /**
19
+ * 专用浏览器的生命周期。所有会动页面的操作都走 exclusive()(一次只做一件事)。
20
+ */
21
+ export class DouyinHost {
22
+ /**
23
+ * @param {object} deps
24
+ * @param {import('node:sqlite').DatabaseSync} deps.db
25
+ * @param {() => object} deps.getConfig 返回 config.douyin
26
+ * @param {(level: string, msg: string) => void} [deps.log]
27
+ * @param {(key: string, text: string|null) => void} [deps.notify]
28
+ * @param {(browser: object) => Promise<any>} [deps.openPanel] 打开私信面板(测试里换假的)
29
+ */
30
+ constructor({ db, getConfig, log, notify, port, profileRoot, detect = detectBrowsers, launch = getBrowser, openPanel = ensurePanel } = {}) {
31
+ this.db = db;
32
+ this.getConfig = getConfig;
33
+ this.log = log ?? (() => {});
34
+ this.notify = notify ?? (() => {});
35
+ this.port = Number(port ?? process.env.FISH_SOUL_DOUYIN_PORT ?? DEFAULT_PORT) || DEFAULT_PORT;
36
+ this.profileRoot = profileRoot ?? join(fishSoulDir(), 'douyin-browser');
37
+ this.detect = detect;
38
+ this.launch = launch;
39
+ this.openPanel = openPanel;
40
+ this.browser = null;
41
+ this.info = null;
42
+ this.browsers = null;
43
+ this.state = 'stopped';
44
+ this.lastError = '';
45
+ this.loggedIn = null;
46
+ this.stopCollector = null;
47
+ this.targetGoneAt = 0;
48
+ this.exitZeroAt = 0;
49
+ this.crashes = [];
50
+ this.retryTimer = null;
51
+ this.starting = null;
52
+ this.disposed = false;
53
+ this.lock = Promise.resolve();
54
+ this.busy = '';
55
+ this.cacheReady = false;
56
+ this.windowShown = false; // 后台模式下,设置页点了「显示一下」
57
+ }
58
+
59
+ /** 窗口模式:background = 停在屏幕外不打扰(默认),visible = 跟普通窗口一样。 */
60
+ windowMode() {
61
+ return this.getConfig()?.window === 'visible' ? 'visible' : 'background';
62
+ }
63
+
64
+ effectiveWindowMode() {
65
+ return this.windowMode() === 'visible' || this.windowShown ? 'visible' : 'background';
66
+ }
67
+
68
+ /** 后台模式下把窗口停回屏幕外(已经停好的不动)。 */
69
+ async tidyWindow() {
70
+ if (!this.running || this.effectiveWindowMode() !== 'background') return false;
71
+ try { return await parkWindow(this.browser); } catch { return false; }
72
+ }
73
+
74
+ /** 设置页「显示一下」:挪回屏幕里,直到点「藏起来」。 */
75
+ async showWindow() {
76
+ this.windowShown = true;
77
+ if (!this.running) return false;
78
+ try { return await showWindow(this.browser); } catch (error) {
79
+ this.log('warn', `[fish-soul] 抖音浏览器窗口挪不回来:${errText(error)}`);
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /** 设置页「藏起来」/ 换回后台模式。 */
85
+ async hideWindow() {
86
+ this.windowShown = false;
87
+ return this.tidyWindow();
88
+ }
89
+
90
+ get paused() {
91
+ return getKv(this.db, 'douyin.browser.paused', false) === true;
92
+ }
93
+
94
+ setPaused(v, why = '') {
95
+ setKv(this.db, 'douyin.browser.paused', v === true);
96
+ if (v === true) setKv(this.db, 'douyin.browser.pausedWhy', why);
97
+ }
98
+
99
+ get running() {
100
+ return this.state === 'running' && this.browser !== null && this.browser.isAlive();
101
+ }
102
+
103
+ browserPref() {
104
+ const b = this.getConfig()?.browser ?? {};
105
+ return { kind: String(b.kind ?? 'edge') || 'edge', customPath: String(b.customPath ?? '').trim() };
106
+ }
107
+
108
+ async rescan() {
109
+ try { this.browsers = await this.detect(); } catch (error) {
110
+ this.browsers = [];
111
+ this.log('warn', `[fish-soul] 找浏览器失败:${errText(error)}`);
112
+ }
113
+ return this.browsers;
114
+ }
115
+
116
+ async listBrowsers() {
117
+ if (this.browsers === null) await this.rescan();
118
+ return this.browsers;
119
+ }
120
+
121
+ extraArgs() {
122
+ const args = ['--mute-audio'];
123
+ // 后台模式:一启动就在屏幕外(命令行位置不会被浏览器夹回屏幕里),不闪一下
124
+ if (this.effectiveWindowMode() === 'background') args.push(`--window-position=${PARK_LEFT},0`);
125
+ const env = String(process.env.FISH_SOUL_DOUYIN_ARGS ?? '').trim();
126
+ // 按「空格 + --」切,参数值里可以带空格(例如 --host-resolver-rules=MAP a b)
127
+ if (env !== '') args.push(...env.split(/\s+(?=--)/).map((a) => a.trim()).filter((a) => a.startsWith('--')));
128
+ return args;
129
+ }
130
+
131
+ /**
132
+ * 启动(或连上已经在跑的)专用浏览器。resume=true 表示用户点了「启动」:清掉暂停标记。
133
+ * 用户关窗口后的暂停状态下,自动流程(插件启动、定时器)不会把窗口再弹出来。
134
+ */
135
+ async start({ resume = false } = {}) {
136
+ if (this.disposed) return false;
137
+ if (resume) { this.setPaused(false); this.crashes = []; }
138
+ if (this.paused) { this.state = 'paused'; return false; }
139
+ if (this.running) return true;
140
+ this.starting ??= this.doStart().finally(() => { this.starting = null; });
141
+ return await this.starting;
142
+ }
143
+
144
+ async doStart() {
145
+ clearTimeout(this.retryTimer);
146
+ this.retryTimer = null;
147
+ this.state = 'starting';
148
+ const list = await this.listBrowsers();
149
+ const info = pickBrowser(list, this.browserPref());
150
+ if (info === null) {
151
+ this.state = 'error';
152
+ this.lastError = this.browserPref().customPath ? '手动指定的浏览器路径不存在' : '没找到 Edge / Chrome 等 Chromium 系浏览器';
153
+ return false;
154
+ }
155
+ // 换了浏览器:先把旧的关掉(两个浏览器不能共用调试端口)
156
+ if (this.browser !== null && this.info !== null && this.info.path !== info.path) await this.quitBrowser();
157
+ this.info = info;
158
+ const userDataDir = join(this.profileRoot, info.kind);
159
+ try {
160
+ mkdirSync(userDataDir, { recursive: true });
161
+ if (!this.cacheReady) { setCacheFile(join(fishSoulDir(), 'douyin-im-cache.json')); this.cacheReady = true; }
162
+ if (this.browser !== null) { try { this.browser.detach(); } catch { /* 已断 */ } this.browser = null; }
163
+ let b = null;
164
+ b = await this.launch({
165
+ exe: info.path,
166
+ userDataDir,
167
+ port: this.port,
168
+ log: (msg) => this.log('info', `[fish-soul] 抖音浏览器:${msg}`),
169
+ reuse: true,
170
+ preloadScripts: [HOOK_SOURCE, COMMENT_BRIDGE_SOURCE],
171
+ extraArgs: this.extraArgs(),
172
+ onDead: (code) => { if (b !== null) this.onDead(b, code); }
173
+ });
174
+ if (this.disposed) { try { b.detach(); } catch { /* 已断 */ } return false; }
175
+ b.onDead = (code) => this.onDead(b, code);
176
+ b.onEvent = (msg) => this.onEvent(b, msg);
177
+ b.windowMode = () => this.effectiveWindowMode(); // douyin-panel 的 ensureWindowVisible 看这个
178
+ try { await b.send('Target.setDiscoverTargets', { discover: true }); } catch { /* 老版本没有也不要紧 */ }
179
+ this.browser = b;
180
+ this.targetGoneAt = 0;
181
+ this.exitZeroAt = 0;
182
+ this.state = 'running';
183
+ this.lastError = '';
184
+ this.notify('douyin.browser', null);
185
+ this.stopCollector?.();
186
+ this.stopCollector = startCollector(b);
187
+ await this.tidyWindow(); // 连上的是早就开着的浏览器 / 命令行位置没生效:现在停出去
188
+ const href = await b.eval('location.href').catch(() => '');
189
+ if (!/^https:\/\/[^/]*douyin\.com\//.test(String(href))) {
190
+ await this.exclusive('打开抖音', () => b.goto(DOUYIN_HOME, { settleMs: 6000 })).catch((error) => {
191
+ this.log('warn', `[fish-soul] 抖音首页没打开:${errText(error)}`);
192
+ });
193
+ }
194
+ this.log('info', `[fish-soul] 抖音专用浏览器已就绪(${info.name}${info.version ? ` ${info.version}` : ''})`);
195
+ return true;
196
+ } catch (error) {
197
+ this.state = 'error';
198
+ this.lastError = errText(error);
199
+ this.log('warn', `[fish-soul] 抖音浏览器启动失败:${this.lastError}`);
200
+ return false;
201
+ }
202
+ }
203
+
204
+ /** CDP 事件:我们的标签页被关了(用户关窗口 / 关标签页都会先有这个)。 */
205
+ onEvent(b, msg) {
206
+ if (b !== this.browser) return;
207
+ const p = msg.params ?? {};
208
+ const gone = (msg.method === 'Target.detachedFromTarget' && (p.sessionId === b.sessionId || p.targetId === b.targetId)) ||
209
+ (msg.method === 'Target.targetDestroyed' && p.targetId === b.targetId) ||
210
+ (msg.method === 'Inspector.detached' && msg.sessionId === b.sessionId);
211
+ if (!gone || this.targetGoneAt > 0) return;
212
+ this.targetGoneAt = Date.now();
213
+ // 浏览器还开着(只关了这个标签页):也算用户自己关的 → 暂停,断开连接但不关浏览器
214
+ // 整个浏览器在关时,标签页事件比 ws 关闭早一两秒到、进程也还没被回收 —— 只看这些会误报成"关了标签页"。
215
+ // 用 CDP 端口确认浏览器是否真的还在:还在才算「只关了标签页」,没了就是浏览器关了。
216
+ setTimeout(async () => {
217
+ if (b !== this.browser || this.disposed) return;
218
+ // 端口探测失败也可能是偶发超时:隔一会儿再探一次,两次都没应答才算浏览器真的关了
219
+ const probe = async () => {
220
+ if (typeof b.probePort !== 'function') return true; // 兜底:没有探测能力的实现按"还开着"处理
221
+ try { return Boolean(await b.probePort()); } catch { return true; }
222
+ };
223
+ if (!(await probe())) {
224
+ await new Promise((r) => setTimeout(r, 800).unref?.());
225
+ if (b !== this.browser || this.disposed) return;
226
+ if (!(await probe())) {
227
+ // 端口已经没了 = 浏览器整个在关(进程可能还在收尾,ws 也可能还挂着)→ 按"浏览器关了"暂停
228
+ this.pauseByUser('你把抖音浏览器关了');
229
+ try { b.detach(); } catch { /* 已断 */ }
230
+ this.browser = null;
231
+ return;
232
+ }
233
+ }
234
+ if (b.ready && b.isAlive()) {
235
+ this.pauseByUser('你把抖音标签页关了');
236
+ try { b.detach(); } catch { /* 已断 */ }
237
+ this.browser = null;
238
+ }
239
+ }, 1500).unref?.();
240
+ }
241
+
242
+ onDead(b, code) {
243
+ if (b !== this.browser || this.disposed || this.state === 'closing') return;
244
+ if (code === 0) this.exitZeroAt = Date.now();
245
+ if (this.state !== 'running') return;
246
+ // 连接断了:等一下看看是不是用户关的(关窗口时先有标签页关闭事件 / 进程正常退出)
247
+ this.state = 'checking';
248
+ setTimeout(() => {
249
+ if (b !== this.browser || this.disposed || this.state !== 'checking') return;
250
+ this.stopCollector?.();
251
+ this.stopCollector = null;
252
+ const byUser = (this.targetGoneAt > 0 && Date.now() - this.targetGoneAt < 10_000) || (this.exitZeroAt > 0 && Date.now() - this.exitZeroAt < 10_000);
253
+ this.browser = null;
254
+ if (byUser) { this.pauseByUser('你把抖音浏览器关了'); return; }
255
+ this.onCrash();
256
+ }, 2000).unref?.();
257
+ }
258
+
259
+ pauseByUser(why) {
260
+ this.stopCollector?.();
261
+ this.stopCollector = null;
262
+ this.setPaused(true, why);
263
+ this.state = 'paused';
264
+ this.lastError = '';
265
+ this.log('info', `[fish-soul] ${why}:抖音先暂停,去设置页点「启动」恢复`);
266
+ }
267
+
268
+ onCrash() {
269
+ const now = Date.now();
270
+ this.crashes = this.crashes.filter((t) => now - t < CRASH_WINDOW_MS);
271
+ this.crashes.push(now);
272
+ if (this.crashes.length > CRASH_MAX) {
273
+ this.state = 'error';
274
+ this.lastError = `浏览器 10 分钟内断了 ${this.crashes.length} 次,先停下了;去设置页点「启动」重试`;
275
+ this.log('warn', `[fish-soul] ${this.lastError}`);
276
+ this.notify('douyin.browser', `抖音专用浏览器老是崩(${this.lastError})`);
277
+ return;
278
+ }
279
+ this.state = 'error';
280
+ this.lastError = `浏览器断开了,${CRASH_RETRY_MS / 1000} 秒后自动重连(第 ${this.crashes.length} 次)`;
281
+ this.log('warn', `[fish-soul] ${this.lastError}`);
282
+ clearTimeout(this.retryTimer);
283
+ // 重连本身失败也要吞掉:否则这次 reject 变成未处理拒绝,进程直接退出(连重试都没了)
284
+ this.retryTimer = setTimeout(() => { void this.start().catch((error) => this.log('warn', `[fish-soul] 抖音浏览器重连失败:${String(error instanceof Error ? error.message : error)}`)); }, CRASH_RETRY_MS);
285
+ this.retryTimer.unref?.();
286
+ }
287
+
288
+ async quitBrowser() {
289
+ const b = this.browser;
290
+ this.stopCollector?.();
291
+ this.stopCollector = null;
292
+ if (b === null) return;
293
+ this.state = 'closing';
294
+ try { await b.quit(); } catch { /* 已经没了 */ }
295
+ this.browser = null;
296
+ this.state = 'stopped';
297
+ }
298
+
299
+ /** 设置页「关闭浏览器」:真的关掉,并暂停(不会自己再开)。 */
300
+ async closeBrowser() {
301
+ clearTimeout(this.retryTimer);
302
+ this.retryTimer = null;
303
+ this.setPaused(true, '你在设置页关掉了抖音浏览器');
304
+ await this.quitBrowser();
305
+ this.state = 'paused';
306
+ this.loggedIn = null;
307
+ }
308
+
309
+ /** 插件卸载:只断开连接,浏览器留着(热重载后新实例直接连上)。 */
310
+ dispose() {
311
+ this.disposed = true;
312
+ clearTimeout(this.retryTimer);
313
+ this.stopCollector?.();
314
+ this.stopCollector = null;
315
+ if (this.browser !== null) { try { this.browser.detach(); } catch { /* 已断 */ } }
316
+ this.browser = null;
317
+ }
318
+
319
+ /**
320
+ * 互斥:同一时间只有一件事在动页面。
321
+ *
322
+ * 🔴 超时的语义是「**报错给调用方**」,不是「放锁让别人上」。
323
+ * 以前超时就 clearTimeout + 清 busy 直接放锁,但 `fn()` 本身没有被取消
324
+ * (没有 AbortSignal 传进去),它还在动页面 —— 下一件事(比如发私信)
325
+ * 立刻开始,两个操作抢同一个 CDP 会话 / 同一个输入框。实测:
326
+ * 读私信 3 分钟超时后发私信,`read:still-running` 在 `send:end` 之后才打印。
327
+ * `sendDM` 的 expectConvId 能兜住「发错人」,但兜不住「输入框被读操作清掉」。
328
+ *
329
+ * 现在:超时只让**调用方**拿到错误,锁要等 fn() 真正 settle 才放。
330
+ * 死锁风险由 maxMs 的报错 + 调用方超时兜底(不会永远挂着)。
331
+ */
332
+ exclusive(label, fn, { maxMs = LOCK_MAX_MS } = {}) {
333
+ const run = async () => {
334
+ this.busy = label;
335
+ let timer;
336
+ let timedOut = false;
337
+ // 让调用方先拿到超时错误,但 fn() 继续在锁内跑完
338
+ const work = (async () => {
339
+ await this.tidyWindow(); // 动页面之前:被最小化 / 拖回来了就停回屏幕外(后台模式)
340
+ return await fn();
341
+ })();
342
+ // work 的 rejection 必须有接收者:否则超时后它才抛错时会变成未处理拒绝
343
+ const guarded = work.then((v) => ({ ok: true, v }), (e) => ({ ok: false, e }));
344
+ let timeoutError = null;
345
+ const timeout = new Promise((resolve) => {
346
+ timer = setTimeout(() => { timedOut = true; timeoutError = new Error(`${label}超时`); resolve(null); }, maxMs);
347
+ timer.unref?.();
348
+ });
349
+ try {
350
+ const first = await Promise.race([guarded, timeout]);
351
+ if (!timedOut) {
352
+ // fn() 先结束(成功或真失败):直接交结果
353
+ if (first.ok) return first.v;
354
+ throw first.e;
355
+ }
356
+ // 超时了。注意这里**不能 await work** —— 那会让调用方也一起等,
357
+ // 「超时报错」就失去意义了(POLL_TIMEOUT_MS 就是用来及时脱身的)。
358
+ // 做法:把「放锁」这件事挂到 work 结束之后,run() 立刻带着超时错误返回,
359
+ // 但 this.lock 链上多挂一节,下一件事要等那一节完成才轮到。
360
+ this.busy = `${label}(超时,等它收尾)`;
361
+ const release = work.then(() => {}, () => {});
362
+ throw Object.assign(timeoutError, { __holdLock: release });
363
+ } finally {
364
+ clearTimeout(timer);
365
+ }
366
+ };
367
+ const p = this.lock.then(run, run);
368
+ // 超时的那一次会在错误上挂 `__holdLock`(等 fn 真收尾的 promise):
369
+ // 把它接到锁链上,下一件事就排在「收尾完成」之后,而不是和它并发。
370
+ this.lock = p.then(
371
+ () => {},
372
+ (error) => {
373
+ const hold = error?.__holdLock;
374
+ if (hold === undefined) return;
375
+ return hold.then(() => { if (this.busy.endsWith('(超时,等它收尾)')) this.busy = ''; });
376
+ },
377
+ );
378
+ return p;
379
+ }
380
+
381
+ /**
382
+ * 刷新抖音页面(#72)。
383
+ *
384
+ * 抖音页面放久了会被浏览器「睡」掉 —— 标签页被丢弃 / 渲染进程被冻结,
385
+ * 表现成页面白屏、选择器一个都命中不了(自检必然不过),手动刷新一下就恢复。
386
+ * 刷新完把私信面板重新打开:刷新后面板是关着的,
387
+ * 而自检的关键项之一 conversationItem 只在面板开着时才有。
388
+ *
389
+ * ⚠️ 调用方必须已经在 exclusive() 里 —— 这里不再抢锁(自己抢自己的锁会死锁)。
390
+ * @returns {Promise<boolean>} 刷新 + 面板开回来了没有
391
+ */
392
+ async refresh() {
393
+ if (!this.running) return false;
394
+ const b = this.browser;
395
+ try {
396
+ const href = String(await b.eval('location.href').catch(() => '') || '');
397
+ if (/^https?:\/\/[^/]*douyin\.com(\/|$)/.test(href)) {
398
+ if (typeof b.reload === 'function') await b.reload({ settleMs: 6000 });
399
+ else await b.goto(href, { settleMs: 6000 });
400
+ } else {
401
+ // 已经跑到 about:blank / 别的站上去了:刷新没意义,直接回抖音
402
+ await b.goto(DOUYIN_HOME, { settleMs: 8000 });
403
+ }
404
+ } catch (error) {
405
+ this.log('warn', `[fish-soul] 刷新抖音页面失败:${errText(error)}`);
406
+ return false;
407
+ }
408
+ // 面板另算:刷新后私信面板是关着的,自检的关键项 conversationItem 只在面板开着时才有。
409
+ // 面板开不成不算刷新失败(自检重跑会自己判),只记一笔。
410
+ try { await this.openPanel(b); } catch (error) {
411
+ this.log('warn', `[fish-soul] 刷新后私信面板没打开:${errText(error)}`);
412
+ }
413
+ this.log('info', '[fish-soul] 抖音页面已刷新');
414
+ return true;
415
+ }
416
+
417
+ async checkLogin() {
418
+ if (!this.running) return null;
419
+ try {
420
+ const r = await checkLogin(this.browser);
421
+ this.loggedIn = r.loggedIn === true;
422
+ } catch { /* 这次看不了 */ }
423
+ return this.loggedIn;
424
+ }
425
+
426
+ /** 登录用的截图(jpeg,小一点)。 */
427
+ async screenshot() {
428
+ if (!this.running) return null;
429
+ const b = this.browser;
430
+ const r = await b.send('Page.captureScreenshot', { format: 'jpeg', quality: 60 }, b.sessionId);
431
+ const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId).catch(() => null);
432
+ const vp = m?.cssVisualViewport ?? m?.cssLayoutViewport ?? {};
433
+ return { jpeg: Buffer.from(r.data, 'base64'), width: Math.round(vp.clientWidth ?? 0), height: Math.round(vp.clientHeight ?? 0) };
434
+ }
435
+
436
+ /** 设置页里点截图 → 转成页面上的一次点击(xr / yr 是 0–1 的相对坐标)。 */
437
+ async click(xr, yr) {
438
+ if (!this.running) return false;
439
+ const b = this.browser;
440
+ const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId);
441
+ const vp = m?.cssVisualViewport ?? m?.cssLayoutViewport ?? {};
442
+ const x = Math.round(Math.min(1, Math.max(0, Number(xr))) * (vp.clientWidth ?? 0));
443
+ const y = Math.round(Math.min(1, Math.max(0, Number(yr))) * (vp.clientHeight ?? 0));
444
+ for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
445
+ await b.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: type === 'mouseMoved' ? 0 : 1 }, b.sessionId);
446
+ }
447
+ return true;
448
+ }
449
+
450
+ /** 没有 sharp 时的 webp → png(在专用浏览器里用 canvas 画一遍;动图只留第一帧)。 */
451
+ async canvasConvert(bytes) {
452
+ if (!this.running) return null;
453
+ const b64 = Buffer.from(bytes).toString('base64');
454
+ const out = await this.exclusive('转图片', () => this.browser.eval(`(async () => {
455
+ const bin = atob(${JSON.stringify(b64)});
456
+ const arr = new Uint8Array(bin.length);
457
+ for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
458
+ const bmp = await createImageBitmap(new Blob([arr], { type: 'image/webp' }));
459
+ const c = new OffscreenCanvas(bmp.width, bmp.height);
460
+ c.getContext('2d').drawImage(bmp, 0, 0);
461
+ const blob = await c.convertToBlob({ type: 'image/png' });
462
+ const u = new Uint8Array(await blob.arrayBuffer());
463
+ let s = '';
464
+ for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode.apply(null, u.subarray(i, i + 0x8000));
465
+ return btoa(s);
466
+ })()`), { maxMs: 30_000 });
467
+ return typeof out === 'string' && out !== '' ? Buffer.from(out, 'base64') : null;
468
+ }
469
+
470
+ status() {
471
+ const pref = this.browserPref();
472
+ return {
473
+ state: this.paused && this.state !== 'running' ? 'paused' : this.state,
474
+ paused: this.paused,
475
+ pausedWhy: this.paused ? String(getKv(this.db, 'douyin.browser.pausedWhy', '') ?? '') : '',
476
+ lastError: this.lastError,
477
+ busy: this.busy,
478
+ loggedIn: this.loggedIn,
479
+ browser: this.info === null ? null : { kind: this.info.kind, name: this.info.name, version: this.info.version, path: this.info.path },
480
+ pref,
481
+ browsers: (this.browsers ?? []).map((b) => ({ kind: b.kind, name: b.name, version: b.version, path: b.path })),
482
+ kinds: Object.keys(BROWSER_KINDS),
483
+ port: this.port,
484
+ window: this.windowMode(),
485
+ windowShown: this.windowShown
486
+ };
487
+ }
488
+ }