@glittering0717/ai-browser 2.4.2 → 2.4.3

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.2",
3
+ "version": "2.4.3",
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": {
@@ -65,6 +65,7 @@
65
65
  "value": "node e2e/value_ws.cjs",
66
66
  "canvas": "node e2e/canvas_ws.cjs",
67
67
  "appmodel": "node e2e/app_model_ws.cjs",
68
+ "lifecycle": "node e2e/lifecycle_ws.cjs",
68
69
  "focus": "node e2e/focus_ws.cjs",
69
70
  "interact": "node e2e/interact_ws.cjs",
70
71
  "upload": "node e2e/upload_ws.cjs",
@@ -2,12 +2,16 @@
2
2
 
3
3
  ## canvas(纯绘制,没有 DOM 节点)
4
4
 
5
- 读内容**不要 OCR**。canvas 里的文本来自 `fillText` 调用,能被直接截获。
6
-
7
- - 前提:浏览器启动时带 `AI_BROWSER_CANVAS_HOOK=1`(默认关,因为要挂 CDP 绘制层)。
8
- - `browse_canvas {operation:"list"}` → 拿到 canvas 与 `canvas_id`
9
- - `browse_canvas {operation:"read", canvas_id}` → 文本 + 坐标 + 字体
10
- - **WebGL 是黑盒**:捕获不到文本,只能 `browse_canvas {operation:"capture"}` 拿 PNG,自己承担视觉成本。
5
+ **先找应用模型,再退到绘制层。**「图是 canvas」不等于「没有结构」:
6
+
7
+ 1. **`browse_capabilities {deep:true}`** —— 扫库指纹(fabric / Konva / paper / Excalidraw /
8
+ CodeMirror / Monaco)。实例即使**关在闭包里**也能抓出来(hook 原型方法 + 一条合成事件)。
9
+ 命中就给 `read_expr`(**顶层可求值的完整表达式**,直接喂 `browse_evaluate`)。
10
+ 有模型 → 读整张图的结构(图形类型/坐标/尺寸/文本),写完能**回读校验**。**这是首选。**
11
+ 2. 没有已知库 → `browse_canvas {operation:"list"}` + `read` 截获 `fillText` 文本
12
+ (需 `AI_BROWSER_CANVAS_HOOK=1`;**WebGL 是黑盒**,捕获不到文本,只能 `capture` 拿 PNG,
13
+ 自己承担视觉成本)。纯 canvas 应用**不要 OCR**。
14
+ 3. 都没有 → 只能靠坐标动作 + 帧指纹确认"画面变了",但**读不出"画的是什么"**(如实告知,别假装)。
11
15
 
12
16
  在 canvas 上落点用坐标动作,不要找元素:
13
17
 
package/src/main/index.js CHANGED
@@ -12,6 +12,11 @@ import { parseWatchdogTargets, isWatchdogEnabled } from '../shared/watchdog.js';
12
12
  import { wrapSetActive } from '../shared/tab_hooks.js';
13
13
  import { initErrorLog, recordError, markShutdown, getLogPath } from './error_log.js';
14
14
  import errorBanner from '../shared/error_banner.cjs';
15
+ // .cjs 一律默认导入:ESM 从 .cjs 做具名导入依赖 cjs-module-lexer 静态识别,
16
+ // 而 tests/test_imports.js 只认 ESM `export` 语法,会误报"没有导出它"。全项目约定
17
+ // 用默认导入(见 blank_page.cjs / error_banner.cjs),这里保持一致。
18
+ import viewLiveness from '../shared/view_liveness.cjs';
19
+ const { isAlive, liveness } = viewLiveness;
15
20
  import { classifyShowReason, describeShowUrl } from '../shared/window_show.js';
16
21
 
17
22
  const __filename = fileURLToPath(import.meta.url);
@@ -64,6 +69,29 @@ let pendingBannerTimer = null;
64
69
  // 连窗口都等不到(启动即死)时,多久后退回一次原生框 —— 这是唯一"什么都不显示"
65
70
  // 的场景,否则用户会看到应用静默不动、也没有任何提示。
66
71
  const BANNER_GIVE_UP_MS = 8000;
72
+ // 横幅自动收敛(2026-10-30):以前横幅一旦挂上就只能靠人点 × 收起,异常明明已经
73
+ // 过去却会一直占着底部 34px —— 用户截图里那条深红横幅就是挂了 3 小时没消失。
74
+ // 现在:距最后一次 fatal 静默 BANNER_AUTO_HIDE_MS 后自动收起(日志里的 stack 永久保留,
75
+ // 收横幅不影响查证)。有新异常会重置计时器。
76
+ const BANNER_AUTO_HIDE_MS = (() => {
77
+ const n = Number(process.env.AI_BROWSER_BANNER_AUTOHIDE_MS);
78
+ return Number.isFinite(n) && n >= 500 ? n : 15000; // 允许 e2e 调短;下限 500ms 防误配
79
+ })();
80
+ let bannerAutoHideTimer = null;
81
+
82
+ function scheduleBannerAutoHide() {
83
+ if (bannerAutoHideTimer) { clearTimeout(bannerAutoHideTimer); bannerAutoHideTimer = null; }
84
+ bannerAutoHideTimer = setTimeout(() => {
85
+ bannerAutoHideTimer = null;
86
+ // 只收起横幅视图,不动日志、不动计数;人仍可从 ui.errors 查到完整 stack。
87
+ // 记一条:横幅自动收敛这件事必须可观测,否则"横幅是不是又挂死了"无从查证。
88
+ if (errorBannerView) {
89
+ try { recordError('error_banner_autohide', { after_ms: BANNER_AUTO_HIDE_MS }); } catch {}
90
+ try { hideErrorBanner(); } catch (_) {}
91
+ }
92
+ }, BANNER_AUTO_HIDE_MS);
93
+ if (bannerAutoHideTimer.unref) bannerAutoHideTimer.unref();
94
+ }
67
95
 
