@glittering0717/ai-browser 2.5.10 → 2.6.1

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.
@@ -1,7 +1,8 @@
1
1
  // main/page_manager.js — Multi-tab page lifecycle manager v2
2
2
  // One Electron process, one WS server, multiple tabs.
3
3
  // Agent routes via tab ID. Tab 0 is default.
4
- import { ipcMain, BrowserView, nativeImage, webContents, app } from 'electron';
4
+ import { ipcMain, nativeImage, webContents, app } from 'electron';
5
+ import { createView, attach, detach, raise, isAttached } from './view_layer.js';
5
6
  import path from 'node:path';
6
7
  import fs from 'node:fs';
7
8
  import { fileURLToPath } from 'node:url';
@@ -34,7 +35,7 @@ import { newTracker, noteTree, diagnoseMissingRef } from '../shared/ref_epoch.js
34
35
  // "这一页到底画出来没有"的判定口径(纯函数)。此前没有任何检测覆盖"加载成功但
35
36
  // 屏幕纯白"这一类 —— 见 shared/blank_page.cjs 顶部(2026-10-25 用户报百度白屏)。
36
37
  import blankPage from '../shared/blank_page.cjs';
37
- // "这个 BrowserView 还能不能碰"的唯一判定口径(纯函数)。webContents 在
38
+ // "这个视图还能不能碰"的唯一判定口径(纯函数)。webContents 在
38
39
  // close/destroy 后会变 undefined,裸写 .isDestroyed() 会击穿主进程 ——
39
40
  // 见 shared/view_liveness.cjs 顶部(2026-10-30 白屏事故的 22 次崩溃)。
40
41
  // .cjs 用默认导入(全项目约定,且 tests/test_imports.js 的静态分析只认 ESM export)。
@@ -148,6 +149,15 @@ const CAPTCHA_WALL_RE = /wappass\.baidu\.com|antispider|\/captcha|captcha\.|veri
148
149
  // 它只是展示层的临时文档,不该被当成"一个可返回的页面"。
149
150
  const ERROR_PAGE_RE = /\/renderer\/error_page\.html/;
150
151
 
152
+ // 一个组"没人用"多久之后可以被另一个进程收养(见 ensureGroup)。
153
+ //
154
+ // 为什么需要这段时间:WS 断线重连是毫秒级的,但重连用的是**同一个 key**,
155
+ // 走的是直接命中那条路,压根不需要收养。这里防的是另一种情况 ——
156
+ // A 的进程刚死、B 的进程恰好在同一瞬间起来,别让 B 把 A 的组(连同页)抢走。
157
+ // 200ms 足够覆盖"同一个连接断开又连上",又短于任何进程冷启动(node 起一个
158
+ // MCP server 要 300ms+),所以不会挡住真正的"我回来了"。
159
+ const GROUP_ADOPT_IDLE_MS = 200;
160
+
151
161
  // 具名按键 → CDP Input.dispatchKeyEvent 参数。agent 用自然名字('Delete'、
152
162
  // 'Escape'、'ArrowRight'、'a')而不是让人去查 Windows 虚拟键码。
153
163
  // vk 用 Windows 虚拟键码(Chromium 在 macOS 上也按它解释)。
