@glittering0717/ai-browser 2.1.20 → 2.2.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.
@@ -1,7 +1,7 @@
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 } from 'electron';
4
+ import { ipcMain, BrowserView, nativeImage, webContents } from 'electron';
5
5
  import path from 'node:path';
6
6
  import fs from 'node:fs';
7
7
  import { fileURLToPath } from 'node:url';
@@ -35,6 +35,13 @@ import blankPage from '../shared/blank_page.cjs';
35
35
  import { diffValues, previewOf, safeByteLength, DEFAULT_SNAPSHOT_JS, DIFF_MAX_ENTRIES, evictOldest } from './snapshot_diff.js';
36
36
  import { withDeadline, actionDeadlineMs } from '../shared/deadline.js';
37
37
  import { DownloadMonitor } from './download_monitor.js';
38
+ // 「这条主框架响应该显示还是该下载」的判据与接线(见 shared/media_doc.cjs 顶部:
39
+ // 2026-10-27 用户报"点证书下载 → 卡在正在打开… + 一坨 png URL")。
40
+ import mediaDoc from '../shared/media_doc.cjs';
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';
38
45
  import { probeCapabilities } from './capability_probe.js';
39
46
  import valueContract from '../shared/value_contract.cjs';
40
47
  // 输入成功与否的判定口径(纯函数,独立模块便于单测)。详见文件内注释:
