@glittering0717/ai-browser 2.1.21 → 2.3.0

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.
@@ -39,6 +39,10 @@ import { DownloadMonitor } from './download_monitor.js';
39
39
  // 2026-10-27 用户报"点证书下载 → 卡在正在打开… + 一坨 png URL")。
40
40
  import mediaDoc from '../shared/media_doc.cjs';
41
41
  import { MediaInline } from './media_inline.js';
42
+ // 默认目标标签页的判据(explicit > session > active > first)与"新标签页要不要
43
+ // 切到人眼前"的策略。见 shared/tab_route.cjs 顶部(多 agent 并用的三条事故)。
44
+ import tabRoute, { shouldShowChildTab } from '../shared/tab_route.cjs';
45
+ import tabGroup from '../shared/tab_group.cjs';
42
46
  import { probeCapabilities } from './capability_probe.js';
43
47
  import valueContract from '../shared/value_contract.cjs';
44
48
  // 输入成功与否的判定口径(纯函数,独立模块便于单测)。详见文件内注释:
@@ -186,6 +190,10 @@ class PageManager {
186
190
  this.window = browserWindow;
187
191
  this.tabs = new Map(); // tabId -> BrowserView
188
192
  this.activeTab = null;
193
+ // 启动时那一个标签页。它存在的唯一用途是判断"人眼前这一页是不是还没人动过":
194
+ // 是的话,agent 开的第一个标签页可以直接顶上去(否则用户会盯着百度首页,
195
+ // 以为 agent 什么都没干)。见 shared/tab_route.cjs 的 shouldShowNewTab。
196
+ this.startupTab = null;
189
197
  this.tabCounter = 0;
190
198
  // 窗口首次显示时的那一刻状态(tab / body_len / ready_state)。
191
199
  // 白屏类缺陷的根因是"窗口显示了但渲染器还没画出第一帧",而这只能从窗口侧
@@ -196,6 +204,24 @@ class PageManager {
196
204
  this._pendingRequests = new Map();
197
205
  this._requestId = 0;
198
206
  this._wsClients = new Map();
207
+ // sessionId -> tabId:**这个连接自己的工作标签页**。
208
+ //
209
+ // 为什么必须有(2026-10-27 多 agent 并用):默认目标以前是全局 activeTab,
210
+ // 也就是"人眼看的那一页"。多个 agent 同时干活时它立刻崩掉 —— A 开一个标签页,
211
+ // 所有人的默认目标都变成它;B 说"点提交",点在 A 的页面上。判据与优先级见
212
+ // shared/tab_route.cjs(explicit > session > active > first)。
213
+ this._sessionTab = new Map();
214
+ // ---- 标签页归属(人的一组,每个 agent 一组)----
215
+ //
216
+ // 为什么需要它:会话级目标解决了"动作落在哪一页",但标签条上仍然是一锅粥 ——
217
+ // 人看不出哪些页是自己的、哪些是哪个 agent 的;也没有任何东西**约束** agent
218
+ // 开页面的数量,一个跑长任务的 agent 能悄悄开二十个,内存被无声吃掉。
219
+ // 归属同时承担三件事:标签栏怎么归拢、上限算谁的、人点开 agent 的页只是"看"。
220
+ this._tabGroup = new Map(); // tabId -> groupId
221
+ this._groups = new Map(); // groupId -> { id, kind, label, color, limit, createdAt }
222
+ this._tabUsedAt = new Map(); // tabId -> 最后一次被导航/动作的时间(LRU 淘汰用)
223
+ this._groupSeq = 0; // 组编号(Agent 1 / Agent 2 …)
224
+ this.evictions = []; // 被上限挤掉的标签页(最多 20 条,ui.list_tabs 回采后清空)
199
225
  this._openedTabs = new Map(); // sourceTabId -> { id, url } (new tab opened by window.open)
200
226
  this._windowOpenTokens = new Map(); // token -> { tabId, sourceTabId } (window.open shim, preload bridge.cjs)
201
227
  this._windowOpenShimTabs = new Set(); // 已注入 window.open 垫片的 tabId
@@ -484,9 +510,166 @@ class PageManager {
484
510
  this._wsClients.set(sessionId, ws);
485
511
  }
486
512
 
513
+ /**
514
+ * 把这个连接"自己的工作标签页"记下来。
515
+ * 断开连接时**不关页面**:agent 进程退出后,人可能正想看看它干到哪了。
516
+ */
517
+ // ---- 标签页归属 ----------------------------------------------------------
518
+ //
519
+ // 组 id 有两条来源:HUMAN_GROUP(人点「+」、启动页、人点链接派生出来的页)
520
+ // 和 groupIdForSession(sessionId)(一个 agent 连接一组)。
521
+ // 一个组没有标签页了就删掉 —— 否则标签栏会积一堆空的分组。
522
+
523
+ /** 建(或取)一个 agent 的组。label 是给人看的("Agent 2" / 客户端名)。 */
524
+ ensureGroup(sessionId, label, opts) {
525
+ const id = tabGroup.groupIdForSession(sessionId);
526
+ let g = this._groups.get(id);
527
+ if (!g) {
528
+ this._groupSeq += 1;
529
+ g = {
530
+ id,
531
+ kind: 'agent',
532
+ label: String(label || '').trim().slice(0, 24) || ('Agent ' + this._groupSeq),
533
+ // 颜色按组的诞生顺序取,不按 sessionId 哈希:人记的是"紫色的那个",
534
+ // 哈希出来每组都可能撞色。
535
+ color: tabGroup.colorFor(this._groupSeq - 1),
536
+ limit: tabGroup.limitFromEnv(process.env),
537
+ // capped = 这个组受限额约束。只有**声明过自己是 agent** 的连接才有
538
+ // (ui.hello);裸 WS(e2e / 脚本 / 调试)拿到组只是为了让标签页有归属,
539
+ // 不受限 —— 否则一次性开二十个标签的回归套件会突然报 group-full。
540
+ capped: false,
541
+ createdAt: Date.now(),
542
+ };
543
+ this._groups.set(id, g);
544
+ } else if (label) {
545
+ g.label = String(label).trim().slice(0, 24) || g.label;
546
+ }
547
+ if (opts && opts.capped === true) g.capped = true;
548
+ return g;
549
+ }
550
+
551
+ groupOfTab(tabId) {
552
+ return this._tabGroup.get(tabId) || tabGroup.HUMAN_GROUP;
553
+ }
554
+
555
+ groupMeta(groupId) {
556
+ const id = groupId || tabGroup.HUMAN_GROUP;
557
+ if (id === tabGroup.HUMAN_GROUP) {
558
+ return { id, kind: 'human', label: '我的标签页', color: null, limit: null };
559
+ }
560
+ return this._groups.get(id) || { id, kind: 'agent', label: id, color: null, limit: null };
561
+ }
562
+
563
+ /** 组里还有哪些页(按 tabId 升序 = 创建顺序)。 */
564
+ tabsInGroup(groupId) {
565
+ const out = [];
566
+ for (const [id] of this.tabs) {
567
+ if (this.groupOfTab(id) === groupId) {
568
+ out.push({
569
+ id,
570
+ url: this.tabs.get(id).webContents.getURL(),
571
+ usedAt: this._tabUsedAt.get(id) || 0,
572
+ dialog: this._openDialogs.has(id) ? true : undefined,
573
+ });
574
+ }
575
+ }
576
+ return out;
577
+ }
578
+
579
+ /** 这个组还能不能再开一页。 */
580
+ canOpenInGroup(groupId) {
581
+ const meta = this.groupMeta(groupId);
582
+ // 没被标记 capped 的组(裸 WS / 脚本拿到的组)不限量:组只是个归属标签。
583
+ if (meta.capped !== true) return { allowed: true, count: this.tabsInGroup(groupId).length, limit: null, remaining: null };
584
+ return tabGroup.decideOpen({
585
+ group: groupId,
586
+ count: this.tabsInGroup(groupId).length,
587
+ limit: meta.limit,
588
+ });
589
+ }
590
+
591
+ /** 组满时的牺牲品:最久没用、不在看、没有等人点的对话框。没有就返回 null。 */
592
+ pickEvictableInGroup(groupId, exceptTabId) {
593
+ const meta = this.groupMeta(groupId);
594
+ if (tabGroup.isHumanGroup(groupId)) return null;
595
+ if (meta.capped !== true) return null; // 不受限的组永远不需要牺牲谁
596
+ if (meta.limit && this.tabsInGroup(groupId).length < meta.limit) return null;
597
+ return tabGroup.pickEvictable({
598
+ tabs: this.tabsInGroup(groupId),
599
+ except: exceptTabId,
600
+ activeTab: this.activeTab,
601
+ });
602
+ }
603
+
604
+ /**
605
+ * 记录"这一页刚被用过",供 LRU 淘汰排序。
606
+ * 只在导航/动作这类**作用于页面**的地方调:读一次树不算用过,
607
+ * 否则 agent 循环读树会让真正在用的页被判定为"新",反而淘汰掉该留的。
608
+ */
609
+ touchTab(tabId) {
610
+ if (tabId === undefined || tabId === null) return;
611
+ this._tabUsedAt.set(tabId, Date.now());
612
+ }
613
+
614
+ /** 标签栏/接口用的分组清单(空组已在上面的清理里去掉,这里再滤一遍保险)。 */
615
+ listGroups() {
616
+ const out = [];
617
+ for (const [gid, meta] of this._groups) {
618
+ const tabs = this.tabsInGroup(gid);
619
+ if (!tabs.length) continue;
620
+ out.push({ ...meta, count: tabs.length });
621
+ }
622
+ out.sort((a, b) => a.createdAt - b.createdAt);
623
+ return out;
624
+ }
625
+
626
+ _forgetTab(tabId) {
627
+ const gid = this._tabGroup.get(tabId);
628
+ this._tabGroup.delete(tabId);
629
+ this._tabUsedAt.delete(tabId);
630
+ if (!gid || gid === tabGroup.HUMAN_GROUP) return;
631
+ // 组空了就删:留在 Map 里会让标签栏出现一个 0 页的分组,下次同名 agent
632
+ // 重连还会复用那个组的编号/颜色,看起来像"上一轮的残留"。
633
+ if (!this.tabsInGroup(gid).length) this._groups.delete(gid);
634
+ }
635
+
636
+ /** 把一页挪进某个组(人"接手" agent 的页 / 反向都走这条)。 */
637
+ moveToGroup(tabId, groupId) {
638
+ if (!this.tabs.has(tabId)) return false;
639
+ this._tabGroup.set(tabId, groupId || tabGroup.HUMAN_GROUP);
640
+ return true;
641
+ }
642
+
643
+ bindSessionTab(sessionId, tabId) {
644
+ if (!sessionId) return;
645
+ if (tabId === undefined || tabId === null) this._sessionTab.delete(sessionId);
646
+ else this._sessionTab.set(sessionId, tabId);
647
+ }
648
+
649
+ sessionTabOf(sessionId) {
650
+ if (!sessionId) return null;
651
+ const t = this._sessionTab.get(sessionId);
652
+ return t === undefined ? null : t;
653
+ }
654
+
655
+ /**
656
+ * 这次调用操作哪个标签页。判据只有 shared/tab_route.cjs 一处,这里只把
657
+ * "当前有哪些标签页"和"人眼看的是哪个"喂给它。
658
+ * 返回 {tab, source, error?}:error 存在时调用方必须**报错**,不许就近挑一个。
659
+ */
660
+ resolveTargetTab({ explicit, sessionId } = {}) {
661
+ return tabRoute.resolveTarget({
662
+ explicit,
663
+ session: this.sessionTabOf(sessionId),
664
+ active: this.activeTab,
665
+ tabs: Array.from(this.tabs.keys()),
666
+ });
667
+ }
668
+
487
669
  unregisterClient(sessionId) {
488
670
  this._wsClients.delete(sessionId);
489
671
  this.subscriptions.delete(sessionId);
672
+ this._sessionTab.delete(sessionId);
490
673
  }
491
674
 
492
675
  _layoutAllViews(bounds) {
@@ -762,6 +945,10 @@ class PageManager {
762
945
  const tid = tabId !== undefined ? tabId : this.activeTab;
763
946
  const view = this._getView(tid);
764
947
  if (!view) return { ok: false, error: 'Tab not found' };
948
+ this.touchTab(tid);
949
+ // 一旦有人在这一页上导航过,它就不再是"还没人动过的启动页"了 —— 新标签页
950
+ // 也就不该再顶替它(否则 agent 每开一页都把上一页顶掉,等于一直抢视野)。
951
+ this._spendStartupPrivilege();
765
952
  const w = navWait.normalizeWaitUntil(opts.waitUntil);
766
953
  if (w.error) return { ok: false, error: w.error, wait_until_valid: navWait.LEVELS };
767
954
  const waitUntil = w.value;
@@ -1631,6 +1818,9 @@ class PageManager {
1631
1818
  async executeAction(action, target, params = {}, tabId) {
1632
1819
  const ms = actionDeadlineMs(action, params);
1633
1820
  const tid = tabId !== undefined ? tabId : this.activeTab;
1821
+ this.touchTab(tid);
1822
+ // 见 navigate 里的同一句:动过手的页面不再是"启动页"。
1823
+ this._spendStartupPrivilege();
1634
1824
  // 本次动作的起始时刻:用来判断"有没有对话框是在这一次动作里被应答的",
1635
1825
  // 并把结果写进回执(否则 agent 不知道点击中间弹过确认框)。
1636
1826
  const startedAt = Date.now();
@@ -1990,7 +2180,13 @@ class PageManager {
1990
2180
  this._openedTabs.delete(tid);
1991
2181
  const mine = pickOpenedTab(entry, startedAt);
1992
2182
  if (!mine) return null;
1993
- if (keep !== true) this.setActive(mine.id);
2183
+ // 「自动跟随」是**目标**跟过去,不是**视野**跟过去:
2184
+ // - 人在看这一页(opener 就是可见 tab)→ 照浏览器惯例把新标签切出来;
2185
+ // - opener 是后台页 → 只把调用方的目标挪过去(ws 层据回执 opened_tab 绑定),
2186
+ // 人眼前的页面一动不动。
2187
+ // 这条以前是无条件 setActive,等于"agent 点任何 target=_blank 的链接,
2188
+ // 用户的视野就被拽走一次"。
2189
+ if (keep !== true && tid === this.activeTab) this.setActive(mine.id);
1994
2190
  // 记录里的 url 是**建标签那一刻**的值。window.open("") 这条路上它永远是
1995
2191
  // 'about:blank' —— 真实地址由随后的 ai:window_open_nav 才载入。直接回
1996
2192
  // 'about:blank' 会让 agent 以为"打开了个空白页",这恰恰是当初那个 bug 的样子。
@@ -3416,7 +3612,16 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3416
3612
 
3417
3613
  // === Tab lifecycle ===
3418
3614
 
3419
- newTab(url = null) {
3615
+ /**
3616
+ * 新建标签页。
3617
+ *
3618
+ * @param {string|null} url
3619
+ * @param {{show?: boolean}} [opts] show=false 时**不把人眼前的页面顶掉**:
3620
+ * 视图保持不挂进窗口,但几何照算、脚本照跑、截图照出(后台标签页的完整能力
3621
+ * 有 `npm run background` 钉住)。默认 true 是给"人自己点的"和内部调用用的,
3622
+ * agent 侧由 ws_server 显式传 false(见 shared/tab_route.cjs 的说明)。
3623
+ */
3624
+ newTab(url = null, opts = {}) {
3420
3625
  const tabId = ++this.tabCounter;
3421
3626
  const self = this;
3422
3627
  const view = new BrowserView({
@@ -3440,6 +3645,14 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3440
3645
  },
3441
3646
  });
3442
3647
  this.tabs.set(tabId, view);
3648
+ // 归属在最早的这一刻定下来:后面所有涉及"组"的判断(上限、标签栏、关闭
3649
+ // 后清理空组)都读这一条,晚设一步就会出现"页已经在了、但没人认领"的窗口期。
3650
+ this._tabGroup.set(tabId, opts.group || tabGroup.HUMAN_GROUP);
3651
+ this._tabUsedAt.set(tabId, Date.now());
3652
+ // 每个标签页、从出生起就关掉后台节流。以前只在 setActive 里设,于是"从没
3653
+ // 被显示过"的标签页永远带着节流:定时器被拉长到 1s、rAF 停摆,站点的轮询/
3654
+ // 动画/自动保存全部变慢,而 agent 看起来只是"这一页有点慢"。
3655
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本没有这个方法 */ }
3443
3656
 
3444
3657
  // Tabs created after a subscribe should inherit the CDP domains already
3445
3658
  // active, so network_response / js_error keep flowing without re-subscribing.
@@ -3465,15 +3678,56 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3465
3678
 
3466
3679
  // Intercept window.open / new-window → create new tab instead
3467
3680
  view.webContents.setWindowOpenHandler(({ url: urlToOpen }) => {
3468
- const childId = self.newTab(urlToOpen);
3681
+ // 派生标签页跟**打开它的那一个**走:可见页里弹出来的照旧弹到人眼前
3682
+ // (浏览器惯例),后台页里弹出来的留在后台 —— agent 流程里登录/预览/
3683
+ // 下载这类弹窗极多,每弹一个就抢一次视野等于人没法用电脑。
3684
+ //
3685
+ // 归属也跟打开者走:agent 的页弹出来的子页仍然属于那个 agent,否则它会
3686
+ // 悄悄跑到"人的标签页"里,下次人清理自己的标签就把 agent 的流程删了。
3687
+ const parentGroup = self.groupOfTab(tabId);
3688
+ // 弹窗把组撑满时不能拒绝(站点的脚本在等这个窗口),只能牺牲一页:
3689
+ // 最久没用、不在人眼前、没有挂着对话框的那个。
3690
+ if (!self.canOpenInGroup(parentGroup).allowed) {
3691
+ const victim = self.pickEvictableInGroup(parentGroup, tabId);
3692
+ if (victim !== null) {
3693
+ const deadUrl = (self._getView(victim) || {}).webContents
3694
+ ? self._getView(victim).webContents.getURL() : '';
3695
+ self.evictions.push({ tab: victim, url: deadUrl, at: Date.now(), reason: 'group-full' });
3696
+ if (self.evictions.length > 20) self.evictions.shift();
3697
+ self.closeTab(victim);
3698
+ }
3699
+ }
3700
+ const childId = self.newTab(urlToOpen, {
3701
+ show: shouldShowChildTab({ openerIsVisible: tabId === self.activeTab }),
3702
+ group: parentGroup,
3703
+ });
3469
3704
  // Track which source tab opened a new tab so `executeAction` can report the
3470
3705
  // resulting tab and auto-follow it. Generic (any target=_blank / window.open).
3471
3706
  self._openedTabs.set(tabId, { id: childId, at: Date.now(), url: urlToOpen });
3472
3707
  return { action: 'deny' };
3473
3708
  });
3474
3709
 
3475
- // setActive handles addBrowserView + layout — don't add twice
3476
- this.setActive(tabId);
3710
+ // 可见与否由调用方决定,但**所有**标签页都挂进窗口、用 z 序决定谁在上面。
3711
+ //
3712
+ // 为什么不"不显示就不挂"(2026-10-28 实测):没挂进窗口的 BrowserView 根本
3713
+ // 没有合成表面 —— 读树/点击/输入/导航全都正常(那走的是渲染进程和 CDP 输入),
3714
+ // 但 ui.screenshot 拿到 0 字节、ui.paint_check 直接 no-frame。也就是说
3715
+ // "后台标签页"会变成一个**看不见也拍不到**的黑盒,而 agent 恰恰靠截图判断
3716
+ // "这一页到底画出什么了"。
3717
+ // 挂上去、把可见的那个置顶,就同时得到:真实表面(可截图/可自检)+ 人只看到
3718
+ // 他该看的那一页。
3719
+ const show = opts.show !== false;
3720
+ this._attachView(view);
3721
+ if (show || this.activeTab === null) {
3722
+ this.setActive(tabId);
3723
+ } else {
3724
+ this._layoutView(view);
3725
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本 */ }
3726
+ // 新挂的视图默认在最上层 —— 马上把"人该看的那一页"顶回去,否则后台新建
3727
+ // 的标签页会盖住用户正在看的页面(那就是"抢视野"的另一种形态)。
3728
+ const vis = this._getView(this.activeTab);
3729
+ if (vis) this._raiseView(vis);
3730
+ }
3477
3731
 
3478
3732
  // canvas 绘制记录必须在**首个真实导航之前**装好,否则页面早画完了什么都录不到。
3479
3733
  // 但它又必须在 setActive 之后:BrowserView 还没被加进窗口时,debugger 通道
@@ -3507,6 +3761,8 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3507
3761
  let signalReady = () => {};
3508
3762
  const ready = new Promise((resolve) => { signalReady = resolve; });
3509
3763
  this._windowOpenShimReady.set(tabId, ready);
3764
+ // 占位页地址:proceed 要用它判断"这一页还在不在等我"。
3765
+ const placeholderUrl = this._loadingPlaceholderUrl(targetUrl);
3510
3766
  let proceeded = false;
3511
3767
  const proceed = () => {
3512
3768
  if (proceeded) return;
@@ -3515,6 +3771,20 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3515
3771
  // 失败也放行:宁可这个 tab 没有垫片,也不能把它卡在占位页。
3516
3772
  signalReady();
3517
3773
  if (targetUrl && wc0 && !wc0.isDestroyed()) {
3774
+ // ⚠️ 延迟到达的 proceed **绝不能覆盖已经发生的真实导航**。
3775
+ //
3776
+ // 实测(2026-10-28,npm run background 在 v2.2.0 上同样复现):
3777
+ // 垫片安装偶尔会挂十几秒,这期间 agent 已经把这一页导航走了;
3778
+ // 等它终于 resolve,下面这行 loadURL(启动页) 又把页面盖回去 ——
3779
+ // 表现是"打开的是目标页,下一刻自己跳回首页",读到的树也成了首页的。
3780
+ // 判据只看一句:现在还在占位页上吗?不在就什么都不做。
3781
+ // 判据要宽松:空 / about:blank 都还算"还没开始",只有**明确导航
3782
+ // 到别处**(另一个 http/file 地址)才放弃 —— 收紧成"必须等于占位页"
3783
+ // 会在占位页刚发起、getURL() 还返回 about:blank 的那一瞬误判,
3784
+ // 结果是新标签页永远停在占位页(wrapper 套件当场 red)。
3785
+ const cur = wc0.getURL();
3786
+ const stillMine = !cur || cur === 'about:blank' || cur === placeholderUrl;
3787
+ if (!stillMine) return;
3518
3788
  // 让"正在加载"可被观测:白屏最贵的地方不是慢,是慢得无法和
3519
3789
  // "开错了"区分(见 listTabs 的 state 字段)。
3520
3790
  this._tabNavState.set(tabId, 'loading');
@@ -3543,7 +3813,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3543
3813
  // loading.html 只做展示(目标地址 + 转圈),不发请求不跳转,真实导航
3544
3814
  // 仍由上面的 proceed 发起。无目标 URL 的占位 tab(window.open("") 的
3545
3815
  // 老站模式)保持 about:blank:它本来就要停在这里等 location 赋值。
3546
- wc0.loadURL(this._loadingPlaceholderUrl(targetUrl)).catch(() => {});
3816
+ wc0.loadURL(placeholderUrl).catch(() => {});
3547
3817
  wc0.once('did-finish-load', () => { clearTimeout(guard); proceed(); });
3548
3818
  }
3549
3819
 
@@ -4055,6 +4325,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4055
4325
  _schedulePaintAudit(tabId, delay = 450) {
4056
4326
  if (!this._paintAuditEnabled) return;
4057
4327
  if (tabId !== this.activeTab) return;
4328
+ // 窗口不可见(隐藏/最小化/后台运行)时**不做**判定:这时"屏幕上有没有画出来"
4329
+ // 没有观测意义,取帧拿到的要不是空的、要不是陈旧的,而阶梯会据此 reload ——
4330
+ // 那是自己制造的一场重载风暴(后台 agent 每加载一页就刷一次)。
4331
+ // 人把窗口点开时由 ui.window{visible:true} 走 afterShowRelayout + 一次自检。
4332
+ if (!this._windowVisible()) return;
4058
4333
  const prev = this._paintTimers.get(tabId);
4059
4334
  if (prev) clearTimeout(prev);
4060
4335
  const t = setTimeout(() => {
@@ -4255,6 +4530,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4255
4530
  view.webContents.close();
4256
4531
  }
4257
4532
  this.tabs.delete(tabId);
4533
+ this._forgetTab(tabId);
4258
4534
  // window.open 垫片记账:这个 tab 若是某次 window.open 的目标,token 已
4259
4535
  // 失去意义(nav 到达也只会在上面打一行 warn),清掉防止 Map 无限增长。
4260
4536
  for (const [token, entry] of this._windowOpenTokens) {
@@ -4344,11 +4620,20 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4344
4620
  listTabs() {
4345
4621
  const list = [];
4346
4622
  for (const [id, view] of this.tabs) {
4623
+ const gid = this.groupOfTab(id);
4624
+ const g = this.groupMeta(gid);
4347
4625
  list.push({
4348
4626
  id,
4349
4627
  url: view.webContents.getURL(),
4350
4628
  title: view.webContents.getTitle(),
4351
4629
  active: id === this.activeTab,
4630
+ // 归属:'human' = 人的页,'agent:<session>' = 某个 agent 的工作区。
4631
+ // agent 靠它判断"这一页是不是我的",人靠它在标签栏归拢。
4632
+ group: gid,
4633
+ group_label: g.label,
4634
+ ...(g.color ? { group_color: g.color } : {}),
4635
+ ...(g.capped === true && g.limit ? { group_limit: g.limit } : {}),
4636
+ ...(g.kind === 'agent' ? { group_kind: 'agent' } : {}),
4352
4637
  // 'pending' = 停在占位页等脚本注入(真实导航还没发起)
4353
4638
  // 'loading' = 真实导航已发起、还没完成 —— 这时候页面多半还是空的,
4354
4639
  // 是"正在打开"而不是"开错了",等它,不要重试
@@ -4366,18 +4651,54 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4366
4651
  return list;
4367
4652
  }
4368
4653
 
4654
+ /**
4655
+ * 把视图挂进窗口(幂等)。所有标签页都挂着,靠 z 序决定谁可见 ——
4656
+ * 原因见 newTab 里的注释(没挂 = 没表面 = 截不到图)。
4657
+ */
4658
+ _attachView(view) {
4659
+ if (!view || !this.window) return;
4660
+ try {
4661
+ const attached = this.window.getBrowserViews ? this.window.getBrowserViews() : [];
4662
+ if (attached.indexOf(view) < 0) this.window.addBrowserView(view);
4663
+ } catch (_) { /* 窗口正在销毁 */ }
4664
+ }
4665
+
4666
+ /** 把某个视图提到最上层(= 人看到它)。老版本没有 setTopBrowserView 时退回 remove+add。 */
4667
+ _raiseView(view) {
4668
+ if (!view || !this.window) return;
4669
+ try {
4670
+ if (typeof this.window.setTopBrowserView === 'function') {
4671
+ this.window.setTopBrowserView(view);
4672
+ return;
4673
+ }
4674
+ } catch (_) { /* 落到下面的兼容路径 */ }
4675
+ try {
4676
+ this.window.removeBrowserView(view);
4677
+ this.window.addBrowserView(view);
4678
+ } catch (_) { /* 已销毁 */ }
4679
+ }
4680
+
4681
+ /** 「人眼前还是启动页」这个判断只对**没被动过**的启动页成立(见 shouldShowNewTab)。 */
4682
+ _spendStartupPrivilege() {
4683
+ this.startupTab = null;
4684
+ }
4685
+
4369
4686
  setActive(tabId) {
4370
4687
  if (!this.tabs.has(tabId)) return false;
4371
- // Remove all browser views from window, then re-add only the active one
4372
- for (const [id, view] of this.tabs) {
4373
- try { this.window.removeBrowserView(view); } catch(e) {}
4374
- }
4688
+ // 「人眼前还是启动页」这个特权是一次性的:一旦有人(人点了标签页、或 agent 显式
4689
+ // 把某一页顶到眼前)真正选过一次,之后新开的标签页就不再顶替它了 ——
4690
+ // 否则 agent 每开一页都会把上一页顶掉,等于永远在抢视野。
4691
+ if (this.startupTab !== null && tabId !== this.startupTab) this.startupTab = null;
4375
4692
  this.activeTab = tabId;
4376
4693
  // body / 记录淘汰要"先牺牲后台 tab",所以必须让它知道谁是活跃的。
4377
4694
  this.networkMonitor.setActiveTab(tabId);
4378
4695
  const view = this._getView(tabId);
4379
4696
  if (view) {
4380
- this.window.addBrowserView(view);
4697
+ // 只调 z 序:以前是"把所有视图 remove 掉、再 add 一个",那等于每次切标签页
4698
+ // 都让其余标签页失去合成表面(截图/自检全失效),而且 remove+add 本身会
4699
+ // 闪一帧白。
4700
+ this._attachView(view);
4701
+ this._raiseView(view);
4381
4702
  this._layoutView(view);
4382
4703
  this._focusWebContents(view);
4383
4704
  view.webContents.setBackgroundThrottling(false);
@@ -4437,6 +4758,116 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4437
4758
  *
4438
4759
  * 不传尺寸时纯读;传了就 setBounds + 立刻重排,再回读实际结果(不做乐观报告)。
4439
4760
  */
4761
+ /**
4762
+ * 窗口可见性 / 最小化(读 + 改)。`ui.window`。
4763
+ *
4764
+ * 为什么必须有(2026-10-28,用户要求"跟无头浏览器一样无感知运行"):
4765
+ * 在这之前没有任何一条路能让 agent 自己决定窗口显示与否 —— 窗口一旦被隐藏,
4766
+ * 下一次操作触发的 _focusWindow 又把它拽回来,于是"后台运行"根本不是一个
4767
+ * 稳定状态。现在可见性成为显式状态:
4768
+ * - 人:Dock 图标(app 'activate')/ 手动最小化,随时能点开;
4769
+ * - agent:ui.window {visible|minimized},AI_BROWSER_START_HIDDEN=1 启动即隐藏。
4770
+ *
4771
+ * 三条实现约束:
4772
+ * 1. **隐藏不影响任何页面能力**。视图仍挂在这个窗口上、几何照算,读树/动作/
4773
+ * 截图/上传/下载/对话框全部照旧(`npm run background` 里 20 条断言钉住)。
4774
+ * 2. **隐藏不抢焦点**。show 默认走 showInactive(),只有调用方显式 focus:true
4775
+ * 才把窗口带到前台 —— 这是"人主动要打开它"和"agent 偷偷弹窗"的区别。
4776
+ * 3. **恢复显示后要重排**。macOS/Windows 显示瞬间 content 尺寸与隐藏时不同,
4777
+ * 不重排就会出现"视图底部溢出"(Windows 上实测 26px,见 showInitialWindow)。
4778
+ */
4779
+ /** 窗口此刻是不是"人真的能看见"。判断绘制类问题时它是前置条件(见 _schedulePaintAudit)。 */
4780
+ _windowVisible() {
4781
+ try {
4782
+ if (!this.window) return false;
4783
+ if (this.window.isMinimized && this.window.isMinimized()) return false;
4784
+ if (this.window.isVisible && !this.window.isVisible()) return false;
4785
+ return true;
4786
+ } catch (_) {
4787
+ return false;
4788
+ }
4789
+ }
4790
+
4791
+ windowState() {
4792
+ const out = { ok: true };
4793
+ try {
4794
+ out.visible = !!(this.window.isVisible && this.window.isVisible());
4795
+ out.minimized = !!(this.window.isMinimized && this.window.isMinimized());
4796
+ out.focused = !!(this.window.isFocused && this.window.isFocused());
4797
+ out.bounds = this.window.getBounds();
4798
+ } catch (_) {
4799
+ return { ok: false, error: 'no-window' };
4800
+ }
4801
+ out.tabs = this.tabs.size;
4802
+ out.active_tab = this.activeTab;
4803
+ out.headless_ready = true; // 后台能力已可用;留给调用方判断的显式承诺
4804
+ return out;
4805
+ }
4806
+
4807
+ setWindowVisible(visible, opts = {}) {
4808
+ if (!this.window) return { ok: false, error: 'no-window' };
4809
+ try {
4810
+ if (visible) {
4811
+ if (this.window.isMinimized && this.window.isMinimized()) {
4812
+ try { this.window.restore(); } catch (_) { /* 已销毁 */ }
4813
+ }
4814
+ if (opts.focus === true && this.window.show) this.window.show();
4815
+ else if (typeof this.window.showInactive === 'function') this.window.showInactive();
4816
+ else if (this.window.show) this.window.show();
4817
+ this.afterShowRelayout();
4818
+ // 人刚刚把窗口点开:立刻自检一次"这一页到底画出来没有"。
4819
+ // 后台期间故意不判(见 _schedulePaintAudit),所以这里是唯一能兜住
4820
+ // "agent 在后台把页面搞白了、人一打开正好看到白屏"的时刻。
4821
+ this._schedulePaintAudit(this.activeTab, 700);
4822
+ } else {
4823
+ if (this.window.hide) this.window.hide();
4824
+ }
4825
+ } catch (e) {
4826
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4827
+ }
4828
+ return this.windowState();
4829
+ }
4830
+
4831
+ async setWindowMinimized(min) {
4832
+ if (!this.window) return { ok: false, error: 'no-window' };
4833
+ try {
4834
+ if (min) {
4835
+ if (this.window.minimize) this.window.minimize();
4836
+ } else {
4837
+ if (this.window.restore) this.window.restore();
4838
+ this.afterShowRelayout();
4839
+ }
4840
+ } catch (e) {
4841
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4842
+ }
4843
+ // macOS 的 miniaturize 是带动画的:isMinimized() 在动画结束前仍返回 false,
4844
+ // 当场回读会告诉调用方"没最小化"(实测踩到)。等动画走完再报,回执才是真的。
4845
+ await new Promise((r) => setTimeout(r, 280));
4846
+ return this.windowState();
4847
+ }
4848
+
4849
+ /**
4850
+ * 显示之后补几次重排。Windows 上 show() 之后原生边框才生效,content 高度会变
4851
+ * 而外框不变 → 不触发 resize → 视图按显示前的尺寸布局,底部溢出(实测 26px)。
4852
+ * 与 index.js 的 showInitialWindow 同一套理由,三次是为了覆盖边框真正应用的时刻。
4853
+ */
4854
+ afterShowRelayout() {
4855
+ const relayout = () => {
4856
+ try {
4857
+ for (const [id, v] of this.tabs) {
4858
+ if (id === this.activeTab) this._layoutView(v);
4859
+ }
4860
+ const v = this._getView(this.activeTab);
4861
+ if (v && v.webContents && !v.webContents.isDestroyed()) v.webContents.invalidate();
4862
+ } catch (_) { /* 窗口/视图已销毁 */ }
4863
+ };
4864
+ relayout();
4865
+ const t1 = setTimeout(relayout, 150);
4866
+ const t2 = setTimeout(relayout, 450);
4867
+ if (t1.unref) t1.unref();
4868
+ if (t2.unref) t2.unref();
4869
+ }
4870
+
4440
4871
  windowBounds(next) {
4441
4872
  const snapshot = () => {
4442
4873
  const out = { ok: true };
@@ -4660,37 +5091,29 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4660
5091
  * 拽到最前,等于人完全没法用电脑。
4661
5092
  *
4662
5093
  * AI_BROWSER_FOCUS:
4663
- * auto (默认) 只在窗口被最小化/隐藏时恢复可见,**不** moveTop、**不** focus。
4664
- * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
4665
- * 非前台时依然生效,加上已有的 disable-backgrounding-occluded-windows /
4666
- * disable-renderer-backgrounding / disable-background-timer-throttling,
4667
- * 后台窗口不会被降频或丢事件。
5094
+ * auto (默认) **完全不碰窗口状态**:不 show、不 moveTop、不 focus。
5095
+ * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
5096
+ * 非前台、最小化、甚至隐藏时依然生效(加上已有的
5097
+ * disable-backgrounding-occluded-windows / disable-renderer-backgrounding /
5098
+ * disable-background-timer-throttling,后台窗口不会被降频或丢事件)。
5099
+ * 这是"无头式运行"的前提:窗口隐藏必须是**稳定状态**,而不是
5100
+ * "下一次操作就弹回来"。
4668
5101
  * always 旧行为:每次都 show + moveTop + focus(需要抢焦点时用)。
4669
- * never 完全不碰窗口状态。
5102
+ * never 与 auto 相同(保留这个名字是为了兼容老配置)。
5103
+ *
5104
+ * ⚠️ 2026-10-28 之前 auto 会"窗口被最小化/隐藏就 restore + showInactive",
5105
+ * 依据是当时的产品不变量"窗口必须真实可见"。多 agent 并用之后这条不变量反过来
5106
+ * 咬人:agent 每操作一次,隐藏的窗口就自己爬出来一次 —— 人在用电脑,窗口在
5107
+ * 后台不停弹。现在改成:**窗口可见性只由人(Dock/activate)和显式 ui.window 决定**。
4670
5108
  */
4671
5109
  _focusWindow(view) {
4672
5110
  const policy = String(process.env.AI_BROWSER_FOCUS || 'auto').toLowerCase();
4673
- if (policy === 'never') return;
5111
+ if (policy !== 'always') return;
4674
5112
  try {
4675
- if (policy === 'always') {
4676
- if (this.window.show) this.window.show();
4677
- if (this.window.moveTop) this.window.moveTop();
4678
- if (this.window.focus) this.window.focus();
4679
- if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4680
- return;
4681
- }
4682
- // auto:产品承诺"窗口真实可见、人可随时介入",所以被最小化/隐藏时要恢复可见;
4683
- // 但不主动抢到最前 —— 人可以继续用别的窗口,需要时自己点过来。
4684
- // 用 showInactive(),语义才前后一致:auto 分支**从不**夺走键盘焦点。
4685
- const hidden = (this.window.isVisible && !this.window.isVisible()) ||
4686
- (this.window.isMinimized && this.window.isMinimized());
4687
- if (hidden) {
4688
- if (this.window.isMinimized && this.window.isMinimized() && this.window.restore) {
4689
- try { this.window.restore(); } catch (e) { /* 已销毁 */ }
4690
- }
4691
- if (typeof this.window.showInactive === 'function') this.window.showInactive();
4692
- else if (this.window.show) this.window.show();
4693
- }
5113
+ if (this.window.show) this.window.show();
5114
+ if (this.window.moveTop) this.window.moveTop();
5115
+ if (this.window.focus) this.window.focus();
5116
+ if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4694
5117
  } catch (e) { /* 窗口已销毁等情况,忽略 */ }
4695
5118
  }
4696
5119