@@ -230,7 +240,7 @@ class PageManager {
230
240
  // 但此前只有它赋值 —— 换个入口(单测、脚本、未来的新窗口)就 `undefined`,
231
241
  // 而 `preload: undefined` 不报任何错,只表现为"页面读不到树、全超时"。
232
242
  this._preloadPath = path.join(__dirname, '../preload/bridge.cjs');
233
- this.tabs = new Map(); // tabId -> BrowserView
243
+ this.tabs = new Map(); // tabId -> WebContentsView
234
244
  this.activeTab = null;
235
245
  // 启动时那一个标签页。它存在的唯一用途是判断"人眼前这一页是不是还没人动过":
236
246
  // 是的话,agent 开的第一个标签页可以直接顶上去(否则用户会盯着百度首页,
@@ -263,7 +273,17 @@ class PageManager {
263
273
  // 开页面的数量,一个跑长任务的 agent 能悄悄开二十个,内存被无声吃掉。
264
274
  // 归属同时承担三件事:标签栏怎么归拢、上限算谁的、人点开 agent 的页只是"看"。
265
275
  this._tabGroup = new Map(); // tabId -> groupId
266
- this._groups = new Map(); // groupId -> { id, kind, label, color, limit, createdAt }
276
+ this._groups = new Map(); // groupId -> { id, kind, label, color, limit, createdAt, sessions }
277
+ // sessionId -> groupId。连接断开时要回它所属的组里销号(见 unregisterClient)。
278
+ // 组是**可以被多条连接共用**的:同一个 agent 进程重连、或同时开了两个通道。
279
+ this._sessionGroup = new Map();
280
+ // groupKey(一个**进程**的身份)-> groupId。
281
+ // 有了它,同一个进程断线重连还能找回自己那一组;进程换了 key 就用下面的 scope 认亲。
282
+ this._keyToGroup = new Map();
283
+ // groupId -> { seq, color, label, at }:组的"身份证"缓存。
284
+ // 组因为没页被删掉之后,同一个身份再回来还是原来的编号和颜色 ——
285
+ // 否则过一会儿再看,同一个 agent 会变成 "Agent 37" → "Agent 41",人以为多了两个组。
286
+ this._groupIdent = new Map();
267
287
  this._tabUsedAt = new Map(); // tabId -> 最后一次被导航/动作的时间(LRU 淘汰用)
268
288
  this._groupSeq = 0; // 组编号(Agent 1 / Agent 2 …)
269
289
  this.evictions = []; // 被上限挤掉的标签页(最多 20 条,ui.list_tabs 回采后清空)
@@ -737,33 +757,175 @@ class PageManager {
737
757
  // 一个组没有标签页了就删掉 —— 否则标签栏会积一堆空的分组。
738
758
 
739
759
  /** 建(或取)一个 agent 的组。label 是给人看的("Agent 2" / 客户端名)。 */
740
- ensureGroup(sessionId, label, opts) {
741
- const id = tabGroup.groupIdForSession(sessionId);
742
- let g = this._groups.get(id);
760
+ /**
761
+ * 建(或取)一个 agent 的组。
762
+ *
763
+ * 归属键有两层,别混:
764
+ * groupKey —— 一个**进程**的身份(MCP server 启动时生成,重连不变)
765
+ * scope —— 一个**agent 身份**(客户端名 + 工作目录),进程死了它还在
766
+ *
767
+ * 为什么必须有第二层(2026-11-29 第二轮,用户报"一个 agent 还是开多个组"):
768
+ * 客户端的每次新会话都会拉起一个新的 MCP 进程 → 新 groupKey → 新组;
769
+ * 旧组因为还留着页不会被回收。于是同一件事干一天,标签栏上就有三个组,
770
+ * 编号还是 Agent 37 / 41 / 45(序号只涨不复用,看着像来了三个 agent)。
771
+ * 实测复现:连续起两个 MCP server 各 navigate 一次 → 两个组。
772
+ *
773
+ * 规则(按顺序命中,第一个成立就用它):
774
+ * ① 这条连接已经绑过组 → 不换(否则 new_tab 和 navigate 会分家)
775
+ * ② 这个 key 认识 → 还是那一组(进程内重连走这条,最常用)
776
+ * ③ key 陌生(新进程)+ 同 scope 有空闲组 → **收养**它:页还在,编号颜色不变
777
+ * ④ 都没有 → 新建一组,编号/颜色按身份缓存复用(不跳号)
778
+ *
779
+ * 收养只在"组里没有任何活跃连接"时发生,所以并发是安全的:
780
+ * 同一框架里两个 agent 同时干活,先到的占着组,后到的只能新建 ——
781
+ * 这正是用户要的"多个 agent 各自一组";而先后两次会话(人看起来是同一个
782
+ * agent 在接着干)会落到同一组,正是用户抱怨的那个现象的解法。
783
+ */
784
+ ensureGroup(groupKey, label, opts) {
785
+ const key = String(groupKey || '');
786
+ const o = opts || {};
787
+ const wantLabel = String(label || '').trim().slice(0, 24);
788
+ const scope = String(o.scope || '').slice(0, 80);
789
+ const sid = o.sessionId ? String(o.sessionId) : '';
790
+
791
+ // ① 本连接已绑定且组还活着
792
+ if (sid) {
793
+ const bound = this._sessionGroup.get(sid);
794
+ const bg = bound ? this._groups.get(bound) : null;
795
+ if (bg) {
796
+ if (wantLabel) bg.label = wantLabel;
797
+ if (o.capped === true) bg.capped = true;
798
+ if (scope && !bg.scope) bg.scope = scope;
799
+ return bg;
800
+ }
801
+ }
802
+
803
+ // ② 这个进程的 key 命中
804
+ let gid = this._keyToGroup.get(key);
805
+ let g = gid ? this._groups.get(gid) : null;
806
+
807
+ // ③ 进程换了(新会话):同 scope 的空闲组就是"我上一次那个"
808
+ if (!g && scope) {
809
+ const cand = this._adoptableGroup(scope);
810
+ if (cand) { g = cand; gid = cand.id; }
811
+ }
812
+
743
813
  if (!g) {
744
- this._groupSeq += 1;
814
+ // ④ 新建。编号/颜色优先复用身份缓存 —— 组被回收过也不换号。
815
+ // 缓存按 **scope** 存(没有 scope 才退回组 id):进程换了 key 也就换了 id,
816
+ // 按 id 存的话同一个 agent 每次新会话都会拿到新编号。
817
+ const id = tabGroup.groupIdForSession(key);
818
+ const identKey = scope || id;
819
+ let ident = this._groupIdent.get(identKey);
820
+ // 身份缓存只在"那个号没人用"时才复用。并发场景下同一个 scope 会有两组
821
+ // (先到的收养了旧组,同时又起的那个只能新建),这时候如果还照着缓存发号,
822
+ // 标签栏上就会出现两个都叫 "Agent 3" 的组 —— 比多一组更难理解。
823
+ if (ident && ident.gid && ident.gid !== id && this._groups.has(ident.gid)) ident = null;
824
+ const seq = ident ? ident.seq : (this._groupSeq += 1);
745
825
  g = {
746
826
  id,
747
827
  kind: 'agent',
748
- label: String(label || '').trim().slice(0, 24) || ('Agent ' + this._groupSeq),
749
- // 颜色按组的诞生顺序取,不按 sessionId 哈希:人记的是"紫色的那个",
828
+ scope,
829
+ seq,
830
+ label: wantLabel || (ident && ident.label) || ('Agent ' + seq),
831
+ // 颜色按组的诞生顺序取,不按 key 哈希:人记的是"紫色的那个",
750
832
  // 哈希出来每组都可能撞色。
751
- color: tabGroup.colorFor(this._groupSeq - 1),
833
+ color: (ident && ident.color) || tabGroup.colorFor(seq - 1),
752
834
  limit: tabGroup.limitFromEnv(process.env),
753
835
  // capped = 这个组受限额约束。只有**声明过自己是 agent** 的连接才有
754
836
  // (ui.hello);裸 WS(e2e / 脚本 / 调试)拿到组只是为了让标签页有归属,
755
837
  // 不受限 —— 否则一次性开二十个标签的回归套件会突然报 group-full。
756
838
  capped: false,
839
+ // 这个组现在被哪几个连接用着。最后一个连接走了、组里又没页 → 整组回收。
840
+ // 不看这个的话,CLI 每条命令、每次断线重连都会在 _groups 里留一个空组。
841
+ sessions: new Set(),
757
842
  createdAt: Date.now(),
843
+ lastUsedAt: Date.now(),
758
844
  };
759
- this._groups.set(id, g);
760
- } else if (label) {
761
- g.label = String(label).trim().slice(0, 24) || g.label;
845
+ gid = id;
846
+ // 同一个客户端并发两个组时,光靠客户端名分不出谁是谁(两组都叫 "Trae")。
847
+ // 撞名就补一个编号后缀 —— 标签栏上"Trae"和"Trae #4"至少能指着说话。
848
+ if (this._labelTaken(g.label, id)) {
849
+ g.label = `${String(g.label).replace(/ #\d+$/, '')} #${seq}`;
850
+ }
851
+ this._groups.set(gid, g);
852
+ this._groupIdent.set(identKey, { seq, color: g.color, label: g.label, at: Date.now(), gid });
853
+ } else {
854
+ if (wantLabel) g.label = wantLabel;
855
+ if (scope && !g.scope) g.scope = scope;
856
+ g.lastUsedAt = Date.now();
857
+ }
858
+
859
+ if (o.capped === true) g.capped = true;
860
+ if (key) {
861
+ this._keyToGroup.set(key, gid);
862
+ this._pruneKeyMap();
863
+ }
864
+ // 连接 → 组的反查:unregisterClient 收这条连接时要知道去哪个组里销号。
865
+ // 同一个组可以被多条连接共用(同一个 agent 重连、或同时开了两个通道),
866
+ // 所以这里记的是"引用",不是"所有权"。
867
+ if (sid) {
868
+ if (!(g.sessions instanceof Set)) g.sessions = new Set();
869
+ g.sessions.add(sid);
870
+ delete g.idleSince;
871
+ this._sessionGroup.set(sid, gid);
762
872
  }
763
- if (opts && opts.capped === true) g.capped = true;
764
873
  return g;
765
874
  }
766
875
 
876
+ /**
877
+ * 找一个可以被收养的同身份组:同 scope、**没有活跃连接**、闲置够久。
878
+ * 多个候选时取最近用过的 —— agent 刚用完的那一组最可能还想接着干。
879
+ */
880
+ _adoptableGroup(scope) {
881
+ const now = Date.now();
882
+ let best = null;
883
+ let bestAt = -1;
884
+ for (const g of this._groups.values()) {
885
+ if (g.kind !== 'agent' || g.scope !== scope) continue;
886
+ if (g.sessions instanceof Set && g.sessions.size) continue; // 有人正在用,不抢
887
+ const idle = Number(g.idleSince) || 0;
888
+ if (idle && now - idle < GROUP_ADOPT_IDLE_MS) continue; // 刚断开,可能在重连
889
+ const at = Number(g.lastUsedAt) || Number(g.createdAt) || 0;
890
+ if (at > bestAt) { best = g; bestAt = at; }
891
+ }
892
+ return best;
893
+ }
894
+
895
+ /** 这个显示名是不是已经有别的组在用了(撞名时新建的那个要加后缀)。 */
896
+ _labelTaken(label, exceptId) {
897
+ const want = String(label || '');
898
+ for (const [gid, g] of this._groups) {
899
+ if (gid === exceptId) continue;
900
+ if (g.label === want) return true;
901
+ }
902
+ return false;
903
+ }
904
+
905
+ /** key → 组 的反查表别无限长:顺手把指向已删组的条目清掉。 */ _pruneKeyMap() {
906
+ if (this._keyToGroup.size <= 128) return;
907
+ for (const [k, gid] of this._keyToGroup) {
908
+ if (!this._groups.has(gid)) this._keyToGroup.delete(k);
909
+ }
910
+ }
911
+
912
+ /** 组要被删之前留个身份证,下次同一个身份回来还叫这个名字、还是这个颜色。 */
913
+ _rememberGroupIdentity(g) {
914
+ if (!g || !g.id) return;
915
+ this._groupIdent.set(g.scope || g.id, {
916
+ seq: Number(g.seq) || 0,
917
+ color: g.color,
918
+ label: g.label,
919
+ at: Date.now(),
920
+ gid: g.id,
921
+ });
922
+ if (this._groupIdent.size > 64) {
923
+ // 只保留最近 64 个身份:这是给人看的编号,不是审计记录。
924
+ const entries = [...this._groupIdent.entries()].sort((a, b) => (a[1].at || 0) - (b[1].at || 0));
925
+ for (let i = 0; i < entries.length - 64; i++) this._groupIdent.delete(entries[i][0]);
926
+ }
927
+ }
928
+
767
929
  groupOfTab(tabId) {
768
930
  return this._tabGroup.get(tabId) || tabGroup.HUMAN_GROUP;
769
931
  }
@@ -856,7 +1018,10 @@ class PageManager {
856
1018
  for (const [gid, meta] of this._groups) {
857
1019
  const tabs = this.tabsInGroup(gid);
858
1020
  if (!tabs.length) continue;
859
- out.push({ ...meta, count: tabs.length });
1021
+ // sessions 是内部引用计数(Set),seq 是内部编号:都不进回执 ——
1022
+ // 既不给人看,序列化出来也只是 {} 或者一个没人用的数字。
1023
+ const { sessions, seq, ...pub } = meta;
1024
+ out.push({ ...pub, count: tabs.length });
860
1025
  }
861
1026
  out.sort((a, b) => a.createdAt - b.createdAt);
862
1027
  return out;
@@ -999,9 +1164,15 @@ class PageManager {
999
1164
  this._lastMainUrl.delete(tabId);
1000
1165
  this._failedNav.delete(tabId);
1001
1166
  if (!gid || gid === tabGroup.HUMAN_GROUP) return;
1002
- // 组空了就删:留在 Map 里会让标签栏出现一个 0 页的分组,下次同名 agent
1003
- // 重连还会复用那个组的编号/颜色,看起来像"上一轮的残留"。
1004
- if (!this.tabsInGroup(gid).length) this._groups.delete(gid);
1167
+ // 组空了就删:留在 Map 里会让标签栏出现一个 0 页的分组。
1168
+ // 删之前先把"身份证"存下来 —— 同一个身份下次回来还是原来的编号和颜色,
1169
+ // 不会从 "Agent 37" 变成 "Agent 41"(那会让人以为又多了一个 agent)。
1170
+ if (!this.tabsInGroup(gid).length) {
1171
+ const g = this._groups.get(gid);
1172
+ if (g) this._rememberGroupIdentity(g);
1173
+ this._groups.delete(gid);
1174
+ this._pruneKeyMap();
1175
+ }
1005
1176
  }
1006
1177
 
1007
1178
  /** 把一页挪进某个组(人"接手" agent 的页 / 反向都走这条)。 */
@@ -1026,6 +1197,19 @@ class PageManager {
1026
1197
  return t === undefined ? null : t;
1027
1198
  }
1028
1199
 
1200
+ /**
1201
+ * 这条连接归属哪个组。
1202
+ *
1203
+ * 不能假设它等于 `agent:<sessionId>` —— 进程换了身份(scope 相同)时组会被
1204
+ * **收养**,id 还是上一个进程那个。list_tabs 回执的 `mine` 标记靠它,
1205
+ * 猜错的话 agent 会看到一个"没有自己的组"。
1206
+ */
1207
+ groupOfSession(sessionId) {
1208
+ if (!sessionId) return null;
1209
+ const gid = this._sessionGroup.get(sessionId);
1210
+ return gid && this._groups.has(gid) ? gid : null;
1211
+ }
1212
+
1029
1213
  /**
1030
1214
  * 这次调用操作哪个标签页。判据只有 shared/tab_route.cjs 一处,这里只把
1031
1215
  * "当前有哪些标签页"和"人眼看的是哪个"喂给它。
@@ -1044,6 +1228,24 @@ class PageManager {
1044
1228
  this._wsClients.delete(sessionId);
1045
1229
  this.subscriptions.delete(sessionId);
1046
1230
  this._sessionTab.delete(sessionId);
1231
+ // 组的引用计数:这条连接走了,从它所属的组里销号。
1232
+ // · 组里没别的连接、也没有页 → 整组回收(CLI 每条命令、纯探测连接都走这条,
1233
+ // 否则 _groups 会随连接数无限累积,_groupSeq 一直涨、新组颜色跟着漂)
1234
+ // · 组里还有页 → **保留**。人可能还要看 agent 干到哪一步;agent 自己的进程
1235
+ // 重连后也会拿同一个 key 找回这一组继续干(2026-11-29 用户要的行为)。
1236
+ const gid = this._sessionGroup.get(sessionId);
1237
+ if (!gid) return;
1238
+ this._sessionGroup.delete(sessionId);
1239
+ const g = this._groups.get(gid);
1240
+ if (!g) return;
1241
+ if (g.sessions instanceof Set) g.sessions.delete(String(sessionId));
1242
+ const noClients = !(g.sessions instanceof Set) || g.sessions.size === 0;
1243
+ if (!noClients) return;
1244
+ // 记下"没人用了"的时刻:另一个进程想收养这个组,得等过 GROUP_ADOPT_IDLE_MS,
1245
+ // 免得 A 刚断线重连的那一瞬间被 B 抢走(见 ensureGroup ③)。
1246
+ g.idleSince = Date.now();
1247
+ this._rememberGroupIdentity(g);
1248
+ if (!this.tabsInGroup(gid).length) this._groups.delete(gid);
1047
1249
  }
1048
1250
 
1049
1251
  /**
@@ -2005,21 +2207,43 @@ class PageManager {
2005
2207
  async _shotFromSurface(view, o) {
2006
2208
  const wc = view && view.webContents;
2007
2209
  if (!wc || wc.isDestroyed()) return null;
2008
- let img = null;
2009
2210
  // 黑匣子:capturePage 是主进程里最"原生"的一条路(拿视图合成表面 → NSImage)。
2010
2211
  // 2026-11-28 那两次 objc_retain 段错误都在 JS 回调里,capturePage 与
2011
- // addBrowserView 是两个头号嫌疑,谁都不标就永远只能猜。
2212
+ // addChildView 是两个头号嫌疑,谁都不标就永远只能猜。
2012
2213
  const flight = flightBegin('native:capturePage', {
2013
2214
  tab: (() => { try { return this._tabIdOfWebContents(wc); } catch { return null; } })(),
2014
2215
  });
2216
+ // 为什么要重试(2026-11-29,Electron 45 / WebContentsView):
2217
+ //
2218
+ // 一个**从没被顶上来的**标签页,合成表面可能还不存在,第一次 capturePage 拿到
2219
+ // 的是空图(`no-surface-frame`)。而这一次调用本身会把它踢着画一帧 ——
2220
+ // 实测同一个视图:55ms 那发返回空,50ms 后再发就有图了。
2221
+ //
2222
+ // 所以这里不是"等它画"而是"踢一脚再拿":每次尝试给 1.5s 上界(真挂住时不能
2223
+ // 一口气吃掉全部预算),空图就隔 120ms 再试,总时长仍受 _surfaceShotBudgetMs 约束。
2224
+ // 主线程被占死的页面不会因此变快 —— 那种情况本来就该落回 CDP 档。
2225
+ const budget = this._surfaceShotBudgetMs();
2226
+ const hardStop = Date.now() + budget;
2227
+ let img = null;
2015
2228
  try {
2016
- img = await withDeadline(wc.capturePage(), this._surfaceShotBudgetMs(), 'capturePage');
2017
- } catch (_) {
2018
- return null;
2229
+ for (let attempt = 0; attempt < 4; attempt++) {
2230
+ const left = hardStop - Date.now();
2231
+ if (left <= 0) break;
2232
+ const slice = Math.min(1500, left);
2233
+ try {
2234
+ img = await withDeadline(wc.capturePage(), slice, 'capturePage');
2235
+ } catch (_) {
2236
+ img = null;
2237
+ }
2238
+ if (img && typeof img.isEmpty === 'function' && !img.isEmpty()) break;
2239
+ img = null;
2240
+ if (Date.now() >= hardStop) break;
2241
+ await new Promise((r) => setTimeout(r, 120));
2242
+ }
2019
2243
  } finally {
2020
2244
  flightEnd(flight);
2021
2245
  }
2022
- if (!img || typeof img.isEmpty !== 'function' || img.isEmpty()) return null;
2246
+ if (!img) return null;
2023
2247
  let buf = null;
2024
2248
  try {
2025
2249
  buf = o.format === 'jpeg'
@@ -2616,8 +2840,8 @@ class PageManager {
2616
2840
  * 复用 _focusWebContents —— 它就是 AI_BROWSER_FOCUS=auto 的本体("只伪造页面内焦点态,
2617
2841
  * 不抢真实窗口焦点"),产品每个活动页都在用它。这里不是新招,是把同一招给到那一页,
2618
2842
  * 让投得进模拟输入。实测(tools 探针,逐杠杆):
2619
- * 置顶 setTopBrowserView → document 照旧 hidden、事件照旧没
2620
- * webContents.focus() / remove+addBrowserView / setBounds / setBackgroundThrottling
2843
+ * 置顶(再 addChildView)→ document 照旧 hidden、事件照旧没
2844
+ * webContents.focus() / remove+addChildView / setBounds / setBackgroundThrottling
2621
2845
  * / invalidate / Page.setWebLifecycleState{active} → 全部无效
2622
2846
  * Emulation.setFocusEmulationEnabled{enabled:true} → 一次就翻转,点击与键入都落到位
2623
2847
  *
@@ -4611,7 +4835,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4611
4835
  }
4612
4836
  const tabId = ++this.tabCounter;
4613
4837
  const self = this;
4614
- const view = new BrowserView({
4838
+ const view = createView({
4615
4839
  webPreferences: {
4616
4840
  preload: this._preloadPath,
4617
4841
  contextIsolation: true,
@@ -4636,8 +4860,8 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4636
4860
  //
4637
4861
  // 所有标签页的视图都常驻窗口、叠在**同一块 bounds** 上(为什么不"不显示就不挂"
4638
4862
  // 见下面 2026-10-28 那段:没挂进窗口的视图没有合成表面,ui.screenshot 直接
4639
- // 0 字节),可见与否只由 `_raiseView` 的 setTopBrowserView 决定。但 z 序只决定
4640
- // **谁在上面**,不保证**上面那张不透**:BrowserView 的默认背景是透明的,于是
4863
+ // 0 字节),可见与否只由 `_raiseView` 的置顶决定。但 z 序只决定
4864
+ // **谁在上面**,不保证**上面那张不透**:视图的默认背景是透明的,于是
4641
4865
  // 一个根背景透明的页面作为顶层文档打开时,透明像素会把**下面那张视图**照出来 ——
4642
4866
  // 也就是另一个标签页的内容。实测现场(auth.smartedu.cn/uias/login,按 iframe
4643
4867
  // 浮层设计、html/body 都是 rgba(0,0,0,0)):活动标签页自己截出来的帧是
@@ -4652,6 +4876,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4652
4876
  // 后清理空组)都读这一条,晚设一步就会出现"页已经在了、但没人认领"的窗口期。
4653
4877
  this._tabGroup.set(tabId, opts.group || tabGroup.HUMAN_GROUP);
4654
4878
  this._tabUsedAt.set(tabId, Date.now());
4879
+ // 组最近什么时候被用过:收养(ensureGroup ③)靠它挑"最可能还想接着干"的那一组。
4880
+ {
4881
+ const g = opts.group ? this._groups.get(opts.group) : null;
4882
+ if (g) g.lastUsedAt = Date.now();
4883
+ }
4655
4884
  // 每个标签页、从出生起就关掉后台节流。以前只在 setActive 里设,于是"从没
4656
4885
  // 被显示过"的标签页永远带着节流:定时器被拉长到 1s、rAF 停摆,站点的轮询/
4657
4886
  // 动画/自动保存全部变慢,而 agent 看起来只是"这一页有点慢"。
@@ -4759,7 +4988,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4759
4988
 
4760
4989
  // 可见与否由调用方决定,但**所有**标签页都挂进窗口、用 z 序决定谁在上面。
4761
4990
  //
4762
- // 为什么不"不显示就不挂"(2026-10-28 实测):没挂进窗口的 BrowserView 根本
4991
+ // 为什么不"不显示就不挂"(2026-10-28 实测):没挂进窗口的视图根本
4763
4992
  // 没有合成表面 —— 读树/点击/输入/导航全都正常(那走的是渲染进程和 CDP 输入),
4764
4993
  // 但 ui.screenshot 拿到 0 字节、ui.paint_check 直接 no-frame。也就是说
4765
4994
  // "后台标签页"会变成一个**看不见也拍不到**的黑盒,而 agent 恰恰靠截图判断
@@ -4787,7 +5016,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4787
5016
  }
4788
5017
 
4789
5018
  // canvas 绘制记录必须在**首个真实导航之前**装好,否则页面早画完了什么都录不到。
4790
- // 但它又必须在 setActive 之后:BrowserView 还没被加进窗口时,debugger 通道
5019
+ // 但它又必须在 setActive 之后:视图还没被加进窗口时,debugger 通道
4791
5020
  // 不响应(实测 Runtime.enable 直接挂死)。
4792
5021
  // newTab 仍同步返回 tabId(调用方依赖),导航推迟到 hook 装完;安装失败或超时
4793
5022
  // 也照常导航 —— 绝不能因为要录 canvas 就把 tab 卡死。
@@ -4891,7 +5120,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4891
5120
  // ⚠️ 导航事件**不挂任何重绘**(2026-10-25 修)。
4892
5121
  //
4893
5122
  // 历史:这条钩子是为了对付"页面已导航但窗口还显示旧画面",手段是
4894
- // removeBrowserView + addBrowserView(后来换成 invalidate)。但两者都有代价:
5123
+ // removeChildView + addChildView(后来换成 invalidate)。但两者都有代价:
4895
5124
  // remove/add 会闪一帧白;invalidate() 更麻烦 —— 它强制整页重新栅格化,
4896
5125
  // 而在导航刚开始的那一刻,图层的尺寸还是初始值,于是合成器会先把新页面画进
4897
5126
  // 一个小尺寸 surface 再缩放显示:用户看到的就是"先缩成左上角一小块,闪一下,
@@ -5017,7 +5246,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5017
5246
  }
5018
5247
 
5019
5248
  /**
5020
- * Remove + re-add the BrowserView to force the compositor to paint it.
5249
+ * Remove + re-add the view to force the compositor to paint it.
5021
5250
  * Safe for a non-active tab too: the view is re-added in the same position
5022
5251
  * (only the active view is normally attached, so re-adding an inactive one
5023
5252
  * would show it — guard by re-asserting the active view afterwards).
@@ -5067,8 +5296,8 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5067
5296
  * 重新栅格化**(尺寸不变时 setBounds 被 Chromium 直接忽略)。
5068
5297
  *
5069
5298
  * 为什么要分档(2026-10-25 用户报"一闪一闪、大一下小一下"):
5070
- * 1px 微调必然触发两次重排,文字会肉眼可见地跳一下;再叠 removeBrowserView /
5071
- * addBrowserView 还会闪一帧白。把这套放在"每次导航完成 / 每次窗口焦点变化"
5299
+ * 1px 微调必然触发两次重排,文字会肉眼可见地跳一下;再叠 removeChildView /
5300
+ * addChildView 还会闪一帧白。把这套放在"每次导航完成 / 每次窗口焦点变化"
5072
5301
  * 这种高频路径上,就变成了用户看到的抽搐。
5073
5302
  * 所以高频路径一律 soft;只有"确认 surface 尺寸脱节"(scale-mismatch、白屏阶梯)
5074
5303
  * 才付 hard 的代价。
@@ -5675,7 +5904,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5675
5904
  // 黑匣子:摘视图 + 销毁 webContents 是另一处"主进程动原生对象"的地方。
5676
5905
  const flight = flightBegin('native:closeTab', { tab: tabId });
5677
5906
  try {
5678
- this.window.removeBrowserView(view);
5907
+ detach(this.window, view);
5679
5908
  if (view.webContents && !view.webContents.isDestroyed()) {
5680
5909
  try { view.webContents.debugger.detach(); } catch(e) {}
5681
5910
  view.webContents.close();
@@ -5697,7 +5926,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5697
5926
  this._cleanupTabResources(tabId);
5698
5927
 
5699
5928
  if (this.activeTab === tabId || this.activeTab === null) {
5700
- // switch to first remaining tab — must re-addBrowserView
5929
+ // switch to first remaining tab — must re-attach the view
5701
5930
  const first = this.tabs.keys().next();
5702
5931
  this.activeTab = first.done ? null : first.value;
5703
5932
  // 上面是直接改 activeTab(没走 setActive),monitor 不会自己知道;
@@ -5705,7 +5934,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5705
5934
  this.networkMonitor.setActiveTab(this.activeTab);
5706
5935
  if (!first.done) {
5707
5936
  const nextView = this._getView(this.activeTab);
5708
- // 走 _attachView 而不是裸 this.window.addBrowserView:窗口正在销毁时后者会抛,
5937
+ // 走 _attachView 而不是裸 contentView.addChildView:窗口正在销毁时后者会抛,
5709
5938
  // 而这一抛会把后面的重排、_syncMute 全跳过 —— 结果 activeTab 已经换了,
5710
5939
  // 视图和声音却还停在刚关掉的那一页上。
5711
5940
  this._attachView(nextView);
@@ -5835,31 +6064,25 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5835
6064
  _attachView(view) {
5836
6065
  if (!view || !this.window) return;
5837
6066
  try {
5838
- const attached = this.window.getBrowserViews ? this.window.getBrowserViews() : [];
5839
- if (attached.indexOf(view) < 0) {
5840
- // 黑匣子:addBrowserView 是"把一个 NSView 挂进窗口",AppKit 这边一旦拿到
6067
+ if (!isAttached(this.window, view)) {
6068
+ // 黑匣子:addChildView 是"把一个 NSView 挂进窗口",AppKit 这边一旦拿到
5841
6069
  // 失效对象就是 native 段错误,JS 侧什么都记不到。
5842
- const flight = flightBegin('native:addBrowserView');
5843
- try { this.window.addBrowserView(view); } finally { flightEnd(flight); }
6070
+ const flight = flightBegin('native:addChildView');
6071
+ try { attach(this.window, view); } finally { flightEnd(flight); }
5844
6072
  }
5845
6073
  } catch (_) { /* 窗口正在销毁 */ }
5846
6074
  }
5847
6075
 
5848
- /** 把某个视图提到最上层(= 人看到它)。老版本没有 setTopBrowserView 时退回 remove+add。 */
6076
+ /**
6077
+ * 把某个视图提到最上层(= 人看到它)。
6078
+ *
6079
+ * 实测(Electron 45):对已在 contentView.children 里的 view 再调
6080
+ * addChildView,它会移到末尾 = 最上层,且**不重建合成表面**。
6081
+ * 所以这里一次调用就够,不要 remove+add —— 那会闪一帧白。
6082
+ */
5849
6083
  _raiseView(view) {
5850
6084
  if (!view || !this.window) return;
5851
- // 优先 setTopBrowserView(不改 surface,只改 z 序)。
5852
- // 如果不可用,退回 remove+add(强制重建 surface,代价是闪一帧白)。
5853
- try {
5854
- if (typeof this.window.setTopBrowserView === 'function') {
5855
- this.window.setTopBrowserView(view);
5856
- return;
5857
- }
5858
- } catch (_) { /* 落到下面的兼容路径 */ }
5859
- try {
5860
- this.window.removeBrowserView(view);
5861
- this.window.addBrowserView(view);
5862
- } catch (_) { /* 已销毁 */ }
6085
+ try { raise(this.window, view); } catch (_) { /* 已销毁 */ }
5863
6086
  }
5864
6087
 
5865
6088
  /** 「人眼前还是启动页」这个判断只对**没被动过**的启动页成立(见 shouldShowNewTab)。 */
@@ -6261,7 +6484,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
6261
6484
  mode: 'semantic',
6262
6485
  });
6263
6486
 
6264
- // ⚠️ 实测结论:在**刚创建的 BrowserView** 上,await dbg.sendCommand('Runtime.enable')
6487
+ // ⚠️ 实测结论:在**刚创建的视图**上,await dbg.sendCommand('Runtime.enable')
6265
6488
  // 永远不返回(试过 20 秒、8 次重试,全部挂死),而同样"发了不等"的
6266
6489
  // Network.enable 却是生效的。也就是说:命令能送达,但响应在这个阶段回不来。
6267
6490
  // 因此这里一律 **fire-and-forget**,改用 Runtime.evaluate 去**验证**是否真的装上。
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 视图层适配 —— Electron 45。
3
+ *
4
+ * 33 时代这里用的是 `BrowserView` + `window.addBrowserView / setTopBrowserView`。
5
+ * `BrowserView` 自 Electron 30 起被 `WebContentsView` 取代,官方文档已标
6
+ * "use WebContentsView instead";45 里这个类还在,但那是给老代码留的通道,
7
+ * 迟早会删。既然升一次版本要重跑全套 e2e,就一次迁完,不做"先升 38 再迁"。
8
+ *
9
+ * 映射(语义已实测,不是照文档抄的):
10
+ * new BrowserView({webPreferences}) → new WebContentsView({webPreferences})
11
+ * win.addBrowserView(v) → win.contentView.addChildView(v)
12
+ * win.removeBrowserView(v) → win.contentView.removeChildView(v)
13
+ * win.setTopBrowserView(v) → win.contentView.addChildView(v)
14
+ * win.getBrowserViews().includes(v) → win.contentView.children.includes(v)
15
+ *
16
+ * 关键实测结论(2026-11-29,探针见提交说明):
17
+ * 1. `contentView.children` 一开始是 **0** —— 窗口自己的页面不是这个列表的
18
+ * 元素,所以这里只会有我们加的视图,`indexOf` 判断不会误伤。
19
+ * 2. 对一个**已经在 children 里**的 view 再调 `addChildView`,它会从原位置
20
+ * 移到末尾,也就是**最上层**(v1,v2,v3 → v2,v3,v1)。所以"置顶"就是再
21
+ * add 一次,不需要 remove+add —— 后者会重建合成表面,闪一帧白。
22
+ * 3. `removeChildView` 不会销毁 webContents(isDestroyed 仍为 false),
23
+ * 重新 add 后 `capturePage` 正常出图。
24
+ *
25
+ * bounds 语义不变:仍是相对内容区左上角。
26
+ */
27
+
28
+ import { WebContentsView } from 'electron';
29
+
30
+ /** 造一个承载页面的视图。参数形状与 BrowserView 一致({ webPreferences })。 */
31
+ export function createView(options) {
32
+ return new WebContentsView(options);
33
+ }
34
+
35
+ /** 取内容视图容器;窗口正在销毁时返回 null,调用方按"做不了"处理。 */
36
+ function container(win) {
37
+ try {
38
+ if (!win || win.isDestroyed()) return null;
39
+ return win.contentView || null;
40
+ } catch (_) {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ /** 这个视图当前是否挂在窗口上。 */
46
+ export function isAttached(win, view) {
47
+ const cv = container(win);
48
+ if (!cv || !view) return false;
49
+ try {
50
+ return cv.children.indexOf(view) >= 0;
51
+ } catch (_) {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * 挂进窗口(幂等)。已挂着就什么都不做 —— 重复 add 会把它提到最上层,
58
+ * 那是 raise 的语义,不该由 attach 顺手做掉。
59
+ */
60
+ export function attach(win, view) {
61
+ const cv = container(win);
62
+ if (!cv || !view) return false;
63
+ try {
64
+ if (cv.children.indexOf(view) >= 0) return false;
65
+ cv.addChildView(view);
66
+ return true;
67
+ } catch (_) {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /** 从窗口摘掉(幂等)。不销毁 webContents —— 由调用方决定要不要 close。 */
73
+ export function detach(win, view) {
74
+ const cv = container(win);
75
+ if (!cv || !view) return false;
76
+ try {
77
+ if (cv.children.indexOf(view) < 0) return false;
78
+ cv.removeChildView(view);
79
+ return true;
80
+ } catch (_) {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 置顶(= 人看到它)。等价于旧的 setTopBrowserView。
87
+ * 已在列表里 → 移到末尾;不在 → 顺带挂上。两种情形一次调用都覆盖。
88
+ */
89
+ export function raise(win, view) {
90
+ const cv = container(win);
91
+ if (!cv || !view) return false;
92
+ try {
93
+ cv.addChildView(view);
94
+ return true;
95
+ } catch (_) {
96
+ return false;
97
+ }
98
+ }
@@ -17,7 +17,7 @@
17
17
  // about:blank。现在的实现用 Object.defineProperty 装一个带 setter 的
18
18
  // 访问器来复刻 PutForwards 语义。
19
19
  //
20
- // 为什么必须走 CDP 注入而不是 preload:tab 的 BrowserView 是
20
+ // 为什么必须走 CDP 注入而不是 preload:tab 的视图是
21
21
  // contextIsolation:true,preload 里写的 window.open 只作用于 isolated
22
22
  // world 的 window,页面脚本看到的仍是原生 window.open(第一版就是这么
23
23
  // 失败的——隔离测试里 window.open() 返回 falsy)。Page.addScriptToEvaluate