@@ -182,6 +189,10 @@ class PageManager {
182
189
  this.window = browserWindow;
183
190
  this.tabs = new Map(); // tabId -> BrowserView
184
191
  this.activeTab = null;
192
+ // 启动时那一个标签页。它存在的唯一用途是判断"人眼前这一页是不是还没人动过":
193
+ // 是的话,agent 开的第一个标签页可以直接顶上去(否则用户会盯着百度首页,
194
+ // 以为 agent 什么都没干)。见 shared/tab_route.cjs 的 shouldShowNewTab。
195
+ this.startupTab = null;
185
196
  this.tabCounter = 0;
186
197
  // 窗口首次显示时的那一刻状态(tab / body_len / ready_state)。
187
198
  // 白屏类缺陷的根因是"窗口显示了但渲染器还没画出第一帧",而这只能从窗口侧
@@ -192,6 +203,13 @@ class PageManager {
192
203
  this._pendingRequests = new Map();
193
204
  this._requestId = 0;
194
205
  this._wsClients = new Map();
206
+ // sessionId -> tabId:**这个连接自己的工作标签页**。
207
+ //
208
+ // 为什么必须有(2026-10-27 多 agent 并用):默认目标以前是全局 activeTab,
209
+ // 也就是"人眼看的那一页"。多个 agent 同时干活时它立刻崩掉 —— A 开一个标签页,
210
+ // 所有人的默认目标都变成它;B 说"点提交",点在 A 的页面上。判据与优先级见
211
+ // shared/tab_route.cjs(explicit > session > active > first)。
212
+ this._sessionTab = new Map();
195
213
  this._openedTabs = new Map(); // sourceTabId -> { id, url } (new tab opened by window.open)
196
214
  this._windowOpenTokens = new Map(); // token -> { tabId, sourceTabId } (window.open shim, preload bridge.cjs)
197
215
  this._windowOpenShimTabs = new Set(); // 已注入 window.open 垫片的 tabId
@@ -249,8 +267,19 @@ class PageManager {
249
267
  // agent 点"导出 CSV"拿到 success,然后什么都没有,连错误都没有。
250
268
  this.downloadMonitor = new DownloadMonitor(null, {
251
269
  broadcast: (type, data) => this._broadcast(type, data),
270
+ // 下载一开始就要接手"为它而开的那个标签页",等 done 再处理的话,
271
+ // 用户会先盯着「正在打开…」看几秒(大文件是几分钟)—— 那正是要消灭的症状。
272
+ onStart: (rec, tabId) => this._onDownloadStarted(rec, tabId),
252
273
  });
253
274
  this.downloadMonitor._resolveTab = (wc) => this._tabIdOfWebContents(wc);
275
+ // 可渲染的主框架文档(图片/音视频/PDF)即使服务端挂了 attachment,也按内容
276
+ // 类型显示,而不是丢进下载目录 —— 判据与理由见 shared/media_doc.cjs。
277
+ this.mediaInline = new MediaInline({
278
+ resolveTab: (wcId) => {
279
+ try { return this._tabIdOfWebContents(webContents.fromId(wcId)); } catch (_) { return undefined; }
280
+ },
281
+ onMedia: (rec) => this._broadcast('media_doc', rec),
282
+ });
254
283
  this._setupPermissions();
255
284
  this._setupIPC();
256
285
  }
@@ -302,6 +331,11 @@ class PageManager {
302
331
  this._session = session;
303
332
  this.downloadMonitor.session = session;
304
333
  this.downloadMonitor.install();
334
+ // 与 will-download / 权限钩子同一条 session(见 config.viewPartition 的注释:
335
+ // 装错 session 的后果是"什么都没发生")。
336
+ // AI_BROWSER_MEDIA_INLINE=0 关掉它 → 回到"图片也被当文件下载"的旧行为,
337
+ // 用于二分"某站点的显示问题是不是这条钩子造成的"。
338
+ if (process.env.AI_BROWSER_MEDIA_INLINE !== '0') this.mediaInline.install(session);
305
339
  this._installPermissionHandler();
306
340
  }
307
341
 
@@ -464,9 +498,40 @@ class PageManager {
464
498
  this._wsClients.set(sessionId, ws);
465
499
  }
466
500
 
501
+ /**
502
+ * 把这个连接"自己的工作标签页"记下来。
503
+ * 断开连接时**不关页面**:agent 进程退出后,人可能正想看看它干到哪了。
504
+ */
505
+ bindSessionTab(sessionId, tabId) {
506
+ if (!sessionId) return;
507
+ if (tabId === undefined || tabId === null) this._sessionTab.delete(sessionId);
508
+ else this._sessionTab.set(sessionId, tabId);
509
+ }
510
+
511
+ sessionTabOf(sessionId) {
512
+ if (!sessionId) return null;
513
+ const t = this._sessionTab.get(sessionId);
514
+ return t === undefined ? null : t;
515
+ }
516
+
517
+ /**
518
+ * 这次调用操作哪个标签页。判据只有 shared/tab_route.cjs 一处,这里只把
519
+ * "当前有哪些标签页"和"人眼看的是哪个"喂给它。
520
+ * 返回 {tab, source, error?}:error 存在时调用方必须**报错**,不许就近挑一个。
521
+ */
522
+ resolveTargetTab({ explicit, sessionId } = {}) {
523
+ return tabRoute.resolveTarget({
524
+ explicit,
525
+ session: this.sessionTabOf(sessionId),
526
+ active: this.activeTab,
527
+ tabs: Array.from(this.tabs.keys()),
528
+ });
529
+ }
530
+
467
531
  unregisterClient(sessionId) {
468
532
  this._wsClients.delete(sessionId);
469
533
  this.subscriptions.delete(sessionId);
534
+ this._sessionTab.delete(sessionId);
470
535
  }
471
536
 
472
537
  _layoutAllViews(bounds) {
@@ -641,6 +706,87 @@ class PageManager {
641
706
  };
642
707
  }
643
708
 
709
+ /**
710
+ * 下载开始了 —— 如果"这个 tab 就是为它而开的",当场把它换成结果页。
711
+ *
712
+ * 事故现场(2026-10-27,沧州教师继续教育网"证书下载"):站点用新标签打开
713
+ * `.../xxx.png`,服务端带 `Content-Disposition: attachment`,于是 Electron
714
+ * 把它当下载 —— **导航永远不会提交**,那个标签页停在 loading.html 上:
715
+ * 一句「正在打开…」+ 一坨 URL,永远不变。文件其实已经落盘,但界面上
716
+ * 没有任何回执,人的判断只能是"卡住了"。
717
+ *
718
+ * 判据是"这个 tab 还停在占位页":说明它没有真正的页面可丢,接管它没有任何
719
+ * 代价。反过来,页面里点"导出 CSV"那种下载,tab 上是真实页面,绝不能动。
720
+ */
721
+ _onDownloadStarted(rec, tabId) {
722
+ try {
723
+ if (tabId === undefined || tabId === null || !rec) return;
724
+ const view = this.tabs.get(tabId);
725
+ if (!view || view.webContents.isDestroyed()) return;
726
+ const cur = view.webContents.getURL() || '';
727
+ if (!mediaDoc.isPlaceholderUrl(cur)) return;
728
+ // 让这条 will-download 先走完,再切页面:避免和刚刚被取消的导航抢加载。
729
+ setImmediate(() => {
730
+ try {
731
+ if (view.webContents.isDestroyed()) return;
732
+ if (!mediaDoc.isPlaceholderUrl(view.webContents.getURL() || '')) return;
733
+ this.showDownloadResult(tabId, rec);
734
+ } catch (_) { /* 结果页只是"有回执",失败不该影响下载本身 */ }
735
+ });
736
+ } catch (_) { /* 同上 */ }
737
+ }
738
+
739
+ /** 把一个 tab 换成"下载结果"页(文件名/大小/缩略图/打开/在 Finder 中显示)。 */
740
+ showDownloadResult(tabId, rec) {
741
+ const view = this.tabs.get(tabId);
742
+ if (!view || view.webContents.isDestroyed()) return false;
743
+ const q = new URLSearchParams();
744
+ q.set('id', rec.id || '');
745
+ q.set('name', rec.filename || 'download');
746
+ q.set('path', rec.path || '');
747
+ q.set('mime', rec.mime || '');
748
+ q.set('size', String(rec.total_bytes || 0));
749
+ q.set('url', rec.url || '');
750
+ const pagePath = path.join(__dirname, '../renderer/download.html');
751
+ const target = 'file://' + pagePath + '?' + q.toString();
752
+ view.webContents.loadURL(target).catch(() => {});
753
+ return true;
754
+ }
755
+
756
+ /**
757
+ * 工具条上的「下载」按钮:把当前页(一份被救回来的图片/视频/PDF)存到下载目录。
758
+ *
759
+ * 走 `downloadURL` 而不是自己 fetch:用的是同一个 session,站点的 Cookie /
760
+ * Referer / 临时签名全部照旧,也就不会出现"浏览器里能看、下载下来是 403 页面"。
761
+ */
762
+ downloadCurrent(tabId) {
763
+ const id = tabId === undefined || tabId === null ? this.activeTab : tabId;
764
+ const view = this.tabs.get(id);
765
+ if (!view || view.webContents.isDestroyed()) return { ok: false, error: 'no such tab' };
766
+ const cur = view.webContents.getURL() || '';
767
+ const rec = this.mediaInline.recordOf(id, cur);
768
+ const url = rec ? rec.url : cur;
769
+ if (!/^https?:/i.test(url)) return { ok: false, error: 'not an http(s) page: ' + url };
770
+ try {
771
+ view.webContents.downloadURL(url);
772
+ return { ok: true, tab: id, url, note: 'check ui.downloads / the toolbar receipt for the path' };
773
+ } catch (e) {
774
+ return { ok: false, error: String(e && e.message || e) };
775
+ }
776
+ }
777
+
778
+ /** 当前页是不是一份"被救回来的"可显示文档(要显示下载按钮)。 */
779
+ mediaDocOf(tabId) {
780
+ const id = tabId === undefined || tabId === null ? this.activeTab : tabId;
781
+ const view = this.tabs.get(id);
782
+ if (!view || view.webContents.isDestroyed()) return null;
783
+ try {
784
+ return this.mediaInline.recordOf(id, view.webContents.getURL() || '');
785
+ } catch (_) {
786
+ return null;
787
+ }
788
+ }
789
+
644
790
  _sendToView(tabId, channel, payload) {
645
791
  const view = this._getView(tabId);
646
792
  if (!view) return false;
@@ -661,6 +807,9 @@ class PageManager {
661
807
  const tid = tabId !== undefined ? tabId : this.activeTab;
662
808
  const view = this._getView(tid);
663
809
  if (!view) return { ok: false, error: 'Tab not found' };
810
+ // 一旦有人在这一页上导航过,它就不再是"还没人动过的启动页"了 —— 新标签页
811
+ // 也就不该再顶替它(否则 agent 每开一页都把上一页顶掉,等于一直抢视野)。
812
+ this._spendStartupPrivilege();
664
813
  const w = navWait.normalizeWaitUntil(opts.waitUntil);
665
814
  if (w.error) return { ok: false, error: w.error, wait_until_valid: navWait.LEVELS };
666
815
  const waitUntil = w.value;
@@ -1530,6 +1679,8 @@ class PageManager {
1530
1679
  async executeAction(action, target, params = {}, tabId) {
1531
1680
  const ms = actionDeadlineMs(action, params);
1532
1681
  const tid = tabId !== undefined ? tabId : this.activeTab;
1682
+ // 见 navigate 里的同一句:动过手的页面不再是"启动页"。
1683
+ this._spendStartupPrivilege();
1533
1684
  // 本次动作的起始时刻:用来判断"有没有对话框是在这一次动作里被应答的",
1534
1685
  // 并把结果写进回执(否则 agent 不知道点击中间弹过确认框)。
1535
1686
  const startedAt = Date.now();
@@ -1889,7 +2040,13 @@ class PageManager {
1889
2040
  this._openedTabs.delete(tid);
1890
2041
  const mine = pickOpenedTab(entry, startedAt);
1891
2042
  if (!mine) return null;
1892
- if (keep !== true) this.setActive(mine.id);
2043
+ // 「自动跟随」是**目标**跟过去,不是**视野**跟过去:
2044
+ // - 人在看这一页(opener 就是可见 tab)→ 照浏览器惯例把新标签切出来;
2045
+ // - opener 是后台页 → 只把调用方的目标挪过去(ws 层据回执 opened_tab 绑定),
2046
+ // 人眼前的页面一动不动。
2047
+ // 这条以前是无条件 setActive,等于"agent 点任何 target=_blank 的链接,
2048
+ // 用户的视野就被拽走一次"。
2049
+ if (keep !== true && tid === this.activeTab) this.setActive(mine.id);
1893
2050
  // 记录里的 url 是**建标签那一刻**的值。window.open("") 这条路上它永远是
1894
2051
  // 'about:blank' —— 真实地址由随后的 ai:window_open_nav 才载入。直接回
1895
2052
  // 'about:blank' 会让 agent 以为"打开了个空白页",这恰恰是当初那个 bug 的样子。
@@ -3315,7 +3472,16 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3315
3472
 
3316
3473
  // === Tab lifecycle ===
3317
3474
 
3318
- newTab(url = null) {
3475
+ /**
3476
+ * 新建标签页。
3477
+ *
3478
+ * @param {string|null} url
3479
+ * @param {{show?: boolean}} [opts] show=false 时**不把人眼前的页面顶掉**:
3480
+ * 视图保持不挂进窗口,但几何照算、脚本照跑、截图照出(后台标签页的完整能力
3481
+ * 有 `npm run background` 钉住)。默认 true 是给"人自己点的"和内部调用用的,
3482
+ * agent 侧由 ws_server 显式传 false(见 shared/tab_route.cjs 的说明)。
3483
+ */
3484
+ newTab(url = null, opts = {}) {
3319
3485
  const tabId = ++this.tabCounter;
3320
3486
  const self = this;
3321
3487
  const view = new BrowserView({
@@ -3339,6 +3505,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3339
3505
  },
3340
3506
  });
3341
3507
  this.tabs.set(tabId, view);
3508
+ // 每个标签页、从出生起就关掉后台节流。以前只在 setActive 里设,于是"从没
3509
+ // 被显示过"的标签页永远带着节流:定时器被拉长到 1s、rAF 停摆,站点的轮询/
3510
+ // 动画/自动保存全部变慢,而 agent 看起来只是"这一页有点慢"。
3511
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本没有这个方法 */ }
3342
3512
 
3343
3513
  // Tabs created after a subscribe should inherit the CDP domains already
3344
3514
  // active, so network_response / js_error keep flowing without re-subscribing.
@@ -3364,15 +3534,39 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3364
3534
 
3365
3535
  // Intercept window.open / new-window → create new tab instead
3366
3536
  view.webContents.setWindowOpenHandler(({ url: urlToOpen }) => {
3367
- const childId = self.newTab(urlToOpen);
3537
+ // 派生标签页跟**打开它的那一个**走:可见页里弹出来的照旧弹到人眼前
3538
+ // (浏览器惯例),后台页里弹出来的留在后台 —— agent 流程里登录/预览/
3539
+ // 下载这类弹窗极多,每弹一个就抢一次视野等于人没法用电脑。
3540
+ const childId = self.newTab(urlToOpen, {
3541
+ show: shouldShowChildTab({ openerIsVisible: tabId === self.activeTab }),
3542
+ });
3368
3543
  // Track which source tab opened a new tab so `executeAction` can report the
3369
3544
  // resulting tab and auto-follow it. Generic (any target=_blank / window.open).
3370
3545
  self._openedTabs.set(tabId, { id: childId, at: Date.now(), url: urlToOpen });
3371
3546
  return { action: 'deny' };
3372
3547
  });
3373
3548
 
3374
- // setActive handles addBrowserView + layout — don't add twice
3375
- this.setActive(tabId);
3549
+ // 可见与否由调用方决定,但**所有**标签页都挂进窗口、用 z 序决定谁在上面。
3550
+ //
3551
+ // 为什么不"不显示就不挂"(2026-10-28 实测):没挂进窗口的 BrowserView 根本
3552
+ // 没有合成表面 —— 读树/点击/输入/导航全都正常(那走的是渲染进程和 CDP 输入),
3553
+ // 但 ui.screenshot 拿到 0 字节、ui.paint_check 直接 no-frame。也就是说
3554
+ // "后台标签页"会变成一个**看不见也拍不到**的黑盒,而 agent 恰恰靠截图判断
3555
+ // "这一页到底画出什么了"。
3556
+ // 挂上去、把可见的那个置顶,就同时得到:真实表面(可截图/可自检)+ 人只看到
3557
+ // 他该看的那一页。
3558
+ const show = opts.show !== false;
3559
+ this._attachView(view);
3560
+ if (show || this.activeTab === null) {
3561
+ this.setActive(tabId);
3562
+ } else {
3563
+ this._layoutView(view);
3564
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本 */ }
3565
+ // 新挂的视图默认在最上层 —— 马上把"人该看的那一页"顶回去,否则后台新建
3566
+ // 的标签页会盖住用户正在看的页面(那就是"抢视野"的另一种形态)。
3567
+ const vis = this._getView(this.activeTab);
3568
+ if (vis) this._raiseView(vis);
3569
+ }
3376
3570
 
3377
3571
  // canvas 绘制记录必须在**首个真实导航之前**装好,否则页面早画完了什么都录不到。
3378
3572
  // 但它又必须在 setActive 之后:BrowserView 还没被加进窗口时,debugger 通道
@@ -3954,6 +4148,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3954
4148
  _schedulePaintAudit(tabId, delay = 450) {
3955
4149
  if (!this._paintAuditEnabled) return;
3956
4150
  if (tabId !== this.activeTab) return;
4151
+ // 窗口不可见(隐藏/最小化/后台运行)时**不做**判定:这时"屏幕上有没有画出来"
4152
+ // 没有观测意义,取帧拿到的要不是空的、要不是陈旧的,而阶梯会据此 reload ——
4153
+ // 那是自己制造的一场重载风暴(后台 agent 每加载一页就刷一次)。
4154
+ // 人把窗口点开时由 ui.window{visible:true} 走 afterShowRelayout + 一次自检。
4155
+ if (!this._windowVisible()) return;
3957
4156
  const prev = this._paintTimers.get(tabId);
3958
4157
  if (prev) clearTimeout(prev);
3959
4158
  const t = setTimeout(() => {
@@ -4211,6 +4410,9 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4211
4410
  // 同理,下载记录只对"这个 tab 还在"有意义。注意**只清记录,不删文件** ——
4212
4411
  // 文件是用户要的东西,删文件是另一个决定,不能藏在关 tab 里。
4213
4412
  this.downloadMonitor.clearTab(tabId);
4413
+ // tabId 会被复用,媒体文档记录跟着一起清 —— 否则新 tab 一打开就带着
4414
+ // 上一个 tab 的「下载」按钮状态(地址对不上时 recordOf 会兜住,但别依赖兜底)。
4415
+ if (this.mediaInline) this.mediaInline.forget(tabId);
4214
4416
  // 白屏自检 / 崩溃自救的 per-tab 状态。不清的话 tabId 会被新 tab 复用,
4215
4417
  // 新 tab 一开就继承上一任的"已经救过两步",白屏时直接被判定成 give-up。
4216
4418
  this._paintState.delete(tabId);
@@ -4262,18 +4464,54 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4262
4464
  return list;
4263
4465
  }
4264
4466
 
4467
+ /**
4468
+ * 把视图挂进窗口(幂等)。所有标签页都挂着,靠 z 序决定谁可见 ——
4469
+ * 原因见 newTab 里的注释(没挂 = 没表面 = 截不到图)。
4470
+ */
4471
+ _attachView(view) {
4472
+ if (!view || !this.window) return;
4473
+ try {
4474
+ const attached = this.window.getBrowserViews ? this.window.getBrowserViews() : [];
4475
+ if (attached.indexOf(view) < 0) this.window.addBrowserView(view);
4476
+ } catch (_) { /* 窗口正在销毁 */ }
4477
+ }
4478
+
4479
+ /** 把某个视图提到最上层(= 人看到它)。老版本没有 setTopBrowserView 时退回 remove+add。 */
4480
+ _raiseView(view) {
4481
+ if (!view || !this.window) return;
4482
+ try {
4483
+ if (typeof this.window.setTopBrowserView === 'function') {
4484
+ this.window.setTopBrowserView(view);
4485
+ return;
4486
+ }
4487
+ } catch (_) { /* 落到下面的兼容路径 */ }
4488
+ try {
4489
+ this.window.removeBrowserView(view);
4490
+ this.window.addBrowserView(view);
4491
+ } catch (_) { /* 已销毁 */ }
4492
+ }
4493
+
4494
+ /** 「人眼前还是启动页」这个判断只对**没被动过**的启动页成立(见 shouldShowNewTab)。 */
4495
+ _spendStartupPrivilege() {
4496
+ this.startupTab = null;
4497
+ }
4498
+
4265
4499
  setActive(tabId) {
4266
4500
  if (!this.tabs.has(tabId)) return false;
4267
- // Remove all browser views from window, then re-add only the active one
4268
- for (const [id, view] of this.tabs) {
4269
- try { this.window.removeBrowserView(view); } catch(e) {}
4270
- }
4501
+ // 「人眼前还是启动页」这个特权是一次性的:一旦有人(人点了标签页、或 agent 显式
4502
+ // 把某一页顶到眼前)真正选过一次,之后新开的标签页就不再顶替它了 ——
4503
+ // 否则 agent 每开一页都会把上一页顶掉,等于永远在抢视野。
4504
+ if (this.startupTab !== null && tabId !== this.startupTab) this.startupTab = null;
4271
4505
  this.activeTab = tabId;
4272
4506
  // body / 记录淘汰要"先牺牲后台 tab",所以必须让它知道谁是活跃的。
4273
4507
  this.networkMonitor.setActiveTab(tabId);
4274
4508
  const view = this._getView(tabId);
4275
4509
  if (view) {
4276
- this.window.addBrowserView(view);
4510
+ // 只调 z 序:以前是"把所有视图 remove 掉、再 add 一个",那等于每次切标签页
4511
+ // 都让其余标签页失去合成表面(截图/自检全失效),而且 remove+add 本身会
4512
+ // 闪一帧白。
4513
+ this._attachView(view);
4514
+ this._raiseView(view);
4277
4515
  this._layoutView(view);
4278
4516
  this._focusWebContents(view);
4279
4517
  view.webContents.setBackgroundThrottling(false);
@@ -4333,6 +4571,116 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4333
4571
  *
4334
4572
  * 不传尺寸时纯读;传了就 setBounds + 立刻重排,再回读实际结果(不做乐观报告)。
4335
4573
  */
4574
+ /**
4575
+ * 窗口可见性 / 最小化(读 + 改)。`ui.window`。
4576
+ *
4577
+ * 为什么必须有(2026-10-28,用户要求"跟无头浏览器一样无感知运行"):
4578
+ * 在这之前没有任何一条路能让 agent 自己决定窗口显示与否 —— 窗口一旦被隐藏,
4579
+ * 下一次操作触发的 _focusWindow 又把它拽回来,于是"后台运行"根本不是一个
4580
+ * 稳定状态。现在可见性成为显式状态:
4581
+ * - 人:Dock 图标(app 'activate')/ 手动最小化,随时能点开;
4582
+ * - agent:ui.window {visible|minimized},AI_BROWSER_START_HIDDEN=1 启动即隐藏。
4583
+ *
4584
+ * 三条实现约束:
4585
+ * 1. **隐藏不影响任何页面能力**。视图仍挂在这个窗口上、几何照算,读树/动作/
4586
+ * 截图/上传/下载/对话框全部照旧(`npm run background` 里 20 条断言钉住)。
4587
+ * 2. **隐藏不抢焦点**。show 默认走 showInactive(),只有调用方显式 focus:true
4588
+ * 才把窗口带到前台 —— 这是"人主动要打开它"和"agent 偷偷弹窗"的区别。
4589
+ * 3. **恢复显示后要重排**。macOS/Windows 显示瞬间 content 尺寸与隐藏时不同,
4590
+ * 不重排就会出现"视图底部溢出"(Windows 上实测 26px,见 showInitialWindow)。
4591
+ */
4592
+ /** 窗口此刻是不是"人真的能看见"。判断绘制类问题时它是前置条件(见 _schedulePaintAudit)。 */
4593
+ _windowVisible() {
4594
+ try {
4595
+ if (!this.window) return false;
4596
+ if (this.window.isMinimized && this.window.isMinimized()) return false;
4597
+ if (this.window.isVisible && !this.window.isVisible()) return false;
4598
+ return true;
4599
+ } catch (_) {
4600
+ return false;
4601
+ }
4602
+ }
4603
+
4604
+ windowState() {
4605
+ const out = { ok: true };
4606
+ try {
4607
+ out.visible = !!(this.window.isVisible && this.window.isVisible());
4608
+ out.minimized = !!(this.window.isMinimized && this.window.isMinimized());
4609
+ out.focused = !!(this.window.isFocused && this.window.isFocused());
4610
+ out.bounds = this.window.getBounds();
4611
+ } catch (_) {
4612
+ return { ok: false, error: 'no-window' };
4613
+ }
4614
+ out.tabs = this.tabs.size;
4615
+ out.active_tab = this.activeTab;
4616
+ out.headless_ready = true; // 后台能力已可用;留给调用方判断的显式承诺
4617
+ return out;
4618
+ }
4619
+
4620
+ setWindowVisible(visible, opts = {}) {
4621
+ if (!this.window) return { ok: false, error: 'no-window' };
4622
+ try {
4623
+ if (visible) {
4624
+ if (this.window.isMinimized && this.window.isMinimized()) {
4625
+ try { this.window.restore(); } catch (_) { /* 已销毁 */ }
4626
+ }
4627
+ if (opts.focus === true && this.window.show) this.window.show();
4628
+ else if (typeof this.window.showInactive === 'function') this.window.showInactive();
4629
+ else if (this.window.show) this.window.show();
4630
+ this.afterShowRelayout();
4631
+ // 人刚刚把窗口点开:立刻自检一次"这一页到底画出来没有"。
4632
+ // 后台期间故意不判(见 _schedulePaintAudit),所以这里是唯一能兜住
4633
+ // "agent 在后台把页面搞白了、人一打开正好看到白屏"的时刻。
4634
+ this._schedulePaintAudit(this.activeTab, 700);
4635
+ } else {
4636
+ if (this.window.hide) this.window.hide();
4637
+ }
4638
+ } catch (e) {
4639
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4640
+ }
4641
+ return this.windowState();
4642
+ }
4643
+
4644
+ async setWindowMinimized(min) {
4645
+ if (!this.window) return { ok: false, error: 'no-window' };
4646
+ try {
4647
+ if (min) {
4648
+ if (this.window.minimize) this.window.minimize();
4649
+ } else {
4650
+ if (this.window.restore) this.window.restore();
4651
+ this.afterShowRelayout();
4652
+ }
4653
+ } catch (e) {
4654
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4655
+ }
4656
+ // macOS 的 miniaturize 是带动画的:isMinimized() 在动画结束前仍返回 false,
4657
+ // 当场回读会告诉调用方"没最小化"(实测踩到)。等动画走完再报,回执才是真的。
4658
+ await new Promise((r) => setTimeout(r, 280));
4659
+ return this.windowState();
4660
+ }
4661
+
4662
+ /**
4663
+ * 显示之后补几次重排。Windows 上 show() 之后原生边框才生效,content 高度会变
4664
+ * 而外框不变 → 不触发 resize → 视图按显示前的尺寸布局,底部溢出(实测 26px)。
4665
+ * 与 index.js 的 showInitialWindow 同一套理由,三次是为了覆盖边框真正应用的时刻。
4666
+ */
4667
+ afterShowRelayout() {
4668
+ const relayout = () => {
4669
+ try {
4670
+ for (const [id, v] of this.tabs) {
4671
+ if (id === this.activeTab) this._layoutView(v);
4672
+ }
4673
+ const v = this._getView(this.activeTab);
4674
+ if (v && v.webContents && !v.webContents.isDestroyed()) v.webContents.invalidate();
4675
+ } catch (_) { /* 窗口/视图已销毁 */ }
4676
+ };
4677
+ relayout();
4678
+ const t1 = setTimeout(relayout, 150);
4679
+ const t2 = setTimeout(relayout, 450);
4680
+ if (t1.unref) t1.unref();
4681
+ if (t2.unref) t2.unref();
4682
+ }
4683
+
4336
4684
  windowBounds(next) {
4337
4685
  const snapshot = () => {
4338
4686
  const out = { ok: true };
@@ -4556,37 +4904,29 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4556
4904
  * 拽到最前,等于人完全没法用电脑。
4557
4905
  *
4558
4906
  * AI_BROWSER_FOCUS:
4559
- * auto (默认) 只在窗口被最小化/隐藏时恢复可见,**不** moveTop、**不** focus。
4560
- * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
4561
- * 非前台时依然生效,加上已有的 disable-backgrounding-occluded-windows /
4562
- * disable-renderer-backgrounding / disable-background-timer-throttling,
4563
- * 后台窗口不会被降频或丢事件。
4907
+ * auto (默认) **完全不碰窗口状态**:不 show、不 moveTop、不 focus。
4908
+ * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
4909
+ * 非前台、最小化、甚至隐藏时依然生效(加上已有的
4910
+ * disable-backgrounding-occluded-windows / disable-renderer-backgrounding /
4911
+ * disable-background-timer-throttling,后台窗口不会被降频或丢事件)。
4912
+ * 这是"无头式运行"的前提:窗口隐藏必须是**稳定状态**,而不是
4913
+ * "下一次操作就弹回来"。
4564
4914
  * always 旧行为:每次都 show + moveTop + focus(需要抢焦点时用)。
4565
- * never 完全不碰窗口状态。
4915
+ * never 与 auto 相同(保留这个名字是为了兼容老配置)。
4916
+ *
4917
+ * ⚠️ 2026-10-28 之前 auto 会"窗口被最小化/隐藏就 restore + showInactive",
4918
+ * 依据是当时的产品不变量"窗口必须真实可见"。多 agent 并用之后这条不变量反过来
4919
+ * 咬人:agent 每操作一次,隐藏的窗口就自己爬出来一次 —— 人在用电脑,窗口在
4920
+ * 后台不停弹。现在改成:**窗口可见性只由人(Dock/activate)和显式 ui.window 决定**。
4566
4921
  */
4567
4922
  _focusWindow(view) {
4568
4923
  const policy = String(process.env.AI_BROWSER_FOCUS || 'auto').toLowerCase();
4569
- if (policy === 'never') return;
4924
+ if (policy !== 'always') return;
4570
4925
  try {
4571
- if (policy === 'always') {
4572
- if (this.window.show) this.window.show();
4573
- if (this.window.moveTop) this.window.moveTop();
4574
- if (this.window.focus) this.window.focus();
4575
- if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4576
- return;
4577
- }
4578
- // auto:产品承诺"窗口真实可见、人可随时介入",所以被最小化/隐藏时要恢复可见;
4579
- // 但不主动抢到最前 —— 人可以继续用别的窗口,需要时自己点过来。
4580
- // 用 showInactive(),语义才前后一致:auto 分支**从不**夺走键盘焦点。
4581
- const hidden = (this.window.isVisible && !this.window.isVisible()) ||
4582
- (this.window.isMinimized && this.window.isMinimized());
4583
- if (hidden) {
4584
- if (this.window.isMinimized && this.window.isMinimized() && this.window.restore) {
4585
- try { this.window.restore(); } catch (e) { /* 已销毁 */ }
4586
- }
4587
- if (typeof this.window.showInactive === 'function') this.window.showInactive();
4588
- else if (this.window.show) this.window.show();
4589
- }
4926
+ if (this.window.show) this.window.show();
4927
+ if (this.window.moveTop) this.window.moveTop();
4928
+ if (this.window.focus) this.window.focus();
4929
+ if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4590
4930
  } catch (e) { /* 窗口已销毁等情况,忽略 */ }
4591
4931
  }
4592
4932
 
@@ -5120,6 +5460,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5120
5460
  // that are about to stop existing.
5121
5461
  this._snapshots.clear();
5122
5462
  this.downloadMonitor.clearAll();
5463
+ if (this.mediaInline) this.mediaInline.clearAll();
5123
5464
  for (const t of this._repaintTimers.values()) clearTimeout(t);
5124
5465
  this._repaintTimers.clear();
5125
5466
  for (const [id, view] of this.tabs) {