@glittering0717/ai-browser 2.4.3 → 2.4.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.4.3",
3
+ "version": "2.4.5",
4
4
  "description": "AI-native browser — renders pixels for humans, structured semantic-tree API for agents. No screenshots, no OCR, no coordinate guessing.",
5
5
  "main": "src/main/index.js",
6
6
  "bin": {
@@ -96,8 +96,21 @@ function parseArgs(argv) {
96
96
  // 文件(由下面的 icon 选项显式指定,从源目录读取),
97
97
  // 目录里的 svg/png/iconset 都不该随包分发;src 里也没有
98
98
  // 任何地方引用 build/。
99
+ // ⚠️ 顶层名单必须用 `^` 锚死,不能用 `(^|\/)`。
100
+ // 历史事故(2026-10-30 实测已发布 asar):`dist` 用任意层级匹配,于是
101
+ // **依赖自己的 dist/ 目录**也被删了 —— @modelcontextprotocol/sdk 677 个文件里
102
+ // 674 个没进包(只剩 package.json/README/LICENSE)、ajv 缺 337/466、hono 缺 559/562。
103
+ // prune 认为它们是生产依赖要留着,黑名单却把内容删了:包内依赖树不自洽,
104
+ // 构建照样"成功",只有真去 require 的那一刻才炸。目录名(dist/build/docs/…)
105
+ // 在 node_modules 深处同名是**别人的东西**,不该由我们替它删。
99
106
  const IGNORE = new RegExp(
100
- '(^|\\/)(\\.git|outputs|docs|e2e|tests|dist|build|node_modules\\/\\.cache|node_modules\\/\\.bin|node_modules\\/electron|tools\\/_oneoff)(\\/|$)'
107
+ // ① 仓库顶层才剔的(这些名字一旦出现在 node_modules 里,是包自己的产物目录)
108
+ // 前导 `\\/?` 不能省:packager 传给 ignore 的路径是**带前导分隔符**的
109
+ // ('/outputs/xxx.png'),只写 `^` 会让整条规则静默失效 —— 实测体积从
110
+ // 12.5MB 涨到 89MB(outputs/ 的取证截图、tools/_oneoff/ 的 logo 母版全打进去了)。
111
+ '^\\/?(?:\\.git|outputs|docs|e2e|tests|dist|build|tools|\\.github|\\.trae|\\.trae-html-share-packages|\\.exec-trail|\\.workbuddy)(\\/|$)'
112
+ // ② node_modules 里只剔明确不该随包分发的:构建工具链、纯类型、测试依赖
113
+ + '|(^|\\/)node_modules\\/(electron|\\.cache|\\.bin|@vitest|@esbuild|@types|@electron|jsdom|vitest)(\\/|$)'
101
114
  );
102
115
 
103
116
  function run(cmd, args, opts = {}) {
@@ -296,6 +309,11 @@ function build(packager, args) {
296
309
  const appPath = path.join(destRoot, bundledApp);
297
310
 
298
311
  const size = dirSize(appPath);
312
+ // 打包后自检(2026-10-30 加的硬闸门):asar 里每个依赖声明的入口必须真的
313
+ // 在包里。历史上 IGNORE 用 `(^|\/)dist(\/|$)` 把依赖的 dist/ 删了 ——
314
+ // 包内依赖树不自洽,构建却报成功,只有装到用户机器上 require 时才炸。
315
+ // 这一条把"打成功了"从主观变成可验证:入口文件不在就直接 fail。
316
+ require('./verify_asar.cjs').assertAsarDeps(appPath);
299
317
  console.log(`[build] app bundle: ${appPath}`);
300
318
  console.log(`[build] app size: ${mb(size)}`);
301
319
  installIcon(appPath);
@@ -25,8 +25,14 @@ const OUT_DIR = path.join(root, 'dist');
25
25
 
26
26
  // 与 build_dmg.cjs 完全一致的黑名单:测试/文档/构建产物/Electron 发行版/图标母版
27
27
  // 都不进安装包(src 里 from 'electron' 由 Electron 内置模块解析,不经 node_modules)。
28
+ // ⚠️ 顶层名单必须 `^` 锚死:`dist` 若按任意层级匹配,会把**依赖自己的 dist/**
29
+ // 一起删掉(实测 @modelcontextprotocol/sdk 缺 674/677、ajv 缺 337、hono 缺 559),
30
+ // 包内依赖树不自洽而构建照样"成功"。与 build_dmg.cjs 保持完全一致。
28
31
  const IGNORE = new RegExp(
29
- '(^|\\/)(\\.git|outputs|docs|e2e|tests|dist|build|node_modules\\/\\.cache|node_modules\\/\\.bin|node_modules\\/electron|tools\\/_oneoff)(\\/|$)'
32
+ // 前导 `\\/?` 不能省:packager 传进来的路径带前导分隔符('/outputs/x.png'),
33
+ // 只写 `^` 会让整条规则静默失效(实测体积 12.5MB → 89MB)。
34
+ '^\\/?(?:\\.git|outputs|docs|e2e|tests|dist|build|tools|\\.github|\\.trae|\\.trae-html-share-packages|\\.exec-trail|\\.workbuddy)(\\/|$)'
35
+ + '|(^|\\/)node_modules\\/(electron|\\.cache|\\.bin|@vitest|@esbuild|@types|@electron|jsdom|vitest)(\\/|$)'
30
36
  );
31
37
 
32
38
  // 复用本地已下载好的 electron-v<version>-win32-x64.zip,避免每次联网从 GitHub 拉
@@ -91,6 +97,9 @@ function build(packager) {
91
97
  console.log(`[build:win] 产物目录:${out}`);
92
98
  console.log(`[build:win] 可执行文件:${ok ? exe : '(未找到 ' + exe + ')'}`);
93
99
  if (!ok) process.exit(1);
100
+ // 与 build_dmg 同一条闸门:asar 里每个依赖声明的入口必须真的在包里。
101
+ // 打包"成功"不等于产物可用 —— 黑名单写宽会把依赖的 dist/ 删掉而构建照绿。
102
+ require('./verify_asar.cjs').assertAsarDeps(out);
94
103
  return paths;
95
104
  });
96
105
  }
@@ -0,0 +1,223 @@
1
+ // scripts/verify_asar.cjs — 打包后自检:asar 里的依赖必须自洽。
2
+ //
3
+ // # 为什么需要这一步(2026-10-30 实测)
4
+ //
5
+ // IGNORE 是一个**按路径删除**的黑名单。写宽了就把依赖的代码删掉,而构建照样
6
+ // 报"成功":实测已发布 v2.4.3 的 app.asar 里,@modelcontextprotocol/sdk 的
7
+ // 677 个文件只剩 3 个(package.json / README / LICENSE),ajv 缺 337/466,
8
+ // hono 缺 559/562 —— `prune` 认为它们是生产依赖要留着,黑名单却把内容删了。
9
+ // 这种包内依赖树不自洽的产物,只有真正 `require` 到它的那一刻才炸,
10
+ // 而那时用户已经装上了。
11
+ //
12
+ // # 判据
13
+ //
14
+ // 对 asar 里出现的每个包(有 package.json 的),把它声明的入口(main / exports
15
+ // 的 '.' 条件导出)解析成相对路径,然后要求 at least one 候选**真的在包里**;
16
+ // 一个都不在就判违规。不猜语义、不看体积,只问"你说你有入口,那个文件在哪"。
17
+ //
18
+ // 用法(也可单独跑):
19
+ // node scripts/verify_asar.cjs "dist/AI Browser-darwin-arm64/AI Browser.app"
20
+ 'use strict';
21
+
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+
25
+ /** 在给定目录里找 app.asar(mac 是 Contents/Resources,win/linux 是 resources)。 */
26
+ function findAsar(dir) {
27
+ const direct = [
28
+ path.join(dir, 'Contents', 'Resources', 'app.asar'),
29
+ path.join(dir, 'resources', 'app.asar'),
30
+ path.join(dir, 'app.asar'),
31
+ ].find((p) => fs.existsSync(p));
32
+ if (direct) return direct;
33
+ // 兜底:向下找两层(packager 的外层目录里套着 .app / 应用目录)
34
+ const stack = [{ d: dir, depth: 0 }];
35
+ while (stack.length) {
36
+ const { d, depth } = stack.pop();
37
+ let ents;
38
+ try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { continue; }
39
+ for (const e of ents) {
40
+ const full = path.join(d, e.name);
41
+ if (e.isFile() && e.name === 'app.asar') return full;
42
+ if (e.isDirectory() && depth < 3) stack.push({ d: full, depth: depth + 1 });
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+
48
+ /**
49
+ * 把 package.json 的入口声明解析成相对路径候选(去掉 './' 前缀)。
50
+ *
51
+ * 必须**递归**条件导出:`exports['.']` 既可能是字符串,也可能是
52
+ * `{node:{require,import}}` 这种嵌套条件对象(pkce-challenge 就是),
53
+ * 只取一层会把一个完全正常的包报成"缺入口"。
54
+ */
55
+ function entryCandidates(pkg) {
56
+ const out = [];
57
+ const norm = (v) => String(v).replace(/^\.\//, '').replace(/^\/+/, '');
58
+ const walk = (v, depth) => {
59
+ if (depth > 4 || v === null || v === undefined) return;
60
+ if (typeof v === 'string') { out.push(norm(v)); return; }
61
+ if (typeof v !== 'object') return;
62
+ for (const k of ['node', 'require', 'import', 'default', 'browser']) {
63
+ if (v[k] !== undefined) walk(v[k], depth + 1);
64
+ }
65
+ };
66
+ if (typeof pkg.main === 'string') out.push(norm(pkg.main));
67
+ const ex = pkg.exports;
68
+ if (typeof ex === 'string') out.push(norm(ex));
69
+ else if (ex && typeof ex === 'object') {
70
+ const dot = ex['.'] !== undefined ? ex['.'] : null;
71
+ walk(dot, 0);
72
+ }
73
+ return [...new Set(out)].filter(Boolean); // "" / undefined 不算入口
74
+ }
75
+
76
+ /**
77
+ * @param {string} target 打包产物目录(.app 或 win 的便携目录)
78
+ * @param {{sourceNodeModules?: string}} [opts] 源 node_modules(默认 <cwd>/node_modules)
79
+ * @returns {{ok:boolean, asar:string|null, checked:number, typesOnly:number, violations:Array, skippedReason?:string}}
80
+ *
81
+ * 两条判据,都必须与**源 node_modules 对照**才准:
82
+ * A. 声明了入口(main / exports '.')、源目录里确实有、包里却没有 → 是我们删的。
83
+ * 反过来"源里也没有"是包自己的事(实测 @modelcontextprotocol/sdk 1.29 声明了
84
+ * dist/cjs/index.js 但根本没发这个文件,我们只走子路径导入,报它就是误报)。
85
+ * B. 内容塌缩:源里有 N 个运行时文件,包里剩不到一半 → 被黑名单删掉一大片。
86
+ * 这条专门对付历史事故那种形态(677 个文件只剩 3 个),而且不依赖入口声明。
87
+ */
88
+ function verifyAsarDeps(target, opts = {}) {
89
+ let asarMod = null;
90
+ try {
91
+ asarMod = require('@electron/asar');
92
+ } catch (_) {
93
+ return { ok: true, asar: null, checked: 0, typesOnly: 0, violations: [], skippedReason: '缺少 @electron/asar,跳过校验' };
94
+ }
95
+
96
+ const srcNM = opts.sourceNodeModules || path.join(process.cwd(), 'node_modules');
97
+ const asarPath = findAsar(target);
98
+ if (!asarPath) {
99
+ return { ok: false, asar: null, checked: 0, typesOnly: 0, violations: [{ pkg: '(app.asar)', entry: '找不到 app.asar', why: '' }] };
100
+ }
101
+
102
+ const entries = new Set(asarMod.listPackage(asarPath).map((p) => p.replace(/^\//, '')));
103
+
104
+ // 与 Node 的解析规则一致:无扩展名要试 .js/.json/.node,目录要退到 index.*
105
+ const SUFFIX = ['', '.js', '.json', '.node', '/index.js', '/index.json', '/index.node'];
106
+ const asarHas = (rel) => {
107
+ for (const sfx of SUFFIX) {
108
+ if (entries.has(rel + sfx)) return true;
109
+ const prefix = rel + sfx + '/';
110
+ for (const e of entries) if (e.startsWith(prefix)) return true;
111
+ }
112
+ return false;
113
+ };
114
+ const toSrc = (rel) => path.join(srcNM, rel.replace(/^node_modules\//, ''));
115
+ const srcHas = (rel) => {
116
+ for (const sfx of SUFFIX) {
117
+ if (fs.existsSync(toSrc(rel + sfx))) return true;
118
+ }
119
+ return false;
120
+ };
121
+
122
+ // 运行时文件数(.js/.cjs/.mjs/.node)—— 只数代码,不数 README/类型声明,
123
+ // 否则"删掉代码但留下文档"这种形态会被平均数掩盖。
124
+ const isRuntime = (p) => /\.(js|cjs|mjs|node)$/.test(p);
125
+ const asarRuntimeCount = (pkgDir) => {
126
+ let n = 0;
127
+ const prefix = pkgDir + '/';
128
+ for (const e of entries) if (e.startsWith(prefix) && isRuntime(e)) n++;
129
+ return n;
130
+ };
131
+ const srcRuntimeCount = (pkgDir) => {
132
+ const base = toSrc(pkgDir);
133
+ let n = 0;
134
+ const stack = [base];
135
+ while (stack.length) {
136
+ const d = stack.pop();
137
+ let ents;
138
+ try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { continue; }
139
+ for (const e of ents) {
140
+ const full = path.join(d, e.name);
141
+ if (e.isDirectory()) stack.push(full);
142
+ else if (isRuntime(e.name)) n++;
143
+ }
144
+ }
145
+ return n;
146
+ };
147
+
148
+ const violations = [];
149
+ let checked = 0;
150
+ let typesOnly = 0;
151
+ const pkgJsonPaths = [...entries].filter((p) => /^node_modules\/(?:@[^/]+\/)?[^/]+\/package\.json$/.test(p));
152
+ for (const pj of pkgJsonPaths) {
153
+ const pkgDir = pj.slice(0, -'/package.json'.length);
154
+ const pkgName = pkgDir.replace(/^node_modules\//, '');
155
+ checked++;
156
+ let meta = null;
157
+ try {
158
+ meta = JSON.parse(asarMod.extractFile(asarPath, pj).toString('utf8'));
159
+ } catch (_) {
160
+ violations.push({ pkg: pkgName, entry: '(package.json 无法解析)', why: '' });
161
+ continue;
162
+ }
163
+
164
+ // A:入口文件被我们删了
165
+ const cands = entryCandidates(meta);
166
+ if (cands.length) {
167
+ const inSrc = cands.some((c) => srcHas(pkgDir + '/' + c));
168
+ const inAsar = cands.some((c) => asarHas(pkgDir + '/' + c));
169
+ if (inSrc && !inAsar) {
170
+ violations.push({ pkg: pkgName, entry: cands.join(' | '), why: '入口在 node_modules 里有,没进包' });
171
+ } else if (!cands.length) {
172
+ typesOnly++;
173
+ }
174
+ } else {
175
+ typesOnly++; // 没声明根入口(纯类型包 / 只暴露子路径):无根入口可验
176
+ }
177
+
178
+ // B:内容塌缩
179
+ const sc = srcRuntimeCount(pkgDir);
180
+ const ac = asarRuntimeCount(pkgDir);
181
+ if (sc >= 5 && ac < sc * 0.5) {
182
+ violations.push({ pkg: pkgName, entry: '运行时文件 ' + ac + '/' + sc, why: '被删掉一大半' });
183
+ }
184
+ }
185
+
186
+ return { ok: violations.length === 0, asar: asarPath, checked, typesOnly, violations, skippedReason: undefined };
187
+ }
188
+
189
+ /** 供构建脚本调用:违规就抛,附上前 10 条便于当场定位。 */
190
+ function assertAsarDeps(target) {
191
+ const r = verifyAsarDeps(target);
192
+ if (r.skippedReason) {
193
+ console.log(`[verify] ${r.skippedReason}`);
194
+ return r;
195
+ }
196
+ const rel = r.asar ? path.relative(process.cwd(), r.asar) : '(未找到)';
197
+ if (r.ok) {
198
+ console.log(`[verify] asar 依赖自洽:${r.checked} 个包,入口与内容都对得上 node_modules(其中 ${r.typesOnly} 个无根入口,按规则跳过)(${rel})`);
199
+ return r;
200
+ }
201
+ const head = r.violations.slice(0, 10).map((v) => ` - ${v.pkg} → ${v.entry}${v.why ? ' [' + v.why + ']' : ''}`).join('\n');
202
+ throw new Error(
203
+ `asar 里有 ${r.violations.length} 个依赖缺入口文件(声明了入口但包里没有):\n${head}`
204
+ + '\n这通常是 IGNORE 黑名单写宽了(按目录名删到了依赖自己的产物目录)。'
205
+ + '\n检查 scripts/build_*.cjs 的 IGNORE:顶层目录名必须用 ^ 锚死。'
206
+ );
207
+ }
208
+
209
+ module.exports = { findAsar, entryCandidates, verifyAsarDeps, assertAsarDeps };
210
+
211
+ if (require.main === module) {
212
+ const target = process.argv[2];
213
+ if (!target) {
214
+ console.error('用法: node scripts/verify_asar.cjs <产物目录>');
215
+ process.exit(2);
216
+ }
217
+ try {
218
+ assertAsarDeps(path.resolve(target));
219
+ } catch (e) {
220
+ console.error('[verify] FAILED: ' + e.message);
221
+ process.exit(1);
222
+ }
223
+ }
@@ -131,6 +131,11 @@ export class CanvasMonitor {
131
131
  return { accepted, dropped };
132
132
  }
133
133
 
134
+ /**
135
+ * 只丢抓取到的**数据**,保留该 tab 的配置(mode / hook / warnings)。
136
+ * `canvas_configure{clear:true}` 走这里 —— 它要的是"从零开始记",
137
+ * 不是"顺手把我刚设的 mode 也忘掉"。
138
+ */
134
139
  clear(tabId) {
135
140
  const st = this.tabs.get(tabId);
136
141
  if (!st) return { cleared_calls: 0 };
@@ -142,6 +147,20 @@ export class CanvasMonitor {
142
147
  return { cleared_calls: n };
143
148
  }
144
149
 
150
+ /**
151
+ * 彻底忘掉一个 tab(关 tab 时调用)。与 clear 的区别:
152
+ * 连 mode / hookInstalled / warnings 一起丢,并把 tabs 里的条目**删掉**。
153
+ *
154
+ * 为什么必须删条目:这个 Map 没有任何淘汰上限,而此前关 tab 只清数据、
155
+ * 留一个空 state 对象 —— 每关一页就多一条,长会话下无界累积(TODO 里
156
+ * "关掉的 tab 保留 canvas 抓取状态"指的就是这里)。之后 list/read 会按需重建,
157
+ * 行为不变。
158
+ */
159
+ forget(tabId) {
160
+ const had = this.tabs.delete(tabId);
161
+ return { forgotten: !!had };
162
+ }
163
+
145
164
  /** 列出该 tab 的 canvas。 */
146
165
  list(tabId) {
147
166
  const st = this._tab(tabId);
package/src/main/index.js CHANGED
@@ -18,6 +18,10 @@ import errorBanner from '../shared/error_banner.cjs';
18
18
  import viewLiveness from '../shared/view_liveness.cjs';
19
19
  const { isAlive, liveness } = viewLiveness;
20
20
  import { classifyShowReason, describeShowUrl } from '../shared/window_show.js';
21
+ // 地址栏跟随的挂载状态机(幂等 wire)。抽成模块是因为它原来写在闭包里,
22
+ // 判据只能 grep 源码 —— 实测监听累到 3 个时测试照样全绿。
23
+ import navFollow from '../shared/nav_follow.cjs';
24
+ const { createNavFollower } = navFollow;
21
25
 
22
26
  const __filename = fileURLToPath(import.meta.url);
23
27
  const __dirname = path.dirname(__filename);
@@ -486,7 +490,6 @@ let tabBarView = null;
486
490
  let pageManager = null;
487
491
  let tabRefreshInterval = null;
488
492
  let navStateInterval = null;
489
- let navStateWc = null;
490
493
  let networkWatchdog = null;
491
494
  let isQuitting = false;
492
495
  // 退出时固化会话 cookie 的一次性开关:cleanupAndQuit 分流用(见其注释),
@@ -520,12 +523,21 @@ if (gotLock) {
520
523
  }
521
524
  } catch (_) { /* 窗口正在销毁 */ }
522
525
  });
523
- } else if (!(process.platform === 'darwin' && app.isPackaged)) {
524
- // A real second instance would fight the first one over the :9223 WS port.
525
- // Still tolerant of weird environments (EPERM on sandboxed setups, and
526
- // macOS packaged builds where the lock can report false and quitting would
527
- // make the app unlaunchable) — everywhere else, the duplicate exits and
528
- // lets the existing window handle the request.
526
+ } else {
527
+ // A real second instance would fight the first one over the :9223 WS port
528
+ // and share one Chromium profile / userDataDir with the first — the duplicate
529
+ // must exit and let the existing window handle the request.
530
+ // gotLock===false already means "another instance owns the lock", on EVERY
531
+ // platform (including macOS packaged builds); the previous platform-conditional
532
+ // exemption silently skipped this quit, which let two ai-browser instances run
533
+ // side by side — closing one of them then crashed (Bug 6).
534
+ // 落了盘才有"事后可查":从 Finder/双击启动时 stderr 是黑洞,只 console.error
535
+ // 等于什么都没留下(用户只会说"我点了没反应")。
536
+ recordError('second_instance_exit', {
537
+ port: PORT,
538
+ user_data: config.userDataDir,
539
+ note: '另一个实例持有单实例锁,本进程退出(避免两个进程共享同一 Chromium profile 并抢同一端口)',
540
+ });
529
541
  console.error('[index] another AI Browser instance is already running — quitting');
530
542
  app.quit();
531
543
  }
@@ -685,6 +697,18 @@ function createWindow() {
685
697
 
686
698
  // Start WS server — pass cleanupAndQuit so ui.quit can shut down the app
687
699
  wsServer = startWSServer(pageManager, PORT, cleanupAndQuit);
700
+ // 监听失败必须让人看见。此前 ws_server 把错误 `.catch(() => {})` 吞了,
701
+ // 实测端口被占时窗口照常起来、却没有任何 WS,用户与 agent 都不知道为什么。
702
+ wsServer.ready.catch(() => {
703
+ const err = wsServer.listenError;
704
+ const code = (err && err.code) || 'unknown';
705
+ reportFatal(
706
+ `WS 端口 ${PORT} 监听失败(${code})。本实例收不到任何指令 —— `
707
+ + (code === 'EADDRINUSE'
708
+ ? '端口已被占用:先关掉另一个 ai-browser 实例,或用 AI_BROWSER_PORT 换一个端口。'
709
+ : '详见 error.jsonl 的 ws_listen_error 条目。')
710
+ );
711
+ });
688
712
 
689
713
  // === Tab bar IPC ===
690
714
  ipcMain.on('tab:new', () => {
@@ -882,26 +906,20 @@ function createWindow() {
882
906
  // 导航可能来自三方:人在地址栏输入、agent 调 ui.navigate、页面自己跳转。
883
907
  // 地址栏必须反映**真实**状态,所以这里订阅激活 tab 的 webContents 事件主动推,
884
908
  // 而不是靠定时轮询(轮询有最多 2s 的滞后,人会以为按钮坏了)。
885
- const wireNavState = (tabId) => {
886
- const wc = activeWebContents();
887
- if (!wc) return;
888
- if (navStateWc === wc) return; // 同一个 tab 重复 setActive,不重复挂
889
- navStateWc = wc;
890
- const push = () => pushNavState();
891
- wc.on('did-start-loading', push);
892
- wc.on('did-stop-loading', push);
893
- wc.on('did-navigate', push);
894
- wc.on('did-navigate-in-page', push);
895
- wc.on('page-title-updated', push);
896
- };
909
+ // 挂载规则收敛到 shared/nav_follow.cjs:同一个 webContents **幂等**
910
+ // (WeakSet 记账),修掉"切回旧 tab 又挂一遍"的累加;webContents 被销毁时
911
+ // 顺手清掉我们持有的引用。这段原来写在闭包里,判据只能 grep 源码 ——
912
+ // 实测 A→B→A×5 后监听数是 3,而回归全绿(见 tests/test_nav_follow.js)。
913
+ const navFollower = createNavFollower({ push: pushNavState });
914
+ const wireNavState = () => navFollower.wire(activeWebContents());
897
915
  // 包一层只为了挂「地址栏跟随」这块副作用,返回值必须原样透传 ——
898
916
  // ws_server 的 ui.set_active_tab 靠它回 { ok }(2026-10-19 测到过包装吞掉
899
917
  // 返回值导致 agent 收到空回执的事故,见 shared/tab_hooks.js 注释)。
900
- wrapSetActive(pageManager, (tabId) => {
901
- wireNavState(tabId);
918
+ wrapSetActive(pageManager, () => {
919
+ wireNavState();
902
920
  pushNavState();
903
921
  });
904
- wireNavState(pageManager.activeTab);
922
+ wireNavState();
905
923
  // 兜底轮询:只覆盖上面事件没抓到的情况(低频,成本可忽略)
906
924
  navStateInterval = setInterval(pushNavState, 1500);
907
925
 
@@ -148,7 +148,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
148
148
  // 都会实际调用一次工具,不透明的 internal error 会被当成"坏了"。
149
149
  return { content: [{ type: 'text', text: `Error: ${guardErr}` }], isError: true };
150
150
  }
151
- const result = await wsClient.call('ui.evaluate', { js, tab: args.tab });
151
+ // frame_ref 必须转发:旧版这里只传 js/tab,schema 却承诺了"显式指定运行帧",
152
+ // 于是 agent 传了也照样在顶层帧跑、对 iframe 内元素返回 null —— 不报错、
153
+ // 只是拿不到(同类事故第 5 次,见 docs/AUDIT-2026-10-30.md P1-1)。
154
+ // tests/test_mcp_forwarding.js 用表驱动钉住"声明即转发"。
155
+ const result = await wsClient.call('ui.evaluate', {
156
+ js,
157
+ tab: args.tab,
158
+ frame_ref: args.frame_ref || undefined,
159
+ });
152
160
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
153
161
  }
154
162
 
@@ -38,6 +38,12 @@ import blankPage from '../shared/blank_page.cjs';
38
38
  // .cjs 用默认导入(全项目约定,且 tests/test_imports.js 的静态分析只认 ESM export)。
39
39
  import viewLiveness from '../shared/view_liveness.cjs';
40
40
  const { isAlive, liveness } = viewLiveness;
41
+ // "关掉一个 tab 时哪些 per-tab 容器必须跟着消失"的唯一清单(纯函数)。
42
+ // 为什么是表而不是逐行 delete:这类清理历史上漏过两轮(Bug 5 补了 4 个字段,
43
+ // 2026-10-30 评估又查出 3 个漏网)。清单数据化 + 完整性闸门单测之后,
44
+ // "新增一个 per-tab Map 忘了清"会变成构建失败而不是半年后的一次泄漏。
45
+ // 见 shared/tab_state.cjs 顶部与 docs/AUDIT-2026-10-30.md P1-2。
46
+ import tabState from '../shared/tab_state.cjs';
41
47
  import { diffValues, previewOf, safeByteLength, DEFAULT_SNAPSHOT_JS, DIFF_MAX_ENTRIES, evictOldest } from './snapshot_diff.js';
42
48
  import { withDeadline, actionDeadlineMs } from '../shared/deadline.js';
43
49
  import { DownloadMonitor } from './download_monitor.js';
@@ -4725,16 +4731,12 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4725
4731
  for (const [token, entry] of this._windowOpenTokens) {
4726
4732
  if (entry.tabId === tabId) this._windowOpenTokens.delete(token);
4727
4733
  }
4728
- this._windowOpenShimTabs.delete(tabId);
4729
- this._windowOpenShimReady.delete(tabId);
4730
- this._tabNavState.delete(tabId);
4731
- // 对话框状态跟着 tab 走:留着会让下次同 id 的 tab 继承一个不存在的对话框。
4732
- this._lastDialog.delete(tabId);
4733
- this._openDialogs.delete(tabId);
4734
- this._dialogWatched.delete(tabId);
4735
- // Release per-tab network resources so a closed tab can never leak its
4736
- // debugger attachment or cached request entries / stale monitors.
4734
+ // per-tab 纯容器的清理由 shared/tab_state.cjs 的 PER_TAB 表统一执行
4735
+ // (唯一清单)。这里不再逐行 delete:两处清单一定会分叉 —— Bug 5 与
4736
+ // 2026-10-30 评估各漏一次,就是这么漏的。有副作用的步骤(detach 调试器、
4737
+ // 释放抓包内存、canvas 账本)也在同一个函数里,但**晚于**纯删除。
4737
4738
  this._cleanupTabResources(tabId);
4739
+
4738
4740
  if (this.activeTab === tabId || this.activeTab === null) {
4739
4741
  // switch to first remaining tab — must re-addBrowserView
4740
4742
  const first = this.tabs.keys().next();
@@ -4758,6 +4760,13 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4758
4760
  // unaffected — each tab owns its own webContents debugger)
4759
4761
  // - drop cached request entries made on that tab
4760
4762
  _cleanupTabResources(tabId) {
4763
+ // 第一件事:把纯数据容器全部清掉。
4764
+ // 放在最前面是因为它是**纯删除、不会抛**,而后面几步都有副作用(detach 调试器、
4765
+ // 释放抓包内存)——万一哪一步抛了,至少 tabId 不会带着上一任的状态被复用。
4766
+ // 清单只有一份:shared/tab_state.cjs 的 PER_TAB(新增 per-tab 容器必须登记,
4767
+ // 否则 tests/test_tab_state_reset.js 的完整性闸门会红)。
4768
+ tabState.clearPerTab(this, tabId);
4769
+
4761
4770
  const entry = this._cdpTabs.get(tabId);
4762
4771
  if (entry) {
4763
4772
  try { entry.wc.debugger.detach(); } catch(e) {}
@@ -4780,14 +4789,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4780
4789
  // tabId 会被复用,媒体文档记录跟着一起清 —— 否则新 tab 一打开就带着
4781
4790
  // 上一个 tab 的「下载」按钮状态(地址对不上时 recordOf 会兜住,但别依赖兜底)。
4782
4791
  if (this.mediaInline) this.mediaInline.forget(tabId);
4783
- // 白屏自检 / 崩溃自救的 per-tab 状态。不清的话 tabId 会被新 tab 复用,
4784
- // 新 tab 一开就继承上一任的"已经救过两步",白屏时直接被判定成 give-up。
4785
- this._paintState.delete(tabId);
4786
- this._paintSteps.delete(tabId);
4787
- this._paintSelfReload.delete(tabId);
4788
- this._crashReloadAt.delete(tabId);
4789
- const pt = this._paintTimers.get(tabId);
4790
- if (pt) { clearTimeout(pt); this._paintTimers.delete(tabId); }
4792
+ // canvas 抓取状态有自己的配额账本与 hook 句柄,需要连带释放;用 forget 而不是
4793
+ // clear —— clear 是"重记"(canvas_configure{clear:true} 用),会保留 mode/hook,
4794
+ // 关 tab 要的是连那个空壳一起删,否则 tabs Map 无界累积(没有淘汰上限)。
4795
+ this.canvasMonitor.forget(tabId);
4791
4796
  }
4792
4797
 
4793
4798
  /** 白屏相关的"值得报出去的结论";正常页面返回 null(listTabs 不带这个字段)。 */
@@ -74,13 +74,39 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
74
74
  // Passing a host pushes Node onto the async DNS-lookup listen path, so
75
75
  // wss.address() is null until 'listening'. Cache it and let callers await.
76
76
  let bound = null;
77
+ let listenError = null;
77
78
  const ready = new Promise((resolve, reject) => {
78
79
  wss.once('listening', () => { bound = wss.address(); resolve(bound); });
79
80
  wss.once('error', reject);
80
81
  });
82
+ // ⚠️ 这里原来是 `.catch(() => {})` —— 监听失败被彻底吞掉。实测(2026-10-30,
83
+ // 两个实例不同 userData、同端口):第二个实例照常起了窗口,但没有 WS、没有
84
+ // 一行报错、error.jsonl 里只有 boot。用户看到"窗口开着但什么都不响应",
85
+ // agent 连不上,两边都查不出原因 —— 静默失败比崩溃更难查。
86
+ //
87
+ // 现在:落盘(ws_listen_error)+ 打一行带可执行下一步的日志 + 记录错误对象,
88
+ // 由 index.js 据此弹横幅。**不主动退出**:端口冲突可能是临时的(另一个实例
89
+ // 正在关),窗口留着比直接消失更好,但状态必须如实说出来。
81
90
  ready.then(() => {
82
91
  console.log(`AI Browser WS server listening on ws://${bound.address}:${bound.port}`);
83
- }).catch(() => {});
92
+ }).catch((err) => {
93
+ const e = err instanceof Error ? err : new Error(String(err));
94
+ listenError = e;
95
+ const code = (e && e.code) || 'unknown';
96
+ recordError('ws_listen_error', {
97
+ port,
98
+ bind_host: config.wsBindHost,
99
+ code,
100
+ message: String(e.message || e).slice(0, 300),
101
+ note: 'WS 未能监听:本实例收不到任何指令(窗口可能仍在,但没有入口)',
102
+ });
103
+ console.error(
104
+ `[ws] 监听失败 ${config.wsBindHost}:${port} — ${code}: ${e.message}`
105
+ + (code === 'EADDRINUSE'
106
+ ? '(端口已被占用:先关掉另一个 ai-browser,或用 AI_BROWSER_PORT 换一个端口)'
107
+ : '')
108
+ );
109
+ });
84
110
 
85
111
  wss.on('connection', (ws, _req) => {
86
112
  const sessionId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
@@ -696,14 +722,32 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
696
722
  // === ui.wait — poll until condition or timeout ===
697
723
  case 'ui.wait': {
698
724
  // params: { condition: 'button_enabled'|'modal_appeared'|'text_contains', target, text, timeout_ms }
699
- const timeoutMs = params.timeout_ms || 10000;
725
+ //
726
+ // timeout_ms 必须钳制:调用方写 600000 会让这条 RPC 和一次 500ms 一轮的
727
+ // 树抽取循环一直跑着,而 agent 那边通常早就超时放弃了。
728
+ const timeoutMs = Math.max(100, Math.min(120000, Number(params.timeout_ms) || 10000));
700
729
  const pollMs = 500;
701
730
  const startTime = Date.now();
702
731
  let satisfied = false;
732
+ let attempts = 0;
733
+ // 最后一次"这一轮没读成"的原因。仅仅不满足**不是**错误,但读失败
734
+ // 必须如实报出来 —— 否则调用方分不清"条件没出现"和"我一直在读空"。
735
+ let lastError = null;
703
736
 
704
737
  const poll = async () => {
705
738
  while (Date.now() - startTime < timeoutMs) {
706
- const result = await pageManager.getTree(false, tabId);
739
+ attempts++;
740
+ // ⚠️ 单次抽取失败不是"等待失败"。导航之后的几百毫秒里文档正在换,
741
+ // preload 的 ai:extract 会因为旧文档已拆而超时(getTree 硬 5s 后
742
+ // reject)。此前这里没有 try/catch → `browse_wait({url_contains})`
743
+ // 这个最典型的用法直接变成 -32603 internal error,而调用方看到
744
+ // "内部错误"的合理反应是**重试导航**,把已经成功的导航重做一遍。
745
+ let result = null;
746
+ try {
747
+ result = await pageManager.getTree(false, tabId);
748
+ } catch (e) {
749
+ lastError = String((e && e.message) || e);
750
+ }
707
751
  const tree = result?.tree;
708
752
  const ctx = result?.context;
709
753
 
@@ -718,12 +762,20 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
718
762
  if (ctx?.modals && ctx.modals.length > 0) { satisfied = true; break; }
719
763
  }
720
764
  if (params.condition === 'text_contains' && params.text) {
721
- const bodyText = await pageManager.evaluate('document.body.innerText', tabId);
722
- if (bodyText && bodyText.indexOf(params.text) >= 0) { satisfied = true; break; }
765
+ try {
766
+ const bodyText = await pageManager.evaluate('document.body.innerText', tabId);
767
+ if (bodyText && bodyText.indexOf(params.text) >= 0) { satisfied = true; break; }
768
+ } catch (e) {
769
+ lastError = String((e && e.message) || e);
770
+ }
723
771
  }
724
772
  if (params.condition === 'url_contains' && params.text) {
725
- const url = await pageManager.evaluate('location.href', tabId);
726
- if (url && url.indexOf(params.text) >= 0) { satisfied = true; break; }
773
+ try {
774
+ const url = await pageManager.evaluate('location.href', tabId);
775
+ if (url && url.indexOf(params.text) >= 0) { satisfied = true; break; }
776
+ } catch (e) {
777
+ lastError = String((e && e.message) || e);
778
+ }
727
779
  }
728
780
 
729
781
  await new Promise(r => setTimeout(r, pollMs));
@@ -731,7 +783,17 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
731
783
  };
732
784
 
733
785
  await poll();
734
- send({ jsonrpc: '2.0', id, result: { satisfied, elapsed_ms: Date.now() - startTime } });
786
+ send({
787
+ jsonrpc: '2.0', id,
788
+ result: {
789
+ satisfied,
790
+ elapsed_ms: Date.now() - startTime,
791
+ // 抽了几轮。0 轮 = 一次都没轮到(超时被钳到极小或页面立即失效),
792
+ // 这个数字让"等了两秒但只读了 3 次"这种事可诊断。
793
+ attempts,
794
+ ...(satisfied || !lastError ? {} : { last_error: lastError }),
795
+ },
796
+ });
735
797
  break;
736
798
  }
737
799
  // === ui.scroll — scroll page or element ===
@@ -752,8 +814,19 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
752
814
  window.scrollBy(0, d === 'down' ? a : -a);
753
815
  return { ok: true };
754
816
  })(${JSON.stringify(target)}, ${JSON.stringify(direction)}, ${amount})`;
755
- const result = await pageManager.evaluate(js, tabId).catch(() => ({ ok: false }));
756
- send({ jsonrpc: '2.0', id, result: result || { ok: true } });
817
+ const result = await pageManager.evaluate(js, tabId).catch((e) => ({
818
+ ok: false,
819
+ error: String((e && e.message) || e),
820
+ }));
821
+ // 以前这里写 `result || { ok: true }`:evaluate 返回 undefined 时也报成功。
822
+ // 「命令发出去了」不等于「页面动了」—— 这个项目为这条判据付过代价
823
+ // (不变量 5:任何写入必须 操作→回读→diff)。没有回执就如实说没有。
824
+ send({
825
+ jsonrpc: '2.0', id,
826
+ result: result && typeof result === 'object'
827
+ ? result
828
+ : { ok: false, error: 'scroll produced no result from the page' },
829
+ });
757
830
  break;
758
831
  }
759
832
  // === 网络抓包(可查询的 Network 面板)===
@@ -776,22 +849,21 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
776
849
  break;
777
850
  }
778
851
  case 'ui.network_get': {
779
- try {
780
- const result = await pageManager.networkGet(String(params.network_id || ''), {
781
- include_request_headers: params.include_request_headers === true,
782
- include_request_body: params.include_request_body === true,
783
- include_response_headers: params.include_response_headers === true,
784
- include_response_body: params.include_response_body === true,
785
- include_sensitive_headers: params.include_sensitive_headers === true,
786
- request_body_offset: params.request_body_offset,
787
- response_body_offset: params.response_body_offset,
788
- body_limit: params.body_limit,
789
- });
790
- send({ jsonrpc: '2.0', id, result });
791
- } catch (e) {
792
- if (e && e.rpcCode) send({ jsonrpc: '2.0', id, error: { code: e.rpcCode, message: e.message, data: e.data || undefined } });
793
- else send({ jsonrpc: '2.0', id, error: { code: -32603, message: e.message } });
794
- }
852
+ // 这里**不**自带 try/catch:以前自带一份,catch 里 send 完继续往下走,
853
+ // 最后落到统一的 noteCall(..., true) —— 于是"body 被淘汰"这类失败会被
854
+ // 记成一次**成功**调用,错误日志里"崩溃前最近调用"就成了假证据。
855
+ // 现在只有一个错误出口(外层 catch),它认 e.rpcCode 并回精确错误码。
856
+ const result = await pageManager.networkGet(String(params.network_id || ''), {
857
+ include_request_headers: params.include_request_headers === true,
858
+ include_request_body: params.include_request_body === true,
859
+ include_response_headers: params.include_response_headers === true,
860
+ include_response_body: params.include_response_body === true,
861
+ include_sensitive_headers: params.include_sensitive_headers === true,
862
+ request_body_offset: params.request_body_offset,
863
+ response_body_offset: params.response_body_offset,
864
+ body_limit: params.body_limit,
865
+ });
866
+ send({ jsonrpc: '2.0', id, result });
795
867
  break;
796
868
  }
797
869
  case 'ui.network_clear': {
@@ -866,17 +938,26 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
866
938
  // 而不是给每次点击都记一行日志。
867
939
  noteCall(method, params, Date.now() - t0, true);
868
940
  } catch (e) {
869
- noteCall(method, params, Date.now() - t0, 'error: ' + ((e && e.message) || e));
941
+ const errMsg = (e && e.message) || String(e);
942
+ noteCall(method, params, Date.now() - t0, 'error: ' + errMsg);
943
+ // 带 rpcCode 的是**可预期的业务失败**(记录不存在 / body 已被淘汰 /
944
+ // 敏感头未开):回精确错误码,但**不落盘** —— 它不是"主进程出问题了",
945
+ // 落盘只会把真正的 uncaught/崩溃淹掉。此前 ui.network_get 在自己的
946
+ // catch 里这么做,代价是错误调用被记成了成功(见 AUDIT P2-1)。
947
+ if (e && e.rpcCode) {
948
+ send({ jsonrpc: '2.0', id, error: { code: e.rpcCode, message: errMsg, data: e.data || undefined } });
949
+ return;
950
+ }
870
951
  // RPC 层异常**必须落盘**。此前它只变成一句 JSON-RPC error 回给调用方,
871
952
  // 一旦客户端那边没截住(或用户只看到界面里闪一下),现场就永久丢了 ——
872
953
  // 事后既查不到崩在哪,也证不了"刚才是不是真的报过错"。
873
954
  recordError('ws_error', {
874
955
  method,
875
956
  params,
876
- message: (e && e.message) || String(e),
957
+ message: errMsg,
877
958
  stack: String((e && e.stack) || '').slice(0, 8000),
878
959
  });
879
- send({ jsonrpc: '2.0', id, error: { code: -32603, message: e.message } });
960
+ send({ jsonrpc: '2.0', id, error: { code: -32603, message: errMsg } });
880
961
  }
881
962
  });
882
963
 
@@ -887,7 +968,10 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
887
968
 
888
969
  return {
889
970
  // Resolves once the socket is actually bound (port 0 → ephemeral port known).
971
+ // Rejects on listen failure —— 调用方必须处理,别让"起不来"变成静默。
890
972
  ready,
973
+ // 监听失败的具体错误(null 表示正常)。给调用方拼提示用。
974
+ get listenError() { return listenError; },
891
975
  // Actual bound port/address; null until ready.
892
976
  get port() { return bound ? bound.port : null; },
893
977
  // Security invariant: must be a loopback literal.
@@ -0,0 +1,69 @@
1
+ // shared/nav_follow.cjs — 「地址栏跟随」的挂载状态机。
2
+ //
3
+ // 要解决的问题:地址栏必须反映**激活 tab 的真实导航状态**,所以每次切 tab 都要
4
+ // 把 5 个导航事件转到 pushNavState 上。这段逻辑原来直接写在 index.js 的闭包里,
5
+ // 结果两个坑同时存在、而且只有真浏览器才看得见:
6
+ //
7
+ // 1. **重复挂载**:守卫是 `if (navStateWc === wc) return`,只挡住"连续两次切到
8
+ // 同一个 tab"。A→B→A 切回来时旧对象没销毁,于是又挂一遍 —— 实测切 5 次后
9
+ // A 上 `did-navigate` 的监听数是 3(应为 1),每次导航 pushNavState 被调 3 次;
10
+ // 翻过 10 个还会触发 Node 的 MaxListenersExceededWarning。
11
+ // 2. **判据证伪不了它**:写在闭包里没法单测,回归只能 grep 源码
12
+ // ("出现 removeListener 就算对"),而上面那个真实的重复挂载在 grep 下全绿。
13
+ //
14
+ // 所以把状态机搬出来,用 WeakSet 记账(webContents 被回收时记账自动失效,
15
+ // 不需要额外清理),并对销毁时机做显式处理:webContents 一旦 destroyed,
16
+ // 监听器随对象消亡,但**我们持有的引用**必须清掉,否则下次切 tab 前它一直悬空。
17
+
18
+ /** 地址栏需要跟随的 5 个事件。顺序无关,但必须与 pushNavState 的语义一致。 */
19
+ const NAV_EVENTS = [
20
+ 'did-start-loading',
21
+ 'did-stop-loading',
22
+ 'did-navigate',
23
+ 'did-navigate-in-page',
24
+ 'page-title-updated',
25
+ ];
26
+
27
+ /**
28
+ * @param {object} opts
29
+ * @param {string[]} [opts.events] 要跟随的事件名
30
+ * @param {() => void} opts.push 事件触发时调用的推送函数(必须是无参、幂等的)
31
+ * @returns {{wire: (wc:any)=>any, current: ()=>any, wired: (wc:any)=>boolean}}
32
+ */
33
+ function createNavFollower({ events = NAV_EVENTS, push } = {}) {
34
+ if (typeof push !== 'function') throw new TypeError('createNavFollower: push 必须是函数');
35
+
36
+ let current = null; // 当前跟随的 webContents(只用来报告/清理,不参与判重)
37
+ const seen = new WeakSet(); // 已经挂过监听的 webContents
38
+
39
+ /**
40
+ * 把 wc 设为跟随目标。**幂等**:同一个 wc 无论调多少次,每个事件只会有一个监听。
41
+ * 传 null/undefined 是合法调用(没有激活 tab),直接返回 null。
42
+ */
43
+ function wire(wc) {
44
+ if (!wc) return null;
45
+ current = wc;
46
+ if (seen.has(wc)) return wc; // 已经挂过 —— 只更新跟随目标,不再挂第二遍
47
+ seen.add(wc);
48
+ for (const ev of events) {
49
+ try {
50
+ wc.on(ev, push);
51
+ } catch (_) {
52
+ // 对象刚好在这几毫秒内销毁:跳过,下一次 wire 会重新挂。
53
+ }
54
+ }
55
+ // 销毁后清掉引用。监听器本身随对象一起消亡,不需要(也无法)手动摘。
56
+ try {
57
+ wc.once('destroyed', () => { if (current === wc) current = null; });
58
+ } catch (_) { /* 不支持 once 的假对象(单测)忽略 */ }
59
+ return wc;
60
+ }
61
+
62
+ return {
63
+ wire,
64
+ current: () => current,
65
+ wired: (wc) => !!wc && seen.has(wc),
66
+ };
67
+ }
68
+
69
+ module.exports = { createNavFollower, NAV_EVENTS };
@@ -0,0 +1,115 @@
1
+ // shared/tab_state.cjs — "关掉一个 tab 时,哪些 per-tab 状态必须跟着消失"的唯一清单。
2
+ //
3
+ // 为什么要有这份表(而不是继续在 _cleanupTabResources 里逐行写 delete):
4
+ // PageManager 现在有 26 个 `new Map()/Set()` 字段,其中 20 多个以 tabId 为键。
5
+ // tabId **会被复用**,所以任何一处漏清都会变成"新 tab 带着上一任的状态活着"——
6
+ // 它不报错,只让新 tab 的第一次白屏自检直接被判成 give-up、让旧 URL 一直挂在
7
+ // _openedTabs 里。历史上已经发生过两轮:
8
+ // · Bug 5(2026-10-30):漏了 _refTrackers / _axDiffCache / _failureGuard /
9
+ // canvasMonitor —— 当时只补了被点名的 4 个;
10
+ // · 本次评估(AUDIT-2026-10-30 P1-2):又查出 _openedTabs / _canvasBindings /
11
+ // _paintAuditInflight 三项漏网。
12
+ // 根因不是"谁忘了写",而是**机制**:新增一个 per-tab 容器时,没有任何东西会
13
+ // 提醒你去清理它。所以把清单变成数据,再用"构造函数里的每个 Map/Set 必须登记
14
+ // 在表里或白名单里"的单测当闸门 —— 忘记登记 = 构建失败,而不是半年后一次泄漏。
15
+ //
16
+ // 判定与执行分开(同 view_liveness.cjs 的理由):这里是纯函数,node:electron 不参与,
17
+ // 于是可以用假 owner 把"哪类容器怎么清"逐类钉死。
18
+ //
19
+ // 三类容器,三种清法(表里用标记区分):
20
+ // · 默认 —— Map<K, V> / Set<T>,**键/成员就是 tabId**:delete(tabId)
21
+ // · byValue: true —— Map<K, tabId>,**值是 tabId**(bindingName → tabId 这种):
22
+ // 只删值相等的条目,键是别的东西
23
+ // · timers: true —— Map<tabId, Timeout>:先 clearTimeout 再 delete,
24
+ // 否则关掉的 tab 还会在 5s 后来敲一次已经不存在的视图
25
+
26
+ 'use strict';
27
+
28
+ /**
29
+ * 以 tabId 为键(或值为 tabId)的容器。**新增这类字段必须在这里登记**,
30
+ * 否则 tests/test_tab_state_reset.js 的完整性闸门会红。
31
+ */
32
+ const PER_TAB = [
33
+ // ---- 标签页归属 / LRU ----
34
+ { field: '_tabGroup' },
35
+ { field: '_tabUsedAt' },
36
+ // ---- window.open 垫片记账 ----
37
+ { field: '_openedTabs' }, // 键 = 发起 window.open 的那个 tab
38
+ { field: '_windowOpenShimTabs' },
39
+ { field: '_windowOpenShimReady' },
40
+ // ---- 导航状态机 ----
41
+ { field: '_tabNavState' },
42
+ // ---- 浏览器级对话框 ----
43
+ { field: '_lastDialog' },
44
+ { field: '_openDialogs' },
45
+ { field: '_dialogWatched' },
46
+ // ---- 增量 diff / ref 纪元 ----
47
+ { field: '_axDiffCache' },
48
+ { field: '_refTrackers' },
49
+ { field: '_failureGuard' },
50
+ // ---- 重绘 / 白屏自检 / 崩溃自救 ----
51
+ { field: '_repaintTimers', timers: true },
52
+ { field: '_paintState' },
53
+ { field: '_paintSteps' },
54
+ { field: '_paintTimers', timers: true },
55
+ { field: '_paintAuditInflight' },
56
+ { field: '_paintSelfReload' },
57
+ { field: '_crashReloadAt' },
58
+ // ---- canvas hook 回传路由 ----
59
+ // 键是 `__aiCanvasReport_<tabId>_<rand>`,值是 tabId —— 每次重装 hook 都生成
60
+ // 一个新名字,所以这里只能按**值**清,否则每次 configure 都留一条永不释放。
61
+ { field: '_canvasBindings', byValue: true },
62
+ ];
63
+
64
+ /**
65
+ * 看起来像 per-tab、但**不该由这里清**的容器。每条都必须写清理由,
66
+ * 否则闸门测试只是被我们用手写白名单骗过去而已。
67
+ */
68
+ const NOT_PER_TAB = {
69
+ _pendingRequests: '键是自增 requestId,promise settle 时自己删;与 tab 生死无关',
70
+ _wsClients: '键是 sessionId,由 unregisterClient 清(连接生命周期)',
71
+ _sessionTab: '键是 sessionId,由 unregisterClient 清(连接生命周期)',
72
+ _groups: '键是 groupId,组空时由 _forgetTab 删;删 tab 不等于删组',
73
+ _windowOpenTokens: '值是 {tabId},closeTab 里手写遍历清(结构不是直接 tabId)',
74
+ _snapshots: '值是 {tab, ...},_cleanupTabResources 里手写遍历清(结构不是直接 tabId)',
75
+ _networkRequestMap: '值是 {tabId, ...},_cleanupTabResources 里手写遍历清',
76
+ _cdpTabs: '值是 {wc},清理前必须 debugger.detach()(有副作用,不能放进纯函数)',
77
+ };
78
+
79
+ /**
80
+ * 清掉一个 tab 的全部状态。
81
+ * @param {object} owner PageManager 实例(或任何带同名字段的假对象)
82
+ * @param {number|string} tabId
83
+ * @param {Array} table 默认用 PER_TAB;测试可传自定义表
84
+ * @returns {string[]} 真正执行过清理的字段名(供调用方/测试观测)
85
+ */
86
+ function clearPerTab(owner, tabId, table = PER_TAB) {
87
+ const cleared = [];
88
+ if (!owner || tabId === undefined || tabId === null) return cleared;
89
+
90
+ for (const row of table) {
91
+ const c = owner[row.field];
92
+ // 懒初始化的字段此刻可能还不存在;类型不对的字段(有人手改成数组)也别抛。
93
+ if (!c || typeof c.delete !== 'function') continue;
94
+
95
+ if (row.byValue) {
96
+ // Map<K, tabId>:只能遍历值。Set 没有 entries(),故要求是 Map。
97
+ if (typeof c.entries !== 'function') continue;
98
+ for (const [k, v] of c.entries()) {
99
+ if (v === tabId) c.delete(k);
100
+ }
101
+ } else {
102
+ if (row.timers && typeof c.get === 'function') {
103
+ const t = c.get(tabId);
104
+ if (t) {
105
+ try { clearTimeout(t); } catch (_) { /* 已触发的 timer 清不掉,正常 */ }
106
+ }
107
+ }
108
+ c.delete(tabId);
109
+ }
110
+ cleared.push(row.field);
111
+ }
112
+ return cleared;
113
+ }
114
+
115
+ module.exports = { PER_TAB, NOT_PER_TAB, clearPerTab };
@@ -2,4 +2,4 @@
2
2
  // Kept in JS (not imported from package.json) to avoid Node import-attribute
3
3
  // (JSON module) compatibility issues inside Electron. package.json "version"
4
4
  // is manually synced to this value; tests assert they match.
5
- export const VERSION = '2.4.3';
5
+ export const VERSION = '2.4.5';