68
96
  function bannerEnabled() {
69
97
  // e2e / 无人值守可以关掉(日志照记):横幅虽不阻塞,但会改变窗口布局,
@@ -105,18 +133,107 @@ function showNativeFatalDialog(detail) {
105
133
  }, 800);
106
134
  }
107
135
 
136
+ // === 标签栏视图的生命周期治理(2026-10-30 白屏事故的根治)=================
137
+ //
138
+ // 事故形态:标题栏还在、页面区全白、底部一条深红横幅 —— 也就是 tabBarView 的
139
+ // webContents 失效(close/destroy 后变 undefined,或渲染进程被 GPU 崩溃连带走),
140
+ // 而 setInterval(pushNavState, 1500) 每 1.5s 无条件访问它 → 抛
141
+ // "Cannot read properties of undefined (reading 'isDestroyed')" → uncaughtException
142
+ // → reportFatal → showErrorBanner → layoutWithBanner 又碰悬空视图 → 二次崩溃 →
143
+ // 进程半死(端口 listen 但 WS 握不上手)。日志里这个异常反复出现 22 次。
144
+ //
145
+ // 治理三要点(底层通用,不是逐个补丁):
146
+ // 1. 所有"这视图还活着吗"的判断走 shared/view_liveness.cjs 的 isAlive,绝不裸写
147
+ // .webContents.isDestroyed();
148
+ // 2. tabBarView 每次被 pushNavState 摸到时顺手体检一次,死了就重建 —— 把原来的
149
+ // "崩溃点"变成"自愈点";
150
+ // 3. 重建有节流与上限:GPU 连续崩溃时不能无限 new BrowserView(那就是另一种死循环)。
151
+ let tabBarRebuildAt = 0;
152
+ let tabBarRebuildCount = 0;
153
+ const TAB_BAR_REBUILD_MIN_GAP = 1500; // 两次重建至少隔 1.5s
154
+ const TAB_BAR_REBUILD_MAX = 8; // 单进程生命周期内最多重建 8 次
155
+
156
+ /** 造一个全新的标签栏 BrowserView 并挂进窗口。交互靠主进程全局 IPC,不用逐 view 重绑。 */
157
+ function createTabBarView() {
158
+ const view = new BrowserView({
159
+ webPreferences: { contextIsolation: false, nodeIntegration: true },
160
+ });
161
+ mainWindow.addBrowserView(view);
162
+ try {
163
+ const cb = mainWindow.getContentBounds();
164
+ view.setBounds({ x: 0, y: 0, width: cb.width, height: TAB_BAR_HEIGHT });
165
+ } catch {
166
+ view.setBounds({ x: 0, y: 0, width: 1280, height: TAB_BAR_HEIGHT });
167
+ }
168
+ view.webContents.loadFile(path.join(__dirname, '../renderer/tab_bar.html'));
169
+
170
+ // 渲染进程真的死了(killed/crashed)时主动报一声并触发自愈,而不是等 1.5s 轮询。
171
+ // clean-exit 也要管:标签栏是常驻视图,"正常退出"对它就是不该发生的丢失。
172
+ view.webContents.on('render-process-gone', (_e, details) => {
173
+ const reason = (details && details.reason) || 'unknown';
174
+ try { recordError('tabbar_renderer_gone', { reason }); } catch {}
175
+ // 让出当前回调栈再重建,避免在 Electron 的事件派发过程中拆自己的 view。
176
+ setTimeout(() => {
177
+ try { ensureTabBarAlive(true); } catch (e) {
178
+ try { recordError('tabbar_rebuild_failed', { error: String(e && e.message || e) }); } catch {}
179
+ }
180
+ }, 120);
181
+ });
182
+ return view;
183
+ }
184
+
185
+ /**
186
+ * 保证标签栏活着。死了就重建(带节流与上限),返回当前可用的 view 或 null。
187
+ * @param {boolean} force 渲染进程刚死时为 true,跳过"最小间隔"节流(但仍受上限约束)。
188
+ */
189
+ function ensureTabBarAlive(force = false) {
190
+ if (isAlive(tabBarView)) return tabBarView;
191
+ if (!mainWindow || mainWindow.isDestroyed()) return null;
192
+ const now = Date.now();
193
+ if (!force && now - tabBarRebuildAt < TAB_BAR_REBUILD_MIN_GAP) return null;
194
+ if (tabBarRebuildCount >= TAB_BAR_REBUILD_MAX) {
195
+ // 到顶了就不再重建,避免 GPU 反复崩溃时的无限循环。日志留一次,让人能查到。
196
+ if (tabBarRebuildCount === TAB_BAR_REBUILD_MAX) {
197
+ tabBarRebuildCount++; // 只记一次,之后静默
198
+ try { recordError('tabbar_rebuild_exhausted', { max: TAB_BAR_REBUILD_MAX }); } catch {}
199
+ }
200
+ return null;
201
+ }
202
+ // 摘掉悬空的旧对象(try 包裹:它可能已经被 Electron 内部拆掉了)。
203
+ if (tabBarView) {
204
+ try { mainWindow.removeBrowserView(tabBarView); } catch {}
205
+ }
206
+ try {
207
+ tabBarView = createTabBarView();
208
+ tabBarRebuildAt = now;
209
+ tabBarRebuildCount++;
210
+ try { recordError('tabbar_rebuilt', { count: tabBarRebuildCount, prev: 'dead' }); } catch {}
211
+ // 新视图的 renderer 会自己拉一次 nav:state;这里再手动补一帧布局,避免它暂时
212
+ // 用了默认 1280 宽而窗口其实更宽/更窄。
213
+ layoutWithBanner();
214
+ return tabBarView;
215
+ } catch (e) {
216
+ tabBarView = null;
217
+ try { recordError('tabbar_rebuild_failed', { error: String(e && e.message || e) }); } catch {}
218
+ return null;
219
+ }
220
+ }
221
+
108
222
  // 布局集中在一处算:横幅要占掉底部 34px,页面视图必须相应让出来,
