@glittering0717/ai-browser 2.5.2 → 2.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,21 @@
1
1
  // shared/config.js — Centralized runtime configuration, single source of truth.
2
2
  // Replaces hardcoded port 9223 / User-Agent / userData dir scattered across
3
- // main/. Each value respects an AI_BROWSER_* env override, with defaults that
4
- // are byte-identical to the previous hardcoded values (no behavior change by
5
- // default).
3
+ // main/. Each value respects an AI_BROWSER_* env override. The User-Agent is
4
+ // the one value that is NOT a fixed string any more: it is derived from the
5
+ // real platform + engine version so that it cannot contradict the client hints
6
+ // (see browser_identity.cjs).
6
7
  import path from 'node:path';
7
8
  import os from 'node:os';
9
+ import identityUtil from './browser_identity.cjs';
8
10
 
9
- const DEFAULT_UA =
10
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
11
+ // 身份(UA + UA-CH 元数据)按**真实运行时**算:平台取自 process.platform,
12
+ // 版本取自内核的 Chromium 版本。以前这里写死一条 macOS 的 Chrome/130,
13
+ // 而 Windows 上 navigator.platform / sec-ch-ua-platform / GPU 后端全是 Windows
14
+ // —— 自相矛盾的 UA 正是百度滑块和 Google "此浏览器可能不安全" 的头号证据。
15
+ // 完整推导与规矩见 shared/browser_identity.cjs 顶部。
16
+ const identity = identityUtil.buildIdentity(
17
+ process.env.AI_BROWSER_UA ? { userAgent: process.env.AI_BROWSER_UA } : {}
18
+ );
11
19
 