109
223
  // 否则横幅会被页面盖住(或反过来压住页面最后一行)。
110
224
  function layoutWithBanner() {
111
225
  if (!mainWindow || mainWindow.isDestroyed()) return;
112
226
  let b;
113
227
  try { b = mainWindow.getContentBounds(); } catch { return; }
114
- if (tabBarView && !tabBarView.webContents.isDestroyed()) {
228
+ // ⚠️ 不能裸写 tabBarView.webContents.isDestroyed():webContents 在 close/destroy
229
+ // 后会变成 undefined,那样会抛 "Cannot read properties of undefined" 击穿主进程
230
+ // (2026-10-30 白屏事故的 22 次崩溃,全在这条链上)。统一走 isAlive。
231
+ if (isAlive(tabBarView)) {
115
232
  tabBarView.setBounds({ x: 0, y: 0, width: b.width, height: TAB_BAR_HEIGHT });
116
233
  }
117
234
  const inset = errorBannerView ? ERROR_BANNER_HEIGHT : 0;
118
235
  if (pageManager) pageManager._bottomInset = inset;
119
- if (errorBannerView && !errorBannerView.webContents.isDestroyed()) {
236
+ if (isAlive(errorBannerView)) {
120
237
  errorBannerView.setBounds({
121
238
  x: 0,
122
239
  y: Math.max(0, b.height - ERROR_BANNER_HEIGHT),
@@ -128,7 +245,12 @@ function layoutWithBanner() {
128
245
  }
129
246
 
130
247
  function ensureErrorBanner() {
131
- if (errorBannerView && !errorBannerView.webContents.isDestroyed()) return errorBannerView;
248
+ if (isAlive(errorBannerView)) return errorBannerView;
249
+ // 悬空的旧横幅:先从窗口摘掉,再重建。否则旧对象会一直占着 z 序位置。
250
+ if (errorBannerView) {
251
+ try { mainWindow.removeBrowserView(errorBannerView); } catch {}
252
+ errorBannerView = null;
253
+ }
132
254
  if (!mainWindow || mainWindow.isDestroyed()) return null;
133
255
  // 与标签栏同样的配置(nodeIntegration + 非隔离):横幅是我们自己的本地页面,
134
256
  // 需要 ipcRenderer 才能把「×」传回主进程。页面里没有任何远程内容。
@@ -148,10 +270,12 @@ function showErrorBanner(payload) {
148
270
  const view = ensureErrorBanner();
149
271
  if (!view) return false;
150
272
  const deliver = () => {
151
- try { view.webContents.send('error-banner:show', payload); } catch { /* 帧已销毁就放弃,日志已有 */ }
273
+ try { if (isAlive(view)) view.webContents.send('error-banner:show', payload); } catch { /* 帧已销毁就放弃,日志已有 */ }
152
274
  };
153
275
  // 首次创建时 listener 还没注册,直接 send 会静默丢失 —— 等 load 完再发。
154
- if (view.webContents.isLoading()) view.webContents.once('did-finish-load', deliver);
276
+ let loading = false;
277
+ try { loading = isAlive(view) && view.webContents.isLoading(); } catch { loading = false; }
278
+ if (loading) { try { view.webContents.once('did-finish-load', deliver); } catch { deliver(); } }
155
279
  else deliver();
156
280
  layoutWithBanner();
157
281
  return true;
@@ -177,6 +301,17 @@ function flushPendingBanner() {
177
301
  }
178
302
 
179
303
  function reportFatal(detail) {
304
+ // reportFatal 本身跑在 process.on('uncaughtException') 里 —— 它是兜底处理器,
305
+ // 自己**绝不能**再抛异常(否则就是"处理器内部二次崩溃 → 进程半死",2026-10-30
306
+ // 白屏事故里端口还 listen 但 WS 握不上手,正是这么来的)。整段包死。
307
+ try {
308
+ reportFatalInner(detail);
309
+ } catch (e) {
310
+ try { console.error('[reportFatal] self-guarded:', e && e.message); } catch {}
311
+ }
312
+ }
313
+
314
+ function reportFatalInner(detail) {
180
315
  const text = String(detail === undefined || detail === null ? '' : detail);
181
316
  if (nativeDialogForced()) { showNativeFatalDialog(text); return; }
182
317
  if (!bannerEnabled()) return;
@@ -190,6 +325,7 @@ function reportFatal(detail) {
190
325
  log_path: logPath,
191
326
  note: 'shown in-window (non-blocking); no modal dialog opened',
192
327
  });
328
+ scheduleBannerAutoHide();
193
329
  if (app.isReady() && mainWindow && !mainWindow.isDestroyed()) {
194
330
  showErrorBanner(payload);
195
331
  return;
@@ -219,13 +355,26 @@ function reportFatal(detail) {
219
355
 
220
356
  process.on('uncaughtException', (err, origin) => {
221
357
  const e = err instanceof Error ? err : new Error(String(err));
222
- recordError('uncaught_exception', {
223
- origin: origin || null,
224
- message: e.message,
225
- stack: String(e.stack || '').slice(0, 8000),
226
- });
227
- console.error('[fatal] uncaughtException:', (e && e.stack) || e);
228
- reportFatal((e && e.message) || String(e));
358
+ try {
359
+ recordError('uncaught_exception', {
360
+ origin: origin || null,
361
+ message: e.message,
362
+ stack: String(e.stack || '').slice(0, 8000),
363
+ });
364
+ } catch (_) {}
365
+ try { console.error('[fatal] uncaughtException:', (e && e.stack) || e); } catch (_) {}
366
+
367
+ // 纵深自愈:如果这次异常本身就是"某个视图失效"引起的(例如别的路径仍存在的
368
+ // 裸访问,或第三方代码碰了我们的 view),立刻体检并重建标签栏,别把白屏留给
369
+ // 用户。识别信号用错误文本 —— 这类崩溃的典型文案就是 reading 'isDestroyed'。
370
+ // 这一步只重建 chrome 视图,不 reload 用户页面,代价可控。
371
+ try {
372
+ if (/isDestroyed|webContents|Object has been destroyed/i.test(String(e.message || ''))) {
373
+ ensureTabBarAlive(true);
374
+ }
375
+ } catch (_) {}
376
+
377
+ try { reportFatal((e && e.message) || String(e)); } catch (_) {}
229
378
  });
230
379
 
231
380
  process.on('unhandledRejection', (reason) => {
@@ -508,15 +657,7 @@ function createWindow() {
508
657
  mainWindow.webContents.on('page-title-updated', (e) => { e.preventDefault(); });
509
658
 
510
659
  // Tab bar — needs nodeIntegration for ipcRenderer
511
- tabBarView = new BrowserView({
512
- webPreferences: {
513
- contextIsolation: false,
514
- nodeIntegration: true,
515
- },
516
- });
517
- mainWindow.addBrowserView(tabBarView);
518
- tabBarView.setBounds({ x: 0, y: 0, width: 1280, height: TAB_BAR_HEIGHT });
519
- tabBarView.webContents.loadFile(path.join(__dirname, '../renderer/tab_bar.html'));
660
+ tabBarView = createTabBarView();
520
661
 
521
662
  // Init PageManager
522
663
  pageManager = PageManager.getInstance(mainWindow);
@@ -992,7 +1133,7 @@ function StartNetworkWatchdog() {
992
1133
  }
993
1134
 
994
1135
  function refreshTabBar() {
995
- if (tabBarView && !tabBarView.webContents.isDestroyed()) {
1136
+ if (isAlive(tabBarView)) {
996
1137
  tabBarView.webContents.executeJavaScript('renderTabs && renderTabs()').catch(() => {});
997
1138
  }
998
1139
  }
@@ -1012,7 +1153,7 @@ function refreshTabBar() {
1012
1153
  function activeWebContents() {
1013
1154
  if (!pageManager) return null;
1014
1155
  const view = pageManager.tabs.get(pageManager.activeTab);
1015
- if (!view || view.webContents.isDestroyed()) return null;
1156
+ if (!isAlive(view)) return null;
1016
1157
  return view.webContents;
1017
1158
  }
1018
1159
 
@@ -1117,11 +1258,24 @@ function pushNavState() {
1117
1258
  // 标题先更新:它不依赖 tabBarView 是否存活(横幅/崩溃场景下 tabBarView
1118
1259
  // 可能已被销毁,但窗口标题仍应反映真实页面)。
1119
1260
  updateWindowTitle();
1120
- if (!tabBarView || tabBarView.webContents.isDestroyed()) return;
1261
+ // ⚠️ 这里曾经裸写 `tabBarView.webContents.isDestroyed()`:tabBarView 悬空时
1262
+ // (webContents 变 undefined)就抛异常,而本函数被 setInterval 每 1.5s 无条件
1263
+ // 调用 —— 于是每 1.5s 崩一次,累计 22 次 uncaught_exception(2026-10-30 白屏事故)。
1264
+ // 现在改为:先体检,死了就自愈重建,绝不裸访问。这次推送可以跳过(1.5s 后再来),
1265
+ // 重建完成后下一次自然会推到新视图上。
1266
+ const view = ensureTabBarAlive(false);
1267
+ if (!view) return;
1268
+ // 刚重建的视图 renderer 还在加载 tab_bar.html,此刻 executeJavaScript 会失败
1269
+ // ("Object has been destroyed" 或空上下文)—— 会被 .catch 接住不致命,但会往
1270
+ // stderr 刷一条没意义的错误。它加载完成后会自己 invoke('nav:state') 拉一次,
1271
+ // 所以加载中直接跳过本次推送即可,1.5s 后下一轮再推。
1272
+ try { if (view.webContents.isLoading()) return; } catch (_) { return; }
1121
1273
  const state = buildNavState();
1122
- tabBarView.webContents.executeJavaScript(
1123
- 'window.__onNavState && window.__onNavState(' + JSON.stringify(state) + ')'
1124
- ).catch(() => {});
1274
+ try {
1275
+ view.webContents.executeJavaScript(
1276
+ 'window.__onNavState && window.__onNavState(' + JSON.stringify(state) + ')'
1277
+ ).catch(() => {});
1278
+ } catch (_) { /* 视图在这几毫秒内又失效:交给下一轮自愈 */ }
1125
1279
  }
1126
1280
 
1127
1281
  /**
@@ -1169,6 +1323,27 @@ app.whenReady().then(() => {
1169
1323
  }, 5000);
1170
1324
  }
1171
1325
  }
1326
+ // 诊断开关(默认关闭):主动把 tabBarView 的 webContents 置为悬空,用来复现
1327
+ // "标签栏渲染进程丢失后,pushNavState 每 1.5s 抛 Cannot read ... isDestroyed" 这一类崩溃。
1328
+ // 修复后这个开关必须能证明:不再抛异常、标签栏自动重建、横幅不会挂死。
1329
+ if (_selftest === 'chrome-gone') {
1330
+ setTimeout(() => {
1331
+ try {
1332
+ if (tabBarView && tabBarView.webContents) {
1333
+ tabBarView.webContents.close();
1334
+ console.log('[selftest:chrome-gone] tabBarView.webContents closed (simulated renderer loss)');
1335
+ }
1336
+ } catch (e) { console.log('[selftest:chrome-gone] close threw:', e.message); }
1337
+ }, 2000);
1338
+ // 5.5s 后自报体检结果:修复后应当是 ok(已被 ensureTabBarAlive 重建),
1339
+ // 而不是崩溃/悬空。这条输出是 e2e/lifecycle_ws.cjs 的判据之一。
1340
+ setTimeout(() => {
1341
+ try {
1342
+ console.log('[selftest:chrome-gone] tabBar liveness after heal = ' + liveness(tabBarView)
1343
+ + ' | rebuildCount=' + tabBarRebuildCount);
1344
+ } catch (e) { console.log('[selftest:chrome-gone] verify threw:', e.message); }
1345
+ }, 5500);
1346
+ }
1172
1347
  // 下载与权限的 session 级钩子。必须装在 will-download 上,否则 Electron 默认
1173
1348
  // **取消**下载:agent 点"导出"只看到 success,然后什么都没有,连错误都没有
1174
1349
  // (2026-10-12 审计发现 src/ 里原先没有任何下载处理)。
@@ -32,6 +32,12 @@ import { newTracker, noteTree, diagnoseMissingRef } from '../shared/ref_epoch.js
32
32
  // "这一页到底画出来没有"的判定口径(纯函数)。此前没有任何检测覆盖"加载成功但
33
33
  // 屏幕纯白"这一类 —— 见 shared/blank_page.cjs 顶部(2026-10-25 用户报百度白屏)。
34
34
  import blankPage from '../shared/blank_page.cjs';
35
+ // "这个 BrowserView 还能不能碰"的唯一判定口径(纯函数)。webContents 在
36
+ // close/destroy 后会变 undefined,裸写 .isDestroyed() 会击穿主进程 ——
37
+ // 见 shared/view_liveness.cjs 顶部(2026-10-30 白屏事故的 22 次崩溃)。
38
+ // .cjs 用默认导入(全项目约定,且 tests/test_imports.js 的静态分析只认 ESM export)。
39
+ import viewLiveness from '../shared/view_liveness.cjs';
40
+ const { isAlive, liveness } = viewLiveness;
35
41
  import { diffValues, previewOf, safeByteLength, DEFAULT_SNAPSHOT_JS, DIFF_MAX_ENTRIES, evictOldest } from './snapshot_diff.js';
36
42
  import { withDeadline, actionDeadlineMs } from '../shared/deadline.js';
37
43
  import { DownloadMonitor } from './download_monitor.js';
@@ -914,13 +920,13 @@ class PageManager {
914
920
  try {
915
921
  if (tabId === undefined || tabId === null || !rec) return;
916
922
  const view = this.tabs.get(tabId);
917
- if (!view || view.webContents.isDestroyed()) return;
923
+ if (!isAlive(view)) return;
918
924
  const cur = view.webContents.getURL() || '';
919
925
  if (!mediaDoc.isPlaceholderUrl(cur)) return;
920
926
  // 让这条 will-download 先走完,再切页面:避免和刚刚被取消的导航抢加载。
921
927
  setImmediate(() => {
922
928
  try {
923
- if (view.webContents.isDestroyed()) return;
929
+ if (!isAlive(view)) return;
924
930
  if (!mediaDoc.isPlaceholderUrl(view.webContents.getURL() || '')) return;
925
931
  this.showDownloadResult(tabId, rec);
926
932
  } catch (_) { /* 结果页只是"有回执",失败不该影响下载本身 */ }
@@ -931,7 +937,7 @@ class PageManager {
931
937
  /** 把一个 tab 换成"下载结果"页(文件名/大小/缩略图/打开/在 Finder 中显示)。 */
932
938
  showDownloadResult(tabId, rec) {
933
939
  const view = this.tabs.get(tabId);
934
- if (!view || view.webContents.isDestroyed()) return false;
940
+ if (!isAlive(view)) return false;
935
941
  const pagePath = path.join(__dirname, '../renderer/download.html');
936
942
  // 一律走 shared/placeholder.cjs 的构造器:手拼 'file://' + path 在打包后
937
943
  // (/Applications/AI Browser.app 含空格)加载不出来。
@@ -957,7 +963,7 @@ class PageManager {
957
963
  downloadCurrent(tabId) {
958
964
  const id = tabId === undefined || tabId === null ? this.activeTab : tabId;
959
965
  const view = this.tabs.get(id);
960
- if (!view || view.webContents.isDestroyed()) return { ok: false, error: 'no such tab' };
966
+ if (!isAlive(view)) return { ok: false, error: 'no such tab' };
961
967
  const cur = view.webContents.getURL() || '';
962
968
  const rec = this.mediaInline.recordOf(id, cur);
963
969
  const url = rec ? rec.url : cur;
@@ -974,7 +980,7 @@ class PageManager {
974
980
  mediaDocOf(tabId) {
975
981
  const id = tabId === undefined || tabId === null ? this.activeTab : tabId;
976
982
  const view = this.tabs.get(id);
977
- if (!view || view.webContents.isDestroyed()) return null;
983
+ if (!isAlive(view)) return null;
978
984
  try {
979
985
  return this.mediaInline.recordOf(id, view.webContents.getURL() || '');
980
986
  } catch (_) {
@@ -2284,7 +2290,7 @@ class PageManager {
2284
2290
  let pending = false;
2285
2291
  try {
2286
2292
  const view = this._getView(mine.id);
2287
- const live = view && view.webContents.getURL();
2293
+ const live = isAlive(view) ? view.webContents.getURL() : null;
2288
2294
  if (live && live !== 'about:blank') url = live;
2289
2295
  // 仍然没有真实地址(占位页还没被导航)→ 明说 pending,而不是回一个
2290
2296
  // 看起来像"空白页"的 about:blank。
@@ -2314,7 +2320,7 @@ class PageManager {
2314
2320
  const view = this._getView(tid);
2315
2321
  // 快路径 2:本 tab 已经开始原地导航 —— 站内跳转不会同时开新标签,别等。
2316
2322
  // 这一类(点链接跳走)是最高频的点击,跳过它等于让绝大多数点击零额外成本。
2317
- if (view && view.webContents.isLoading()) {
2323
+ if (isAlive(view) && view.webContents.isLoading()) {
2318
2324
  return this._consumeOpenedTab(tid, keep, startedAt);
2319
2325
  }
2320
2326
  // 快路径 3:目标不是链接 → 不等。
@@ -4230,8 +4236,20 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4230
4236
  const tid = tabId !== undefined ? tabId : this.activeTab;
4231
4237
  const view = this._getView(tid);
4232
4238
  if (!view) return { ok: false, error: 'no-such-tab', tab: tid };
4239
+ // ⚠️ 视图失效(webContents 悬空/destroyed)以前直接 `return {ok:false, error:'tab-destroyed'}`
4240
+ // —— 而 _auditPaintNow 对 !ok 直接返回,等于**放弃自救**:渲染进程死后用户看到
4241
+ // 永久白屏,日志里却什么都没有(2026-10-30 白屏盲区)。现在把它作为可判定的
4242
+ // view-dead 结论返回,交给 _auditPaintNow 的重建分支处理。
4243
+ if (!isAlive(view)) {
4244
+ const rec = {
4245
+ ok: true, tab: tid, blank: true, verdict: 'view-dead',
4246
+ reason: 'view has no usable webContents (' + liveness(view) + ') — renderer is gone',
4247
+ view_liveness: liveness(view),
4248
+ };
4249
+ this._paintState.set(tid, { ...rec, at: Date.now(), action: 'none' });
4250
+ return rec;
4251
+ }
4233
4252
  const wc = view.webContents;
4234
- if (!wc || wc.isDestroyed()) return { ok: false, error: 'tab-destroyed', tab: tid };
4235
4253
  const startedAt = Date.now();
4236
4254
 
4237
4255
  let bounds = null;
@@ -4312,7 +4330,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4312
4330
  frameError = e && e.message ? e.message : String(e);
4313
4331
  }
4314
4332
 
4315
- let cls = blankPage.classifyPaint({ stats, dom, bounds });
4333
+ // view_alive 让 classifyPaint 能把"截图为空"分成两种:视图真死(view-dead,要救)
4334
+ // 和只是被遮挡/隐藏(no-frame,不动)。这里 isAlive 一定为 true(开头已挡掉死视图),
4335
+ // 传它是为了口径统一 + 未来若读取路径变化时仍正确。
4336
+ let cls = blankPage.classifyPaint({ stats, dom, bounds, view_alive: isAlive(view) });
4316
4337
  // 渲染口径与视图几何必须相等。不等只有两种原因:用户主动缩放(合法)或
4317
4338
  // **合成器把旧尺寸的 surface 缩进了新 bounds**(就是"内容缩成左上角一小块")。
4318
4339
  // 用 zoomFactor 把两者分开:页面缩放有明确的 zoom 值,surface 脱节时 zoom 仍是 1。
@@ -4425,7 +4446,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4425
4446
  const t = setTimeout(() => {
4426
4447
  try {
4427
4448
  const v = this._getView(tabId);
4428
- if (!v || !v.webContents || v.webContents.isDestroyed()) return;
4449
+ if (!isAlive(v)) return;
4429
4450
  let cb;
4430
4451
  try { cb = this.window.getContentBounds(); } catch (_) { return; }
4431
4452
  const exp = {
@@ -4449,15 +4470,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4449
4470
  } catch (_) { /* 忽略 */ }
4450
4471
  }, 120);
4451
4472
  if (t.unref) t.unref();
4473
+ // 只返回 deferred:真正的修正在上面的 setTimeout 里做(延迟确认,避免在窗口
4474
+ // 刚变化的中间态把视图改成错尺寸)。曾经这里 return 之后还留着一段"立即修正"
4475
+ // 的旧代码 —— 永远不可达的死代码,2026-10-30 清理。
4452
4476
  return { ok: false, expected, actual, fixed: 'deferred' };
4453
- try {
4454
- this._layoutView(view);
4455
- view.webContents.invalidate();
4456
- } catch (_) { /* 视图正在销毁 */ }
4457
- const info = { tab: tabId, expected, actual };
4458
- recordError('layout_mismatch', info);
4459
- this._broadcast('layout_mismatch', info);
4460
- return { ok: false, expected, actual, fixed: true };
4461
4477
  }
4462
4478
 
4463
4479
  /**
@@ -4524,7 +4540,38 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4524
4540
  if (action === 'none') return rec;
4525
4541
 
4526
4542
  const view = this._getView(tabId);
4527
- if (!view || !view.webContents || view.webContents.isDestroyed()) return rec;
4543
+
4544
+ // view-dead:视图的 webContents 已悬空/销毁。reload() 对它还活着(进程崩溃但
4545
+ // wc 对象还在)的情形有效;对真正悬空(wc === undefined)的情形无效 —— 那种
4546
+ // 情况下**不盲目重建整个 tab**(会丢导航历史/分组/登录态,代价远大于收益,
4547
+ // 用户的页面不是我们的重建试验场),而是如实上报 paint_blank 让人可见。
4548
+ // 无论哪种,都只走一次,绝不成死循环(decidePaintAction 对 view-dead 只有
4549
+ // reload → give-up 两级)。
4550
+ if (res.verdict === 'view-dead') {
4551
+ const why = liveness(view);
4552
+ recordError('paint_view_dead', { tab: tabId, liveness: why, steps });
4553
+ if (action === 'reload' && isAlive(view)) {
4554
+ this._paintSteps.set(tabId, steps + 1);
4555
+ this._paintSelfReload.add(tabId);
4556
+ try {
4557
+ view.webContents.reload();
4558
+ await this._waitFinishLoad(tabId, 10000);
4559
+ await new Promise((r) => { const t = setTimeout(r, 450); if (t.unref) t.unref(); });
4560
+ return this._auditPaintNow(tabId);
4561
+ } catch (_) {
4562
+ this._paintSelfReload.delete(tabId);
4563
+ }
4564
+ }
4565
+ // 悬空或 reload 无效 → give-up,广播出去让人知道(不再静默放过白屏)。
4566
+ const info = { tab: tabId, verdict: 'view-dead', liveness: why, attempts: steps,
4567
+ reason: res.reason, note: 'view cannot be repainted; renderer may need the tab reopened' };
4568
+ this._paintState.set(tabId, { ...res, action: 'give-up', at: Date.now() });
4569
+ recordError('paint_blank', info);
4570
+ this._broadcast('paint_blank', info);
4571
+ return { ...rec, action: 'give-up' };
4572
+ }
4573
+
4574
+ if (!view || !isAlive(view)) return rec;
4528
4575
  if (action === 'repaint') {
4529
4576
  this._paintSteps.set(tabId, steps + 1);
4530
4577
  // 这里必须 hard:被判成白屏/scale-mismatch 时,surface 很可能就是旧尺寸,
@@ -79,6 +79,9 @@ function statsFromBitmap(bitmap) {
79
79
  * @param {{total:number,white:number,white_ratio:number,unique:number}} p.stats
80
80
  * @param {{text_len:number, nodes:number, ready_state:string}} p.dom 页面自述的事实
81
81
  * @param {{width:number,height:number}} [p.bounds] 视图当前尺寸
82
+ * @param {boolean} [p.view_alive] 视图现在还有没有可用的 webContents(isAlive)。
83
+ * 拿不到位图时用它区分"被遮挡"(不动)和"视图真死了"(要救)——
84
+ * 否则渲染进程崩溃后截图为空会被判成 no-frame 静默放过(2026-10-30 白屏盲区)。
82
85
  * @returns {{verdict:string, blank:boolean, reason:string}}
83
86
  *
84
87
  * verdict:
@@ -86,13 +89,15 @@ function statsFromBitmap(bitmap) {
86
89
  * empty-legit 这页本来就是空的(about:blank / 空文档),白是正确结果
87
90
  * not-ready 页面还没到 interactive/complete,白是暂时的,等它
88
91
  * collapsed 视图本身被压成 0 高/0 宽 —— 不是没画,是没地方画
92
+ * view-dead 拿不到位图**且**视图已失效(webContents 悬空/destroyed)——
93
+ * 渲染进程死了,必须重建/重载,不能静默放过
89
94
  * blank-with-text DOM 里有文字,但屏幕上纯白 —— **真白屏**
90
95
  * blank-with-dom DOM 有几十个节点却纯白 —— **真白屏**(内容层失败)
91
96
  * scale-mismatch 页面按 A 宽排版、视图只有 B 宽(合成器画了一张陈旧尺寸的
92
97
  * surface)—— 表现为"内容缩在左上角,其余全白"
93
- * no-frame 拿不到位图(视图不可见/被销毁),无法判定
98
+ * no-frame 拿不到位图,但视图还活着(被遮挡/隐藏)—— 无法判定,不动
94
99
  */
95
- function classifyPaint({ stats, dom, bounds } = {}) {
100
+ function classifyPaint({ stats, dom, bounds, view_alive } = {}) {
96
101
  const d = dom || {};
97
102
  const textLen = Number(d.text_len) || 0;
98
103
  const nodes = Number(d.nodes) || 0;
@@ -102,7 +107,13 @@ function classifyPaint({ stats, dom, bounds } = {}) {
102
107
  return { verdict: 'collapsed', blank: true, reason: `view is ${bounds.width}x${bounds.height} — nothing to paint into` };
103
108
  }
104
109
  if (!stats || !stats.total) {
105
- return { verdict: 'no-frame', blank: false, reason: 'no bitmap (view not visible or destroyed)' };
110
+ // 视图自己已经没救了(webContents 悬空/destroyed)——这是渲染进程死亡后的
111
+ // 典型形态:截图返回空,而 paintCheck 以前一律判 no-frame 放过,用户看到的是
112
+ // 永久白屏。用 view_alive 把"真死"和"只是被遮挡"分开。
113
+ if (view_alive === false) {
114
+ return { verdict: 'view-dead', blank: true, reason: 'no bitmap AND the view has no usable webContents — renderer is gone' };
115
+ }
116
+ return { verdict: 'no-frame', blank: false, reason: 'no bitmap (view not visible or occluded)' };
106
117
  }
107
118
  const isWhite = stats.white_ratio >= WHITE_MIN_RATIO && stats.unique <= UNIQUE_MAX;
108
119
  const colourDesc = `${stats.unique}${stats.unique_pinned ? '+' : ''} colours`;
@@ -134,6 +145,12 @@ function classifyPaint({ stats, dom, bounds } = {}) {
134
145
  * @returns {'none'|'repaint'|'reload'|'give-up'}
135
146
  */
136
147
  function decidePaintAction({ verdict, steps = 0 } = {}) {
148
+ // view-dead:视图的 webContents 已经没了,重画(invalidate)毫无意义 —— 直接
149
+ // 从"重建/重载"开始。有上限:重建失败就不无限循环(见调用方 _auditPaintNow)。
150
+ if (verdict === 'view-dead') {
151
+ if (steps <= 0) return 'reload'; // reload 对仍可 reload 的崩溃进程有效;悬空的由调用方重建
152
+ return 'give-up';
153
+ }
137
154
  // ok / empty-legit / not-ready / no-frame 都不该动。not-ready 尤其重要:
138
155
  // 首屏那一刻本来就可能是白的,这时候 reload 等于把正在下载的页面打断。
139
156
  if (verdict === 'ok' || verdict === 'empty-legit' || verdict === 'not-ready' || verdict === 'no-frame') {
@@ -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.2';
5
+ export const VERSION = '2.4.3';
@@ -0,0 +1,74 @@
1
+ // shared/view_liveness.cjs — "这个 BrowserView 现在还能不能碰"的唯一判定口径。
2
+ //
3
+ // 事故(2026-10-30,用户报"又白屏了",截图:标题栏正常、内容全白、底部一条深红横幅、
4
+ // 左侧露一小块橙棕):主进程在 22 次 uncaught_exception 里反复抛
5
+ // Cannot read properties of undefined (reading 'isDestroyed')
6
+ // at pushNavState (index.js) ← setInterval(pushNavState, 1500)
7
+ //
8
+ // 根因是 Electron 的一个反直觉行为(用真 Electron 探针实测,见 git 提交说明):
9
+ // - webContents.close() / destroy() 之后,BrowserView 对象**还在**,但
10
+ // view.webContents 变成 undefined —— 此时 `view.webContents.isDestroyed()`
11
+ // 直接抛 TypeError。
12
+ // - 渲染进程崩溃(render-process-gone)之后,view.webContents**还在**,
13
+ // isDestroyed() 也返回 false,但内容不再渲染(视图区域空白),reload() 能救回。
14
+ //
15
+ // 也就是说"视图可能失效"有两种形态,任何一处裸写 `view.webContents.isDestroyed()`
16
+ // 都会在第一种形态下击穿主进程。而这个 HK 项目的地址栏/标题由 setInterval 每 1.5s
17
+ // 无条件重推一次 —— 一旦 tabBarView 悬空,就变成每 1.5s 崩一次的死亡螺旋:
18
+ // 崩溃 → uncaughtException → reportFatal → showErrorBanner → layoutWithBanner
19
+ // → 又碰到悬空视图 → 二次崩溃 → 进程半死(端口还在 listen 但 WS 握手完不成)。
20
+ //
21
+ // 这份模块只做一件事:给一个"可能是 BrowserView"的对象,回答
22
+ // "它现在有没有一个活着、可安全调用的 webContents?"
23
+ // 判定与"怎么救"分开 —— 救(重建/reload/收横幅)有副作用,属于调用方职责,
24
+ // 且必须有上限,不能在纯函数里做。
25
+ //
26
+ // 为什么必须是纯函数:node:electron 在 vitest 里 import 会炸,index.js 整份没法单测。
27
+ // 把这条判定抽出来,才能用假对象把"undefined / 抛异常 / isDestroyed=true"三种形态
28
+ // 一次性钉死 —— 否则这类 bug 永远只能靠真机偶发复现。
29
+
30
+ 'use strict';
31
+
32
+ /**
33
+ * 视图是否"活着且可安全使用"。
34
+ *
35
+ * 覆盖三种失效形态(都用真 Electron 或等价假对象实测):
36
+ * 1. view 本身是 null/undefined → false
37
+ * 2. view.webContents 是 undefined/null → false(close/destroy 后,正是事故形态)
38
+ * 3. webContents.isDestroyed() === true → false
39
+ * 4. 读取 webContents / 调 isDestroyed 抛异常 → false(宁可判死,绝不让异常冒出去)
40
+ *
41
+ * @param {object} view 可能是 BrowserView 的东西
42
+ * @returns {boolean}
43
+ */
44
+ function isAlive(view) {
45
+ if (!view) return false;
46
+ try {
47
+ const wc = view.webContents;
48
+ if (!wc) return false;
49
+ if (typeof wc.isDestroyed !== 'function') return false;
50
+ return !wc.isDestroyed();
51
+ } catch (_) {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * 失效的"原因",供日志/回执区分"悬空"与"已销毁",避免把两种形态混为一谈
58
+ * (它们的救法不同:悬空必须重建 BrowserView,已销毁可考虑 reload)。
59
+ *
60
+ * @param {object} view
61
+ * @returns {'ok'|'no-view'|'no-webcontents'|'destroyed'|'unknown'}
62
+ */
63
+ function liveness(view) {
64
+ if (!view) return 'no-view';
65
+ let wc;
66
+ try { wc = view.webContents; } catch (_) { return 'unknown'; }
67
+ if (!wc) return 'no-webcontents';
68
+ try {
69
+ if (typeof wc.isDestroyed !== 'function') return 'unknown';
70
+ return wc.isDestroyed() ? 'destroyed' : 'ok';
71
+ } catch (_) { return 'unknown'; }
72
+ }
73
+
74
+ module.exports = { isAlive, liveness };