12
20
  export const config = {
13
21
  // WebSocket JSON-RPC server + MCP auto-launch probe port
@@ -19,8 +27,15 @@ export const config = {
19
27
  wsBindHost: process.env.AI_BROWSER_WS_HOST || '127.0.0.1',
20
28
  // Electron userData dir — session/cookie persistence survives restart
21
29
  userDataDir: process.env.AI_BROWSER_USER_DATA || path.join(os.homedir(), '.ai-browser'),
22
- // Spoofed UA to mask the automation fingerprint
23
- userAgent: process.env.AI_BROWSER_UA || DEFAULT_UA,
30
+ // 浏览器身份:UA 字符串 + 与之同源的 UA-CH 元数据(brands/platform/...)。
31
+ // 主进程用 CDP 把它们一起交给内核(Network.setUserAgentOverride),
32
+ // 这样 header、navigator.userAgent、navigator.userAgentData 三处永远一致。
33
+ identity,
34
+ // 身份层总开关。**只用于二分定位**:关掉之后内核用自己那份身份(UA 里带
35
+ // Electron/<ver>、brands 只有 Chromium),用来回答"这个站点的问题是不是
36
+ // 身份层造成的"。默认开:关掉它会同时丢掉"字段互相打脸"那几处修复。
37
+ identityEnabled: identityUtil.isEnabledByDefault(process.env.AI_BROWSER_IDENTITY),
38
+ userAgent: identity.userAgent,
24
39
  // Height of the in-app tab strip below the window title bar.
25
40
  // 36px = tab row, 38px = toolbar row (address bar + back/forward/reload/stop).
26
41
  tabBarHeight: 36 + 38,
@@ -0,0 +1,137 @@
1
+ // shared/input_routing.cjs — "这一页现在收不收得到 CDP 受信输入"的唯一判据。
2
+ //
3
+ // 为什么需要这一层(2026-11-03 逐杠杆实测):
4
+ // 窗口**从未显示过**时,页面自报 document.visibilityState:'visible' 的**唯一条件**是
5
+ // 那一页拿到过 CDP 的 `Emulation.setFocusEmulationEnabled{enabled:true}`;没拿到的页
6
+ // 一律 'hidden'。而 Chromium 对 hidden 文档**丢弃** CDP 受信输入 —— 事件发出去不报错、
7
+ // 不排队、也不改投给别人(实测:hidden 页收不到时,另一页的计数器一次都没涨,所以
8
+ // 不存在跨标签页串台),就是没了。
9
+ // 后果是最坏的那一种:ui.act click 依旧回 `{success:true, clicked_via:'cdp-click'}`
10
+ // —— 回执在说谎。agent 以为点过了,页面什么都没发生,只能重试或放弃。
11
+ // 产品平时把那一招用在每个活动页上(AI_BROWSER_FOCUS=auto 的本体:只伪造页面内焦点态,
12
+ // 不抢真实窗口焦点),所以"顶上去过的那一页"能收输入,其余不能 —— 这就是
13
+ // "多 agent 后台跑,第二个 agent 点不动"的真面目。
14
+ // ⚠️ 同一条实测顺手证伪了 _focusWindow 注释里那句"窗口隐藏时 CDP 输入照样生效":
15
+ // AI_BROWSER_FOCUS=never 时**连活动页都是 hidden**,模拟输入一样被丢 —— 那种组合下
16
+ // ui.act 结构性地做不到,只能如实失败,不能假装成功。
17
+ //
18
+ // 修法:动作之前先问页面一句"你现在 visible 吗"(一发极短的 CDP 读),收不到就给那一页
19
+ // 补上产品已经在用的那招,再问一次;还是收不到就**不发事件**、如实报错。
20
+ //
21
+ // 排除掉的几根(都是当场量出来的,不是猜的):
22
+ // setTopBrowserView(置顶) → visibility 照旧 hidden,事件照旧没
23
+ // webContents.focus()(原生焦点) → 同上
24
+ // removeBrowserView + addBrowserView → 同上
25
+ // setBounds(重排)/ setBackgroundThrottling(false) / invalidate → 同上
26
+ // Page.setWebLifecycleState{active} → 命令存在,但 visibility 不变
27
+ // Emulation.setPageVisibilityOverride → Chromium 130 没有这条命令('wasn't found')
28
+ // window.showInactive() → 有效(而且此后一直有效),代价是窗口真的出现在屏幕上
29
+ // Emulation.setFocusEmulationEnabled → ✅ 一次就翻转,点击与键入都落到位
30
+ //
31
+ // 判据放这里、执行放 page_manager,理由和 tab_audio / tab_group 一样:纯函数可以表驱动钉死,
32
+ // 而"什么时候该伪造、伪造了还不行怎么收场"正是会被写歪的那部分。
33
+
34
+ 'use strict';
35
+
36
+ /**
37
+ * 会走 CDP 受信输入的动作。
38
+ *
39
+ * 为什么按动作而不是"所有 ui.act":get_value / reload / repaint 是只读或控制类,
40
+ * 不需要页面在线;upload 走 DOM.setFileInputFiles(JS 路径,hidden 文档照样收);
41
+ * 而 JS 回退路径(preload 合成事件)本来就不受可见性影响 —— 它只在没有 debugger
42
+ * 会话时被用到,那时这一招也没法用。
43
+ */
44
+ const TRUSTED_INPUT_ACTIONS = [
45
+ 'click', 'hover', 'drag', 'wheel',
46
+ 'type', 'setContent', 'clear',
47
+ 'press', 'paste',
48
+ ];
49
+
50
+ const ENV_KEY = 'AI_BROWSER_INPUT_FOCUS';
51
+
52
+ function trustedInputAction(action) {
53
+ return TRUSTED_INPUT_ACTIONS.indexOf(String(action || '')) >= 0;
54
+ }
55
+
56
+ /**
57
+ * 要不要为收不到输入的那一页补一次焦点伪造(默认开,关掉:AI_BROWSER_INPUT_FOCUS=0)。
58
+ *
59
+ * 留开关不是"功能可以关",是**出事能退回如实报错**:这一招会让页面自认为在前台,
60
+ * 个别站点的"看不见就暂停"逻辑会因此继续跑。关掉之后行为并不回到"谎报成功"——
61
+ * 量到收不到就如实失败。形状沿用 AI_BROWSER_BG_MUTE。
62
+ */
63
+ function focusEnabled(env) {
64
+ const src = env || (typeof process !== 'undefined' ? process.env : {}) || {};
65
+ const raw = src[ENV_KEY];
66
+ if (raw === undefined || raw === null || raw === '') return true;
67
+ return !/^(0|false|off|no)$/i.test(String(raw).trim());
68
+ }
69
+
70
+ /**
71
+ * 这一页现在收不收得到受信输入。
72
+ *
73
+ * visibility 用**页面自己报的**那份,不用"是不是活动页""窗口可见与否"这类主进程侧的
74
+ * 推断 —— "活动页一定 visible"这一条就是这么被证伪的:AI_BROWSER_FOCUS=never 下
75
+ * 活动页同样 hidden,输入同样被丢。平台行为哪天变了,这里跟着事实走。
76
+ *
77
+ * 'prerender' / 'unloaded' 都不算能收输入 —— 只有 'visible' 放行。
78
+ * null(没量到 / 量不到)放行:观测能力不足不能反过来让动作失败,也不能拦住原本能成的
79
+ * 动作(没有 debugger 会话的旧路径就是这个情形)。
80
+ */
81
+ function isReceivable({ visibility } = {}) {
82
+ // 只有量到一个非空字符串才算"量到了"。null / undefined / '' / 非字符串一律当作没量到。
83
+ if (typeof visibility !== 'string' || visibility === '') return true;
84
+ return visibility === 'visible';
85
+ }
86
+
87
+ /** 要不要补那一招焦点伪造。开关关掉时不补,但下面的"如实失败"照旧生效。 */
88
+ function needsVisibilityFix({ action, visibility, enabled } = {}) {
89
+ if (!trustedInputAction(action)) return false;
90
+ if (enabled === undefined ? !focusEnabled() : !enabled) return false;
91
+ return !isReceivable({ visibility });
92
+ }
93
+
94
+ /**
95
+ * 发事件之前最后一次判要不要如实失败。
96
+ *
97
+ * 这一条**不看开关**:AI_BROWSER_INPUT_FOCUS=0 关掉的是"那一招",不是"别说谎"。
98
+ * 退路必须退到"如实报错",不能退到"假装成功"。
99
+ */
100
+ function shouldRefuse({ visibility } = {}) {
101
+ return !isReceivable({ visibility });
102
+ }
103
+
104
+ /**
105
+ * 仍然收不到 —— 如实失败,事件**不发**。
106
+ *
107
+ * 文案要写清三件事:什么都没发生(不是"部分生效")、为什么(这一页自认不在前台,
108
+ * Chromium 会丢弃模拟输入)、出路在哪(JS 路径,或者把窗口显示出来 / 换焦点策略)。
109
+ * 调用方熟悉的旧回执是 success:true,不写清"什么都没发生"它就会照着旧经验重试,
110
+ * 于是一次点击变成两次。
111
+ */
112
+ function notReceivableError({ action, tabId, visibility, focusPolicy, env }) {
113
+ const why = visibility === undefined || visibility === null
114
+ ? 'visibility unknown'
115
+ : `document.visibilityState=${visibility}`;
116
+ const tried = String(focusPolicy || '').toLowerCase() === 'never'
117
+ ? 'AI_BROWSER_FOCUS=never forbids page-focus emulation, so this window state cannot deliver simulated input at all'
118
+ : (focusEnabled(env)
119
+ ? 'page-focus emulation did not make it frontmost'
120
+ : 'page-focus emulation is off (AI_BROWSER_INPUT_FOCUS=0)');
121
+ return `action:${action} was NOT delivered to tab ${tabId} — that page reports ${why} `
122
+ + `and Chromium drops simulated input on such a page; ${tried}. `
123
+ + 'Nothing was clicked or typed, so do not retry blindly. '
124
+ + 'Use ui.evaluate for a JS-side action, or show the window (ui.window {visible:true}) '
125
+ + 'once — after that every tab stays reachable.';
126
+ }
127
+
128
+ module.exports = {
129
+ ENV_KEY,
130
+ TRUSTED_INPUT_ACTIONS,
131
+ trustedInputAction,
132
+ focusEnabled,
133
+ isReceivable,
134
+ needsVisibilityFix,
135
+ shouldRefuse,
136
+ notReceivableError,
137
+ };
@@ -0,0 +1,137 @@
1
+ // shared/popup_geometry.cjs — window.open 的窗口特性 → 我们的视图几何(纯函数)
2
+ //
3
+ // # 为什么需要这一层(2026-11-02)
4
+ //
5
+ // 站点写 `window.open(url, name, 'width=420,height=520,left=120,top=80')` 时,它请求的是
6
+ // **一个 420×520 的浮层**:登录框、支付二维码、选择器都这么写。本项目的模型里没有独立
7
+ // 窗口(setWindowOpenHandler 一律 deny,弹窗落成标签页),而以前这条请求里的几何信息
8
+ // **被整份丢掉**(handler 只解构了 url;页面侧垫片把 _features 参数接了却没用)。
9
+ // 于是弹窗长成整号的独立标签页 —— 表现就是用户看到的"弹窗页面是一片白/整屏换了一页",
10
+ // 而它本该只盖住父页面右下角那一块。
11
+ //
12
+ // 丢掉的不只是观感:弹窗页自己会读 `window.innerWidth`(登录框按它排版)、站点也会读
13
+ // `w.innerWidth` 来决定往下问多少字段 —— 给它整屏宽度,等于让它按不属于它的尺寸排版。
14
+ //
15
+ // # 判据照 Chrome,不自创
16
+ // · 只有**显式请求了尺寸**(width/height)或 `popup=yes|1` 才算弹窗;
17
+ // `noopener` / `noreferrer` / `_blank` 这些不是尺寸,Chrome 也照样开新标签页 ——
18
+ // 把它们当弹窗会让所有普通外链弹成小窗,那是另一种错。
19
+ // · 尺寸下限 100(Chrome 不允许弹窗小于此),上限就是我们能给的内容区。
20
+ // · left/top 缺省居中(Chrome 用级联偏移;我们只有一个窗口,居中更稳定也可复现)。
21
+ //
22
+ // 坐标约定:这里算出来的是 **BrowserView 的 content 坐标**(y 已经含标签栏高度),
23
+ // 调用方给 box = 内容区矩形,返回值可以直接交给 view.setBounds()。
24
+ // 夹取是幂等的:窗口缩放时对旧矩形再夹一次,只可能挪位置/缩尺寸,不会漂。
25
+
26
+ 'use strict';
27
+
28
+ // Chrome 的弹窗最小尺寸;低于此按此处理(站点写 width=50 多半是笔误,照给会看不见)。
29
+ const MIN_WIDTH = 100;
30
+ const MIN_HEIGHT = 100;
31
+ // 站点只给一个维度时的缺省。取"登录框"这个量级,而不是整屏 —— 整屏就等于没修。
32
+ const DEFAULT_WIDTH = 500;
33
+ const DEFAULT_HEIGHT = 600;
34
+
35
+ const TRUTHY = ['1', 'yes', 'true', 'y'];
36
+ const FALSY = ['0', 'no', 'false', 'n', ''];
37
+
38
+ /** 'width=420,height=520' | {width:'420',popup:true} → { width:'420', height:'520' }(键小写)。 */
39
+ function parseFeatures(input) {
40
+ const out = {};
41
+ if (!input) return out;
42
+ if (typeof input === 'object') {
43
+ for (const [k, v] of Object.entries(input)) {
44
+ if (v === undefined || v === null) continue;
45
+ out[String(k).trim().toLowerCase()] = v;
46
+ }
47
+ return out;
48
+ }
49
+ // 站点写的是特性串;分隔符 Chrome 允许 ',' 或 ';',两种都收。
50
+ if (typeof input !== 'string') return out; // 数字等杂类型不是特性,不许当成"裸开关名"
51
+ for (const pair of String(input).split(/[;,]/)) {
52
+ const s = pair.trim();
53
+ if (!s) continue;
54
+ const i = s.indexOf('=');
55
+ if (i < 0) { out[s.toLowerCase()] = true; continue; }
56
+ out[s.slice(0, i).trim().toLowerCase()] = s.slice(i + 1).trim();
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /** '420' | 420 | 'abc' → 数字或 null(NaN 不许当成 0,那会把弹窗塞到左上角)。 */
62
+ function num(v) {
63
+ if (typeof v === 'boolean') return null;
64
+ const n = Number(v);
65
+ return Number.isFinite(n) ? n : null;
66
+ }
67
+
68
+ /** 特性串里的开关值:'no'/0/undefined → false,'yes'/1/true → true。 */
69
+ function flag(v) {
70
+ if (v === true) return true;
71
+ if (v === undefined || v === null) return false;
72
+ return TRUTHY.includes(String(v).trim().toLowerCase());
73
+ }
74
+
75
+ /**
76
+ * 这一发是不是"请求一个弹窗"。
77
+ * 只看尺寸类特性 —— width/height 存在(且解得出数字)或 popup 为真。
78
+ */
79
+ function wantsPopup(input) {
80
+ const f = typeof input === 'string' || (input && typeof input === 'object') ? input : '';
81
+ const o = parseFeatures(f);
82
+ if (flag(o.popup)) return true;
83
+ return num(o.width) !== null || num(o.height) !== null;
84
+ }
85
+
86
+ const clamp = (v, lo, hi) => (hi < lo ? lo : Math.min(Math.max(v, lo), hi));
87
+
88
+ /**
89
+ * 把请求的几何折成内容区里的一个矩形。
90
+ * @param {object|string} input 特性串或特性对象
91
+ * @param {{x:number,y:number,width:number,height:number}} box 可用内容区(视图坐标系)
92
+ * @returns {{x:number,y:number,width:number,height:number}|null} null = 不该按弹窗处理
93
+ */
94
+ function popupRect(input, box) {
95
+ const b = box && typeof box === 'object' ? box : {};
96
+ const bw = num(b.width); const bh = num(b.height);
97
+ if (bw === null || bh === null || bw <= 0 || bh <= 0) return null;
98
+ if (!wantsPopup(input)) return null;
99
+ const ox = num(b.x) === null ? 0 : num(b.x);
100
+ const oy = num(b.y) === null ? 0 : num(b.y);
101
+
102
+ const f = parseFeatures(input);
103
+ // 上限就是内容区:请求比窗口还大的弹窗没有意义(真实浏览器也这么夹),
104
+ // 而且这里夹不住就会让弹窗自己带滚动条还盖住标签栏。
105
+ const w = clamp(num(f.width) === null ? DEFAULT_WIDTH : num(f.width), Math.min(MIN_WIDTH, bw), bw);
106
+ const h = clamp(num(f.height) === null ? DEFAULT_HEIGHT : num(f.height), Math.min(MIN_HEIGHT, bh), bh);
107
+ const left = num(f.left); const top = num(f.top);
108
+ // left/top 是"相对可用区左上角"的偏移(我们没有屏幕坐标这个概念,而弹窗压在父页面
109
+ // 上正是它在本模型里的正确形态)。负值不当成 0 悄悄吞掉,而是夹回可用区内。
110
+ const x = left === null ? ox + Math.round((bw - w) / 2) : clamp(ox + left, ox, ox + bw - w);
111
+ const y = top === null ? oy + Math.round((bh - h) / 2) : clamp(oy + top, oy, oy + bh - h);
112
+ return { x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h) };
113
+ }
114
+
115
+ /**
116
+ * 夹回新的可用区(窗口缩放 / 底部横幅出现时用)。不读特性,只吃已存的矩形。
117
+ * 幂等:同一对 (rect, box) 再夹一次结果不变;box 变大时**不**把弹窗放大回去
118
+ * —— 它请求的就是那个尺寸。
119
+ */
120
+ function clampRect(rect, box) {
121
+ const r = rect && typeof rect === 'object' ? rect : {};
122
+ const b = box && typeof box === 'object' ? box : {};
123
+ const bw = num(b.width); const bh = num(b.height);
124
+ if (bw === null || bh === null || bw <= 0 || bh <= 0) return null;
125
+ const ox = num(b.x) === null ? 0 : num(b.x);
126
+ const oy = num(b.y) === null ? 0 : num(b.y);
127
+ const w = clamp(num(r.width) === null ? bw : num(r.width), Math.min(MIN_WIDTH, bw), bw);
128
+ const h = clamp(num(r.height) === null ? bh : num(r.height), Math.min(MIN_HEIGHT, bh), bh);
129
+ const x = clamp(num(r.x) === null ? ox : num(r.x), ox, ox + bw - w);
130
+ const y = clamp(num(r.y) === null ? oy : num(r.y), oy, oy + bh - h);
131
+ return { x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h) };
132
+ }
133
+
134
+ module.exports = {
135
+ MIN_WIDTH, MIN_HEIGHT, DEFAULT_WIDTH, DEFAULT_HEIGHT,
136
+ parseFeatures, wantsPopup, popupRect, clampRect,
137
+ };
@@ -12,6 +12,19 @@ const DEFAULT_FORMAT = 'png';
12
12
  // 512KB base64 ≈ 684KB 原始字节。单次回执再大,WS 帧和模型上下文都吃不消。
13
13
  const MAX_DATA_URL_CHARS = 512 * 1024;
14
14
 
15
+ // 取帧档位(2026-11-02):
16
+ // surface —— webContents.capturePage():只把视图自己那一帧合成面拷一份,
17
+ // **不进渲染进程主线程**。
18
+ // cdp —— CDP Page.captureScreenshot(fromSurface:true):像素同样是 surface,
19
+ // 但这条命令本身要渲染进程主线程接单排队。
20
+ // auto —— 按「屏幕上现在是不是这一帧」排两档顺序,另一档兜底(默认,见 pickShotTiers)。
21
+ // 事故现场:百度、dumate 的 tab 上 `ui.screenshot` 各报
22
+ // `captureScreenshot timeout after 20000ms —— the page main thread is likely blocked`,
23
+ // 而屏幕上明明是一张正常画面:合成器攥着帧,只有"命令排队"这一步被脚本占死了。
24
+ // 见 SPEC「取帧两条铁律」第 2 条 —— 自检早就是 surface 优先,截图这条路当时没跟上。
25
+ const SHOT_SOURCES = ['auto', 'surface', 'cdp'];
26
+ const DEFAULT_SOURCE = 'auto';
27
+
15
28
  /**
16
29
  * 规范化截图参数。
17
30
  * @param {object} opts 调用方传入(可能缺项/错型)
@@ -92,9 +105,107 @@ function normalizeScreenshotOpts(opts) {
92
105
  out.clip = clip;
93
106
  }
94
107
 
108
+ // --- source(取帧档位;显式传是为了复现旧路径 / 强制只要其中一档)---
109
+ if (src.source != null) {
110
+ if (typeof src.source !== 'string' || !SHOT_SOURCES.includes(src.source)) {
111
+ return { ok: false, error: `source must be one of ${SHOT_SOURCES.join('/')} (got ${JSON.stringify(src.source)})` };
112
+ }
113
+ out.source = src.source;
114
+ } else {
115
+ out.source = DEFAULT_SOURCE;
116
+ }
117
+
95
118
  return { ok: true, opts: out };
96
119
  }
97
120
 
121
+ /**
122
+ * 这一发请求能不能用 surface 档(capturePage)拿帧。
123
+ *
124
+ * 判据不是"想不想快",是**只有整视图的那一帧才是等价的**:
125
+ * · fullPage —— captureBeyondViewport 要渲染进程给出视口外的布局,位图里没有;
126
+ * · clip —— CDP 的 clip 是文档坐标,capturePage 给的是"当前视口那一帧",
127
+ * 本地裁剪会把两个坐标系混成一个(宁可慢,不要静默给错区域);
128
+ * · webp —— nativeImage 只有 toPNG/toJPEG,没有 toWebP。
129
+ * 这三种继续走 CDP,也就继续受"主线程被占住会超时"约束 —— 它们本来就要渲染进程配合。
130
+ */
131
+ function canUseSurface(opts) {
132
+ const o = opts && typeof opts === 'object' ? opts : {};
133
+ if (o.fullPage === true) return false;
134
+ if (o.clip) return false;
135
+ if (o.format === 'webp') return false;
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * auto 档的顺序由"屏幕上现在是不是这一帧"决定,不是由"有没有兄弟压在它上面"决定。
141
+ *
142
+ * 分水岭换过一次(2026-11-03 探针实测):旧判据在**窗口不在屏幕上**时(hide /
143
+ * minimize)算出"没被盖住",于是让后台页先去排 CDP 那条 20s 的队。而那一格实测
144
+ * surface 档 57–107ms 就能给出视图自己的合成帧,CDP 只有**正在重绘**的页面才答
145
+ * (1.1–2.1s),静态页一直等到 deadline。也就是说旧判据在最该快的那一格里选了慢的。
146
+ *
147
+ * 只有**确定**屏幕上显示的就是这一页时,CDP 才优先:那一帧正在被合成,它是"用户
148
+ * 此刻看到的画面"的最准来源,还给得出 clip/fullPage 的坐标语义。
149
+ * 可见性问不到(null)也按 surface 先 —— 这里和布尔判据不同,不是"猜哪边更快":
150
+ * surface 档要么几十毫秒给帧、要么两三毫秒如实说没帧,两种都比先排 20s 的队便宜,
151
+ * 而 CDP 作为后一档一直都在,没丢掉任何一条路。
152
+ *
153
+ * @param {{source?:string, windowOnScreen?:boolean|null, isActive?:boolean}} st
154
+ * @returns {string[]} 'surface' / 'cdp' 的顺序
155
+ */
156
+ function pickShotTiers(st) {
157
+ const s = st && typeof st === 'object' ? st : {};
158
+ // 显式 source 就是点名单一档,不兜底:调用方要"只有 surface"或"只有 CDP"时,
159
+ // 替他换档等于给一张他没要的图。
160
+ if (s.source === 'surface') return ['surface'];
161
+ if (s.source === 'cdp') return ['cdp'];
162
+ return s.windowOnScreen === true && s.isActive === true ? ['cdp', 'surface'] : ['surface', 'cdp'];
163
+ }
164
+
165
+ /**
166
+ * 把每一档的失败原因拼成一句回执。
167
+ *
168
+ * 修的是"只有最后一档的原因能活下来":旧实现每档都往同一个 `lastError` 里写,
169
+ * 于是隐藏窗口里那一发(surface 2ms 没帧 + CDP 20s 超时)只回一句"这一页从来没画过",
170
+ * 真凶那句 `captureScreenshot timeout after 20000ms` 被覆盖掉,调用方既看不到白等的
171
+ * 20 秒,也分不清"根本没帧"和"有帧但取不到"。
172
+ *
173
+ * 每一档都带 `[tier]` 前缀:单档时前缀只是把话说明白,多档时它区分得开谁说的。
174
+ *
175
+ * @param {Array<{tier:string, reason:string}>} failures
176
+ * @returns {string}
177
+ */
178
+ function joinShotFailures(failures) {
179
+ const list = [];
180
+ for (const f of Array.isArray(failures) ? failures : []) {
181
+ if (!f || typeof f !== 'object') continue;
182
+ const msg = String(f.reason || '').trim();
183
+ if (msg) list.push(`[${f.tier || 'tier'}] ${msg}`);
184
+ }
185
+ if (!list.length) return 'screenshot failed — no tier produced a frame';
186
+ return list.join(' | ');
187
+ }
188
+
189
+ /**
190
+ * surface 档的尺寸回执:capturePage 给的是**设备像素**,而调用方按 CSS 像素
191
+ * 传坐标、也按 CSS 像素读回执(CDP 档的 meta 就是 CSS 像素)。视图的 bounds
192
+ * 恰等于这一页的视口(BrowserView 的边界就是它的可视区),所以:
193
+ * CSS 尺寸 = 视图 bounds,dpr = 位图宽 / bounds 宽。
194
+ * 这样主线程被占死、连 devicePixelRatio 都 evaluate 不出来的页面,
195
+ * 回执仍然带得齐 width/height/device_pixel_ratio —— 不必为了这两个数再去排队。
196
+ */
197
+ function surfaceMeta(px, bounds) {
198
+ const p = px && typeof px === 'object' ? px : {};
199
+ const b = bounds && typeof bounds === 'object' ? bounds : {};
200
+ const cssW = Number(b.width);
201
+ const cssH = Number(b.height);
202
+ if (!Number.isFinite(cssW) || cssW <= 0 || !Number.isFinite(cssH) || cssH <= 0) return {};
203
+ const out = { width: Math.round(cssW), height: Math.round(cssH) };
204
+ const pxW = Number(p.width);
205
+ if (Number.isFinite(pxW) && pxW > 0) out.devicePixelRatio = Math.round((pxW / cssW) * 1000) / 1000;
206
+ return out;
207
+ }
208
+
98
209
  /**
99
210
  * 回执摘要:调用方拿到图之后最想知道的几件事,省得它再发一轮查询。
100
211
  * 敏感字段(密码框在场)单独标,因为 captureScreenshot 不会模糊它。
@@ -118,13 +229,27 @@ function describeShot(meta) {
118
229
  }
119
230
  if (m.hasVisiblePasswordInput === true) {
120
231
  out.warning = 'page has a visible password input — the screenshot may contain typed secrets';
232
+ } else if (m.passwordProbe === 'skipped') {
233
+ // surface 档不等渲染进程,密码框探测(一次 evaluate)就探不了。图照样给,
234
+ // 但"这张图里有没有密码"这件事必须如实说成未知,不能默默当成"没有"。
235
+ out.password_probe = 'skipped';
236
+ out.warning = 'password-input probe skipped (page main thread busy) — this frame may contain typed secrets';
121
237
  }
238
+ // 位图是哪一档取的:surface = 视图自己的合成帧(不进主线程),cdp = 渲染进程
239
+ // 配合截的。调用方据此判断"这张图和屏幕上看到的那一帧是不是同一个东西"。
240
+ if (typeof m.source === 'string') out.source = m.source;
122
241
  return out;
123
242
  }
124
243
 
125
244
  module.exports = {
126
245
  FORMATS,
246
+ SHOT_SOURCES,
247
+ DEFAULT_SOURCE,
127
248
  MAX_DATA_URL_CHARS,
128
249
  normalizeScreenshotOpts,
250
+ canUseSurface,
251
+ pickShotTiers,
252
+ joinShotFailures,
253
+ surfaceMeta,
129
254
  describeShot,
130
255
  };
@@ -0,0 +1,63 @@
1
+ // shared/tab_audio.cjs — 一个标签页的声音该不该出喇叭。
2
+ //
3
+ // 为什么需要这一条(2026-11-03 对照 Chromium 之后定下的第 1 项):本项目里所有标签页
4
+ // 都挂在同一个窗口上,"人看到哪一页"只由 z 序决定。**音频没有 z 序** —— 五页同时在放
5
+ // 声音,人就同时听见五路,而我们的标签条上没有喇叭图标可以逐个关。最难受的是 agent:
6
+ // 它在后台开的那几页(视频、直播、带背景音乐的营销页)人根本看不见,声音却一路响,
7
+ // 等于一台找不到静音键的收音机。这里只有纯函数,判据能被单测钉住(tests/test_tab_audio.js)。
8
+ //
9
+ // Chrome **不**自动静音后台页,因为它假设后台页是人自己开的、随时点得回去听。这个假设
10
+ // 在人的那一组成立,在 agent 那一组不成立 —— 人没开过那一页,也不知道是它在响。所以
11
+ // 规则只有两条,每条都有自己的出处,不要合成一条"非活跃就静音":
12
+ // 1) 人眼前那一页(activeTab)永远有声。人点开 agent 的页听一听,就该听见。
13
+ // 2) 人自己开的页(非 agent 组)延续 Chrome 行为:切走了也继续放 —— 一边看别的
14
+ // 一边听歌是真实用法,把它静音是拿 Chromium 没有的行为去改人的体验。
15
+ // 剩下的(agent 在后台开的、当前没人看着的页)静音。
16
+ 'use strict';
17
+
18
+ const { isAgentGroup } = require('./tab_group.cjs');
19
+
20
+ /** 关掉这条行为的开关:AI_BROWSER_BG_MUTE=0(默认开)。 */
21
+ const ENV_KEY = 'AI_BROWSER_BG_MUTE';
22
+
23
+ function bgMuteEnabled(env) {
24
+ const src = env || (typeof process !== 'undefined' ? process.env : {}) || {};
25
+ const raw = src[ENV_KEY];
26
+ if (raw === undefined || raw === null || raw === '') return true;
27
+ return !/^(0|false|off|no)$/i.test(String(raw).trim());
28
+ }
29
+
30
+ /**
31
+ * 这一页现在该不该静音。
32
+ *
33
+ * @param {{tabId?:*, activeTab?:*, group?:string, enabled?:boolean}} o
34
+ * group 是这一页的归属('human' / 'agent:<session>');enabled 不传时读环境变量。
35
+ * @returns {boolean}
36
+ */
37
+ function shouldMute(o) {
38
+ const t = o || {};
39
+ const enabled = t.enabled === undefined ? bgMuteEnabled() : t.enabled === true;
40
+ if (!enabled) return false;
41
+ if (t.tabId === undefined || t.tabId === null) return false;
42
+ // 1) 人眼前那一页永远有声。两边都空(还没有任何页)时不能算"同一个"。
43
+ if (t.activeTab !== undefined && t.activeTab !== null && t.tabId === t.activeTab) return false;
44
+ // 2) 人自己开的页照旧不静音(Chrome 行为)。
45
+ if (!isAgentGroup(t.group)) return false;
46
+ return true;
47
+ }
48
+
49
+ /**
50
+ * 回执里怎么写。静音要**说出来**:agent 截图看到视频在动却没声音,或者人反馈
51
+ * "这一页没声音",判据只能是这一条字段,不能靠猜。
52
+ * 不静音时不给字段(省 token,也不制造"每次都要判"的噪音)。
53
+ */
54
+ function muteField(muted) {
55
+ return muted ? { muted: true } : {};
56
+ }
57
+
58
+ module.exports = {
59
+ ENV_KEY,
60
+ bgMuteEnabled,
61
+ shouldMute,
62
+ muteField,
63
+ };
@@ -73,17 +73,41 @@ function decideOpen({ group, count, limit }) {
73
73
  };
74
74
  }
75
75
 
76
+ /** 哪些动作等于"在这一页留下了还没提交的内容"(草稿保护的置位/清除条件)。
77
+ * mark:把文字送进页面。clear:把文字清掉 —— 没有内容可丢了,保护跟着解除。
78
+ * 点击/键盘/滚动都不算:它们改的是页面状态,不是"别人写了一半的东西"。 */
79
+ const DRAFT_MARK = ['type', 'setContent', 'paste'];
80
+ const DRAFT_CLEAR = ['clear'];
81
+
82
+ /** @returns {'mark'|'clear'|null} 这个动作对草稿状态的影响。 */
83
+ function draftEffect(action) {
84
+ const a = String(action || '');
85
+ if (DRAFT_MARK.indexOf(a) >= 0) return 'mark';
86
+ if (DRAFT_CLEAR.indexOf(a) >= 0) return 'clear';
87
+ return null;
88
+ }
89
+
76
90
  /**
77
91
  * 弹窗(页面里 window.open / target=_blank)把组撑满时,牺牲哪一页。
78
92
  *
79
93
  * 为什么弹窗不能像 ui.new_tab 一样直接拒绝:这个弹窗是**页面脚本要的**,拒绝
80
94
  * 等于让站点的流程断在半路(OAuth 回调、打印预览、编辑器子窗口)。所以这里退一步,
81
- * 挑一页最不心疼的关掉。三条排除:
95
+ * 挑一页最不心疼的关掉。排除的条件按 Chrome Memory Saver 那张"不许丢弃"清单裁到
96
+ * 我们模型里真实存在的几条(我们的淘汰比 Chrome 的 discard 更狠 —— 整页关掉、
97
+ * 状态全没,所以保护必须更紧,不是更松):
82
98
  * - 正在被打开的那个(except,关了自己等于什么都没发生)
83
99
  * - 人眼前那一页(activeTab,人正在看)
84
100
  * - 有对话框挂着的(那是"等人点"的状态,关掉就把人的操作吞了)
101
+ * - **有没提交的输入的**(draft:填了一半的表单、写了一半的私信。关掉等于把
102
+ * 人或者 agent 几分钟的工作删了,而且 reload 回不去那个草稿)
103
+ * - **有进行中的下载的**(downloading:关掉标签页会连带取消那条下载)
104
+ * "正在放声音"这一条不在这里判,因为架构已经把它消化掉了:agent 的后台页从出生起
105
+ * 就被按住声音(shared/tab_audio.cjs),能出声的只有人眼前那一页(= activeTab,
106
+ * 上面已经排除)和人自己开的页(不归这个组管)。
85
107
  * 剩下的按"最久没用"排序(usedAt 由 page_manager 在导航/动作时刷新)。
86
108
  * 没有候选就返回 null,调用方只好允许超限 —— 宁可多一页,不要吞掉正在用的页。
109
+ * 这一条比 Chrome 更松(Chrome 会撑破上限),是有意的:超限只多占一份内存,
110
+ * 选错牺牲品丢的是别人正在做的事。
87
111
  */
88
112
  function pickEvictable({ tabs, except, activeTab }) {
89
113
  const list = Array.isArray(tabs) ? tabs : [];
@@ -91,7 +115,7 @@ function pickEvictable({ tabs, except, activeTab }) {
91
115
  for (const t of list) {
92
116
  if (!t || t.id === undefined || t.id === null) continue;
93
117
  if (t.id === except || t.id === activeTab) continue;
94
- if (t.dialog) continue;
118
+ if (t.dialog || t.draft || t.downloading) continue;
95
119
  const at = Number(t.usedAt) || 0;
96
120
  if (!best || at < best.usedAt) best = { id: t.id, usedAt: at, url: t.url || '' };
97
121
  }
@@ -108,5 +132,6 @@ module.exports = {
108
132
  limitFromEnv,
109
133
  colorFor,
110
134
  decideOpen,
135
+ draftEffect,
111
136
  pickEvictable,
112
137
  };
@@ -37,18 +37,23 @@ const PER_TAB = [
37
37
  { field: '_openedTabs' }, // 键 = 发起 window.open 的那个 tab
38
38
  { field: '_windowOpenShimTabs' },
39
39
  { field: '_windowOpenShimReady' },
40
+ { field: '_popupRects' }, // 这一页是浮层时它请求的矩形;漏清 = 新 tab 继承弹窗尺寸
41
+ { field: '_mutedTabs' }, // Set:被我们按住声音的页;漏清 = 新 tab 生下来就"没声音",而没人按住过它
42
+ { field: '_tabHasDraft' }, // 这一页有没提交的输入(淘汰保护);漏清 = 新 tab 永远挤不掉
40
43
  // ---- 导航状态机 ----
41
44
  { field: '_tabNavState' },
45
+ { field: '_pendingNavUrl' }, // 键 = tab,值 = 正在打开(还没 commit)的地址
46
+ { field: '_lastMainUrl' }, // 键 = tab,值 = 上一次主框架导航的 URL(记验证码墙现场用);漏清 = 新 tab 的"上一页"是上一任的
42
47
  // ---- 浏览器级对话框 ----
43
48
  { field: '_lastDialog' },
44
49
  { field: '_openDialogs' },
45
50
  { field: '_dialogWatched' },
51
+ { field: '_dialogWatchArming' }, // 正在补装 Page.enable 的 tab;漏清 = 新 tab 直接被当成"有人在装"
46
52
  // ---- 增量 diff / ref 纪元 ----
47
53
  { field: '_axDiffCache' },
48
54
  { field: '_refTrackers' },
49
55
  { field: '_failureGuard' },
50
- // ---- 重绘 / 白屏自检 / 崩溃自救 ----
51
- { field: '_repaintTimers', timers: true },
56
+ // ---- 白屏自检 / 崩溃自救 ----
52
57
  { field: '_paintState' },
53
58
  { field: '_paintSteps' },
54
59
  { field: '_paintTimers', timers: true },
@@ -59,6 +64,10 @@ const PER_TAB = [
59
64
  // 键是 `__aiCanvasReport_<tabId>_<rand>`,值是 tabId —— 每次重装 hook 都生成
60
65
  // 一个新名字,所以这里只能按**值**清,否则每次 configure 都留一条永不释放。
61
66
  { field: '_canvasBindings', byValue: true },
67
+ // ---- canvas hook 的"这一页显式点名过"记账 ----
68
+ { field: '_canvasHookForced' },
69
+ // ---- 身份(UA-CH 元数据)下发记账 ----
70
+ { field: '_identityApplied' },
62
71
  ];
63
72
 
64
73
  /**
@@ -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.5.2';
5
+ export const VERSION = '2.5.5';