@glittering0717/ai-browser 2.4.6 → 2.5.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.
- package/README.md +22 -6
- package/package.json +4 -2
- package/src/main/download_monitor.js +23 -1
- package/src/main/index.js +32 -10
- package/src/main/mcp_server.js +4 -3
- package/src/main/mcp_ws.js +14 -3
- package/src/main/page_manager.js +148 -71
- package/src/main/ws_server.js +149 -14
- package/src/preload/bridge.cjs +15 -24
- package/src/shared/eval_route.cjs +63 -0
- package/src/shared/ipc_guard.cjs +45 -0
- package/src/shared/tool_timeout.js +54 -0
- package/src/shared/tree_focus.cjs +58 -0
- package/src/shared/upload_guard.cjs +104 -0
- package/src/shared/version.js +1 -1
- package/src/shared/wrapper_hint.js +1 -1
- package/src/shared/protocol.js +0 -152
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
<img alt="MIT" src="https://img.shields.io/badge/license-MIT-blue.svg">
|
|
16
16
|
<img alt="Electron" src="https://img.shields.io/badge/built%20with-Electron%2033-9cf">
|
|
17
17
|
<img alt="Platforms" src="https://img.shields.io/badge/platforms-macOS%20%E2%80%A2%20Linux-blueviolet">
|
|
18
|
-
<img alt="Tests" src="https://img.shields.io/badge/tests-
|
|
18
|
+
<img alt="Tests" src="https://img.shields.io/badge/tests-1324%20unit%20%2B%20831%20e2e-2ea043">
|
|
19
19
|
<img alt="MCP" src="https://img.shields.io/badge/spec-MCP%20(stdio)-f5b23b">
|
|
20
20
|
</p>
|
|
21
21
|
|
|
@@ -32,17 +32,22 @@
|
|
|
32
32
|
</p>
|
|
33
33
|
|
|
34
34
|
**What it is.** An Electron app that exposes its tabs over two equivalent interfaces — an MCP server
|
|
35
|
-
(
|
|
35
|
+
(17 `browse_*` tools) and a raw WebSocket JSON-RPC API (`ws://localhost:9223`, methods `ui.*`). Your
|
|
36
36
|
agent navigates, reads a structured semantic tree (`role` / `label` / `value` / `states` / `actions`),
|
|
37
|
-
and clicks or types by `data-ai-id`.
|
|
38
|
-
|
|
37
|
+
and clicks or types by `data-ai-id`. **Reading never goes through a screenshot and there is no OCR** —
|
|
38
|
+
that's the point of the tree. `browse_screenshot` exists, but as a *diagnostic* for the cases the tree
|
|
39
|
+
can't see (overlays, canvas, mis-rendered layout), not as the read path.
|
|
39
40
|
|
|
40
41
|
**What it is not.** It is not headless. The window really opens, really renders, and stays interactive —
|
|
41
42
|
see [Letting a human step in](#letting-a-human-step-in). Nor does it "co-drive" with you: the hand-off
|
|
42
43
|
is a conversation between the agent and the user, not a browser API.
|
|
43
44
|
|
|
44
|
-
> **Security note.** The WebSocket server
|
|
45
|
-
>
|
|
45
|
+
> **Security note.** The WebSocket server binds loopback only and **refuses any handshake that carries
|
|
46
|
+
> an `Origin` header** — that's what a browser always sends, so a page running inside AI Browser (or
|
|
47
|
+
> any other browser) cannot drive the control plane, while Node/CLI/MCP clients (which send no
|
|
48
|
+
> `Origin`) work normally. There is still no token: a local process running as you can connect.
|
|
49
|
+
> Do not expose port 9223 beyond loopback.
|
|
50
|
+
> (`AI_BROWSER_WS_ALLOW_ORIGIN=1` disables the check — debug only, it re-opens the page → browser path.)
|
|
46
51
|
|
|
47
52
|
---
|
|
48
53
|
|
|
@@ -207,6 +212,9 @@ small surface, since every tool schema is injected into your agent's context on
|
|
|
207
212
|
| `browse_wait` | Poll until `button_enabled` / `modal_appeared` / `text_contains` / `url_contains`. |
|
|
208
213
|
| `browse_tabs` | Tabs: `list` / `new` / `close` / `switch` / `window`. `switch` = default; add `show:true`. `new` never steals the view unless `show:true`. |
|
|
209
214
|
| `browse_network` | Chrome-DevTools-style network inspection: `list` (filter by method / URL / status / type), `get` (request + response headers and bodies), `clear`, `configure`. |
|
|
215
|
+
| `browse_auth_state` | Login-state self-check for a tab: are we logged in, or bounced to a login wall. Cheap — no tree is built. |
|
|
216
|
+
| `browse_screenshot` | Diagnostic viewport/element capture (`png`/`jpeg`/`webp`, `clip`, `fullPage`). Not the read path — use it when the tree and the screen disagree. |
|
|
217
|
+
| `browse_errors` | Recent errors the browser recorded (crashes, failed navigations, RPC failures) with hints. Ask here when behaviour doesn't match the docs. |
|
|
210
218
|
| `browse_quit` | Shut the whole browser down and release the process. |
|
|
211
219
|
|
|
212
220
|
### What every act result already tells you: `effect_state`
|
|
@@ -485,6 +493,14 @@ MCP is a thin stdio adapter. Anything MCP can do is reachable directly over JSON
|
|
|
485
493
|
`ws://localhost:9223` from any language. Source of truth: the method switch in
|
|
486
494
|
[`src/main/ws_server.js`](src/main/ws_server.js).
|
|
487
495
|
|
|
496
|
+
Two things to know before you write a client:
|
|
497
|
+
|
|
498
|
+
- **Connections carrying an `Origin` header are closed with code 1008.** Browsers always send it;
|
|
499
|
+
Node's `WebSocket` and the `ws` package do not, so a normal script is unaffected. This is a
|
|
500
|
+
security boundary, not a bug — see the security note above.
|
|
501
|
+
- Method parameters are camelCase (`focusedOnly`, `timeout_ms`). MCP maps the snake_case tool
|
|
502
|
+
arguments onto them.
|
|
503
|
+
|
|
488
504
|
You do not have to write a client to do this. The CLI speaks the same protocol:
|
|
489
505
|
|
|
490
506
|
```bash
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glittering0717/ai-browser",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.1",
|
|
4
4
|
"description": "AI-native browser — renders pixels for humans, structured semantic-tree API for agents. No screenshots, no OCR, no coordinate guessing.",
|
|
5
5
|
"main": "src/main/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -96,7 +96,9 @@
|
|
|
96
96
|
"background": "node e2e/background_ws.cjs",
|
|
97
97
|
"icon:check": "node scripts/check_icon.cjs",
|
|
98
98
|
"icons": "env -u ELECTRON_RUN_AS_NODE node_modules/electron/dist/Electron.app/Contents/MacOS/Electron --no-sandbox --disable-gpu scripts/render_icon.cjs",
|
|
99
|
-
"icon": "node e2e/icon_ws.cjs"
|
|
99
|
+
"icon": "node e2e/icon_ws.cjs",
|
|
100
|
+
"security": "node e2e/security_ws.cjs",
|
|
101
|
+
"contract": "node e2e/contract_ws.cjs"
|
|
100
102
|
},
|
|
101
103
|
"dependencies": {
|
|
102
104
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
@@ -19,6 +19,26 @@ import { config } from '../shared/config.js';
|
|
|
19
19
|
|
|
20
20
|
const MAX_RECORDS_PER_TAB = 200;
|
|
21
21
|
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 同名文件唯一化(`report.csv` → `report (1).csv`)。
|
|
25
|
+
*
|
|
26
|
+
* 此前 savePath 直接拼 `dir/basename`,而 Electron 的 `setSavePath` 会**覆盖**
|
|
27
|
+
* 目标文件。同一站点连点两次导出,第一次的文件就没了 —— 回执里两条记录的
|
|
28
|
+
* path 一模一样,用户拿到的却是后一份内容(2026-10-31 复核)。
|
|
29
|
+
*/
|
|
30
|
+
function uniquePath(dir, name) {
|
|
31
|
+
const ext = path.extname(name);
|
|
32
|
+
const stem = ext ? name.slice(0, -ext.length) : name;
|
|
33
|
+
let candidate = path.join(dir, name);
|
|
34
|
+
let n = 1;
|
|
35
|
+
while (fs.existsSync(candidate) && n < 1000) {
|
|
36
|
+
candidate = path.join(dir, `${stem} (${n})${ext}`);
|
|
37
|
+
n += 1;
|
|
38
|
+
}
|
|
39
|
+
return candidate;
|
|
40
|
+
}
|
|
41
|
+
|
|
22
42
|
export class DownloadMonitor {
|
|
23
43
|
constructor(session, opts = {}) {
|
|
24
44
|
this.session = session;
|
|
@@ -50,7 +70,7 @@ export class DownloadMonitor {
|
|
|
50
70
|
const raw = String(item.getFilename() || 'download');
|
|
51
71
|
const safe = path.basename(raw).replace(/[\u0000-\u001f"*/:<>?\\|]/g, '_') || 'download';
|
|
52
72
|
const dir = path.join(this.baseDir, String(tabId));
|
|
53
|
-
const savePath =
|
|
73
|
+
const savePath = uniquePath(dir, safe);
|
|
54
74
|
|
|
55
75
|
try { fs.mkdirSync(dir, { recursive: true }); } catch (_) { /* 落盘失败在下面体现 */ }
|
|
56
76
|
item.setSavePath(savePath);
|
|
@@ -142,3 +162,5 @@ export class DownloadMonitor {
|
|
|
142
162
|
this._byTab.clear();
|
|
143
163
|
}
|
|
144
164
|
}
|
|
165
|
+
|
|
166
|
+
export { uniquePath };
|
package/src/main/index.js
CHANGED
|
@@ -451,13 +451,19 @@ if (!gpuDisabled && gpuPref !== 'on') {
|
|
|
451
451
|
}
|
|
452
452
|
if (gpuDisabled) app.disableHardwareAcceleration();
|
|
453
453
|
|
|
454
|
-
//
|
|
455
|
-
//
|
|
456
|
-
//
|
|
457
|
-
//
|
|
458
|
-
//
|
|
459
|
-
//
|
|
460
|
-
|
|
454
|
+
// Chromium 的 OS 级沙箱**默认关闭**:受限环境(例如 IDE 的集成终端 / TRAE 的
|
|
455
|
+
// shell)里 sandbox helper 拿不到它需要的权限,表现为 "sandbox initialization
|
|
456
|
+
// failed: Operation not permitted" 后立刻退出 —— 那是一个"装上就打不开"的
|
|
457
|
+
// 故障,比沙箱带来的纵深防御更急。
|
|
458
|
+
//
|
|
459
|
+
// 但它不再是**无法打开**的:`AI_BROWSER_SANDBOX=1` 就不加这个开关,让
|
|
460
|
+
// Chromium 用自己的沙箱。前提是启动环境允许 helper 工作(否则启动即退),
|
|
461
|
+
// 所以默认仍然关着 —— 这是权衡,不是"忘了"。
|
|
462
|
+
//
|
|
463
|
+
// 注:渲染器侧无论如何都没有 Node(contextIsolation:true + nodeIntegration:false),
|
|
464
|
+
// 这一位管的是"渲染进程被攻破之后还能不能碰到系统"。
|
|
465
|
+
const wantOsSandbox = process.env.AI_BROWSER_SANDBOX === '1';
|
|
466
|
+
if (!wantOsSandbox) app.commandLine.appendSwitch('no-sandbox');
|
|
461
467
|
|
|
462
468
|
// Keep renderers fully active even when the window is occluded (e.g. an IDE
|
|
463
469
|
// fullscreen window sits on top of the browser). By default Chromium
|
|
@@ -1424,10 +1430,26 @@ async function persistSessionCookies() {
|
|
|
1424
1430
|
// 每 10 个停 100ms,让每一批都有机会落盘。
|
|
1425
1431
|
if (i % 10 === 9) await new Promise((r) => setTimeout(r, 100));
|
|
1426
1432
|
}
|
|
1427
|
-
//
|
|
1433
|
+
// 最后强制落盘。`cookies.set()` resolve 只代表"已经排进 store":Chromium 的
|
|
1434
|
+
// cookie store 是 grouped commit,提交永远追不上(实测 86 个 set 全部"成功"
|
|
1435
|
+
// 但磁盘只剩 2 个,2026-10-19)。此前这里靠"固定睡 2 秒"碰运气,退出因此
|
|
1436
|
+
// 白等 2s 而且不保证成功;`flushStore()` 正是为此存在的原语:强制写盘并
|
|
1437
|
+
// 等它完成。老版本 Electron 没有这个 API 时退回原来的等待。
|
|
1428
1438
|
if (n > 0) {
|
|
1429
|
-
|
|
1430
|
-
|
|
1439
|
+
let flushed = false;
|
|
1440
|
+
try {
|
|
1441
|
+
if (ses.cookies && typeof ses.cookies.flushStore === 'function') {
|
|
1442
|
+
await ses.cookies.flushStore();
|
|
1443
|
+
flushed = true;
|
|
1444
|
+
}
|
|
1445
|
+
} catch (e) {
|
|
1446
|
+
console.error('[index] cookie flushStore failed:', e && e.message);
|
|
1447
|
+
}
|
|
1448
|
+
if (!flushed) await new Promise((r) => setTimeout(r, 2000));
|
|
1449
|
+
// 留一点余量给紧随其后的进程退出路径(不参与正确性,只是别让写盘和
|
|
1450
|
+
// 销毁撞在同一毫秒)。有了 flushStore 之后这 2s 不再需要。
|
|
1451
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
1452
|
+
console.log(`[index] persisted ${n} session cookies before quit (flushStore=${flushed})`);
|
|
1431
1453
|
}
|
|
1432
1454
|
} catch (e) {
|
|
1433
1455
|
console.error('[index] persistSessionCookies failed:', e && e.message);
|
package/src/main/mcp_server.js
CHANGED
|
@@ -17,6 +17,7 @@ import ensureMod from '../../scripts/ensure_running.cjs';
|
|
|
17
17
|
import { MCP_TOOLS } from './mcp_tools.js';
|
|
18
18
|
import { actParams, networkParams } from './mcp_args.js';
|
|
19
19
|
import { evaluateGuardError } from '../shared/guards.js';
|
|
20
|
+
import { timeoutForTool } from '../shared/tool_timeout.js';
|
|
20
21
|
// 截图体积上限(与 WS 侧共用同一把尺):超过就不把图塞进上下文。
|
|
21
22
|
import screenshotOpts from '../shared/screenshot_opts.cjs';
|
|
22
23
|
import { config, wsUrl } from '../shared/config.js';
|
|
@@ -102,7 +103,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
102
103
|
url: args.url,
|
|
103
104
|
tab: args.tab,
|
|
104
105
|
wait_until: args.wait_until || undefined,
|
|
105
|
-
});
|
|
106
|
+
}, { timeoutMs: timeoutForTool('browse_navigate', args) });
|
|
106
107
|
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
107
108
|
}
|
|
108
109
|
|
|
@@ -133,7 +134,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
133
134
|
target: args.target,
|
|
134
135
|
params: actParams(args),
|
|
135
136
|
tab: args.tab
|
|
136
|
-
});
|
|
137
|
+
}, { timeoutMs: timeoutForTool('browse_act', args) });
|
|
137
138
|
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
138
139
|
}
|
|
139
140
|
|
|
@@ -177,7 +178,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
177
178
|
text: args.text,
|
|
178
179
|
timeout_ms: args.timeout_ms,
|
|
179
180
|
tab: args.tab
|
|
180
|
-
});
|
|
181
|
+
}, { timeoutMs: timeoutForTool('browse_wait', args) });
|
|
181
182
|
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
182
183
|
}
|
|
183
184
|
|
package/src/main/mcp_ws.js
CHANGED
|
@@ -153,12 +153,23 @@ export function createWsClient({
|
|
|
153
153
|
|
|
154
154
|
// JSON-RPC call; resolves to the result, rejects on {error} / timeout /
|
|
155
155
|
// connection failure. Uses the shared connection via getWs().
|
|
156
|
-
|
|
156
|
+
//
|
|
157
|
+
// `opts.timeoutMs`:**每次调用**自己的 deadline。此前这里只有模块级的 15s,
|
|
158
|
+
// 于是 `browse_wait {timeout_ms:60000}` / `browse_act {timeout_ms:120000}`
|
|
159
|
+
// 在第 15 秒就被传输层掐掉,而服务端还在正常轮询 —— 调用方看到的是
|
|
160
|
+
// "WS timeout",会以为是服务端卡住。预算换算见 shared/tool_timeout.js。
|
|
161
|
+
function call(method, params = {}, opts = {}) {
|
|
162
|
+
const waitMs = Number(opts && opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : timeout;
|
|
157
163
|
return getWs().then((conn) => new Promise((resolve, reject) => {
|
|
158
164
|
const id = ++_rpcId;
|
|
165
|
+
const t0 = Date.now();
|
|
159
166
|
const timer = setTimeout(() => {
|
|
160
|
-
if (_pending.has(id)) {
|
|
161
|
-
|
|
167
|
+
if (_pending.has(id)) {
|
|
168
|
+
_pending.delete(id);
|
|
169
|
+
// 带上方法与已耗时:否则"15 秒还是 120 秒到期"只能靠猜。
|
|
170
|
+
reject(new Error(`WS timeout after ${Date.now() - t0}ms (method ${method})`));
|
|
171
|
+
}
|
|
172
|
+
}, waitMs);
|
|
162
173
|
_pending.set(id, (msg) => {
|
|
163
174
|
clearTimeout(timer);
|
|
164
175
|
if (msg.error) reject(new Error(msg.error.message || 'RPC error'));
|
package/src/main/page_manager.js
CHANGED
|
@@ -37,7 +37,12 @@ import blankPage from '../shared/blank_page.cjs';
|
|
|
37
37
|
// 见 shared/view_liveness.cjs 顶部(2026-10-30 白屏事故的 22 次崩溃)。
|
|
38
38
|
// .cjs 用默认导入(全项目约定,且 tests/test_imports.js 的静态分析只认 ESM export)。
|
|
39
39
|
import viewLiveness from '../shared/view_liveness.cjs';
|
|
40
|
+
import ipcGuard from '../shared/ipc_guard.cjs';
|
|
41
|
+
import treeFocus from '../shared/tree_focus.cjs';
|
|
42
|
+
import uploadGuard from '../shared/upload_guard.cjs';
|
|
43
|
+
import evalRoute from '../shared/eval_route.cjs';
|
|
40
44
|
const { isAlive, liveness } = viewLiveness;
|
|
45
|
+
const { acceptResult, eventFromTab } = ipcGuard;
|
|
41
46
|
// "关掉一个 tab 时哪些 per-tab 容器必须跟着消失"的唯一清单(纯函数)。
|
|
42
47
|
// 为什么是表而不是逐行 delete:这类清理历史上漏过两轮(Bug 5 补了 4 个字段,
|
|
43
48
|
// 2026-10-30 评估又查出 3 个漏网)。清单数据化 + 完整性闸门单测之后,
|
|
@@ -202,6 +207,10 @@ function keySpec(name, extraModifiers) {
|
|
|
202
207
|
class PageManager {
|
|
203
208
|
constructor(browserWindow) {
|
|
204
209
|
this.window = browserWindow;
|
|
210
|
+
// preload 的路径**必须在这里有默认值**:index.js 也会赋值(同一个路径),
|
|
211
|
+
// 但此前只有它赋值 —— 换个入口(单测、脚本、未来的新窗口)就 `undefined`,
|
|
212
|
+
// 而 `preload: undefined` 不报任何错,只表现为"页面读不到树、全超时"。
|
|
213
|
+
this._preloadPath = path.join(__dirname, '../preload/bridge.cjs');
|
|
205
214
|
this.tabs = new Map(); // tabId -> BrowserView
|
|
206
215
|
this.activeTab = null;
|
|
207
216
|
// 启动时那一个标签页。它存在的唯一用途是判断"人眼前这一页是不是还没人动过":
|
|
@@ -389,7 +398,9 @@ class PageManager {
|
|
|
389
398
|
ipcMain.on('ai:tree', (_event, payload) => {
|
|
390
399
|
const id = payload && payload.id;
|
|
391
400
|
const pending = (id !== undefined) ? self._pendingRequests.get(id) : null;
|
|
392
|
-
|
|
401
|
+
// 归属校验:谁的 tab 发的、什么通道。详见 shared/ipc_guard.cjs 顶部注释
|
|
402
|
+
// (页面曾经能通过 __ai_browser__.sendTree 撞号喂假树)。
|
|
403
|
+
if (acceptResult({ senderTab: self._tabIdForContents(_event.sender), pending, expectedKind: 'tree' })) {
|
|
393
404
|
self._pendingRequests.delete(id);
|
|
394
405
|
pending.resolve(payload);
|
|
395
406
|
}
|
|
@@ -398,7 +409,7 @@ class PageManager {
|
|
|
398
409
|
ipcMain.on('ai:action_result', (_event, result) => {
|
|
399
410
|
const id = result && result.id;
|
|
400
411
|
const pending = (id !== undefined) ? self._pendingRequests.get(id) : null;
|
|
401
|
-
if (pending) {
|
|
412
|
+
if (acceptResult({ senderTab: self._tabIdForContents(_event.sender), pending, expectedKind: 'action' })) {
|
|
402
413
|
self._pendingRequests.delete(id);
|
|
403
414
|
// Strip routing id from the payload before resolving.
|
|
404
415
|
const { id: _drop, ...clean } = result;
|
|
@@ -406,23 +417,16 @@ class PageManager {
|
|
|
406
417
|
}
|
|
407
418
|
});
|
|
408
419
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
if (pending) {
|
|
413
|
-
self._pendingRequests.delete(id);
|
|
414
|
-
if (result.error) pending.reject(new Error(result.error));
|
|
415
|
-
else pending.resolve(result.value);
|
|
416
|
-
}
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
ipcMain.on('ai:diff', (_event, changes) => {
|
|
420
|
-
this._broadcast('dom_change', { changes });
|
|
421
|
-
});
|
|
420
|
+
// ai:diff 已删除:它唯一的产出者是 preload 暴露给页面的 sendDiff,而那个
|
|
421
|
+
// 暴露面在 2026-10-31 被移除(页面可借它伪造 dom_change)。通道一并删掉,
|
|
422
|
+
// 免得留下"能收但没人发"的死路。
|
|
422
423
|
|
|
423
424
|
ipcMain.on('ai:event', (_event, payload) => {
|
|
424
|
-
// Tag events with
|
|
425
|
-
|
|
425
|
+
// Tag events with the tab that produced them. 归属不明的事件不许广播 ——
|
|
426
|
+
// 否则一个不该发事件的上下文也能把 agent 引到别的页面上。
|
|
427
|
+
const tab = eventFromTab({ senderTab: self._tabIdForContents(_event.sender) });
|
|
428
|
+
if (tab === null) return;
|
|
429
|
+
self._broadcast(payload.event, { ...(payload.data || {}), tab });
|
|
426
430
|
});
|
|
427
431
|
|
|
428
432
|
// === window.open 垫片的主进程侧(见 preload/bridge.cjs 的注释)===
|
|
@@ -596,11 +600,15 @@ class PageManager {
|
|
|
596
600
|
/** 组里还有哪些页(按 tabId 升序 = 创建顺序)。 */
|
|
597
601
|
tabsInGroup(groupId) {
|
|
598
602
|
const out = [];
|
|
599
|
-
for (const [id] of this.tabs) {
|
|
603
|
+
for (const [id, view] of this.tabs) {
|
|
600
604
|
if (this.groupOfTab(id) === groupId) {
|
|
605
|
+
// 存活判定收敛到 shared/view_liveness.cjs:视图被销毁后
|
|
606
|
+
// `view.webContents` 会变 undefined,裸解引用会击穿主进程
|
|
607
|
+
// (2026-10-30 白屏事故那一类)。这里填 null 而不是整条丢掉 ——
|
|
608
|
+
// 调用方要看到"这页还在、但已经读不到 URL"。
|
|
601
609
|
out.push({
|
|
602
610
|
id,
|
|
603
|
-
url:
|
|
611
|
+
url: isAlive(view) ? view.webContents.getURL() : null,
|
|
604
612
|
usedAt: this._tabUsedAt.get(id) || 0,
|
|
605
613
|
dialog: this._openDialogs.has(id) ? true : undefined,
|
|
606
614
|
});
|
|
@@ -705,18 +713,25 @@ class PageManager {
|
|
|
705
713
|
this._sessionTab.delete(sessionId);
|
|
706
714
|
}
|
|
707
715
|
|
|
708
|
-
|
|
716
|
+
/**
|
|
717
|
+
* 视图几何的**唯一**公式。此前 `_layoutAllViews` 与 `_layoutView` 各抄一份,
|
|
718
|
+
* 改一处忘另一处必然漏(历史上就漏过 inset:新建 tab 走的是 _layoutView)。
|
|
719
|
+
*/
|
|
720
|
+
_viewBounds(bounds) {
|
|
709
721
|
// `_bottomInset`:窗口底部被别的东西占掉的高度(目前只有主进程异常横幅)。
|
|
710
|
-
// 由 index.js 设置、这里统一扣减 —— 让每个"给视图定尺寸"的地方各自记住
|
|
711
|
-
// 这 34px 必然会漏掉一处(新建 tab 走的是 _layoutView,不是这里)。
|
|
712
722
|
const inset = this._bottomInset || 0;
|
|
723
|
+
return {
|
|
724
|
+
x: 0,
|
|
725
|
+
y: config.tabBarHeight,
|
|
726
|
+
width: bounds.width,
|
|
727
|
+
height: Math.max(0, bounds.height - config.tabBarHeight - inset),
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
_layoutAllViews(bounds) {
|
|
732
|
+
const rect = this._viewBounds(bounds);
|
|
713
733
|
for (const [id, view] of this.tabs) {
|
|
714
|
-
view.setBounds(
|
|
715
|
-
x: 0,
|
|
716
|
-
y: config.tabBarHeight,
|
|
717
|
-
width: bounds.width,
|
|
718
|
-
height: Math.max(0, bounds.height - config.tabBarHeight - inset),
|
|
719
|
-
});
|
|
734
|
+
view.setBounds(rect);
|
|
720
735
|
}
|
|
721
736
|
}
|
|
722
737
|
|
|
@@ -1144,14 +1159,20 @@ class PageManager {
|
|
|
1144
1159
|
return { ok: false, error: msg.slice(0, 300), waited_for: waitUntil };
|
|
1145
1160
|
}
|
|
1146
1161
|
|
|
1147
|
-
|
|
1162
|
+
/**
|
|
1163
|
+
* @param {boolean} focusedOnly 只返回焦点子树(见 shared/tree_focus.cjs)
|
|
1164
|
+
* @param {number} [tabId]
|
|
1165
|
+
* @param {{subset?: 'interactive'|'full'}} [opts] 剪枝选项。此前 subset/mode
|
|
1166
|
+
* 只在 ax:true 分支生效,默认读法**静默忽略** —— 调用方以为省了 token。
|
|
1167
|
+
*/
|
|
1168
|
+
async getTree(focusedOnly = false, tabId, opts = {}) {
|
|
1148
1169
|
const tid = tabId !== undefined ? tabId : this.activeTab;
|
|
1149
1170
|
const view = this._getView(tid);
|
|
1150
1171
|
if (!view) return { tree: null, context: null };
|
|
1151
1172
|
|
|
1152
1173
|
const res = await new Promise((resolve, reject) => {
|
|
1153
1174
|
const id = ++this._requestId;
|
|
1154
|
-
this._pendingRequests.set(id, { resolve, reject });
|
|
1175
|
+
this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'tree' });
|
|
1155
1176
|
view.webContents.send('ai:extract', { focusedOnly, id });
|
|
1156
1177
|
setTimeout(() => {
|
|
1157
1178
|
if (this._pendingRequests.has(id)) {
|
|
@@ -1167,7 +1188,7 @@ class PageManager {
|
|
|
1167
1188
|
// 此前这条通路只在 ax:true 下存在,而**没有任何地方告诉调用方 ax:true
|
|
1168
1189
|
// 的存在** —— B站图文编辑器(正文在 OOPIF 里)因此隐形了两小时,agent
|
|
1169
1190
|
// 得出"编辑器没加载"的错误结论。现在默认读法自己补上这一步。
|
|
1170
|
-
const frames =
|
|
1191
|
+
const frames = await this._autoMergeOpaqueFrames(res, tid);
|
|
1171
1192
|
// 「这棵树读到了多少页面文字」—— 与 frame_hints 的 text_coverage(只看帧)
|
|
1172
1193
|
// 互补:那个回答"帧读够了吗",这个回答"整页读够了吗"。
|
|
1173
1194
|
// 事故里 27 个节点、正文 0 字的页面,两个数字都会报警,而此前一个都没有。
|
|
@@ -1183,6 +1204,21 @@ class PageManager {
|
|
|
1183
1204
|
const idx = await this._editorsIndex(tid, res.tree);
|
|
1184
1205
|
if (idx) res.tree.editors = idx;
|
|
1185
1206
|
}
|
|
1207
|
+
// subset:'interactive' —— 默认读法此前完全不看这个参数(只有 ax:true 分支
|
|
1208
|
+
// 在 getTreeViaAx 里剪枝)。判据复用同一个 filterInteractive,保证两条读法
|
|
1209
|
+
// 剪出来的形状一致;'full' / 缺省 = 不剪。
|
|
1210
|
+
if (res && res.tree && opts && opts.subset === 'interactive') {
|
|
1211
|
+
res.tree = axExtractor.filterInteractive(res.tree) || res.tree;
|
|
1212
|
+
}
|
|
1213
|
+
// focused_only —— 真正的裁剪在这里(抽取器不认这个参数,见 shared/tree_focus.cjs)
|
|
1214
|
+
if (focusedOnly && res) {
|
|
1215
|
+
const f = treeFocus.focusOnly(res.tree);
|
|
1216
|
+
res.tree = f.tree;
|
|
1217
|
+
if (!f.tree) {
|
|
1218
|
+
// 没有焦点就把话说清楚:调用方不能把"焦点不在页面上"当成"页面是空的"。
|
|
1219
|
+
res.context = { ...(res.context || {}), focused_only: { found: false, hint: 'No element has focus on this page. Click into a field first, or read without focused_only.' } };
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1186
1222
|
return res;
|
|
1187
1223
|
}
|
|
1188
1224
|
|
|
@@ -1315,9 +1351,12 @@ class PageManager {
|
|
|
1315
1351
|
// context 只有 modals/session/stats,登录墙、校验错误、必填提示全都来自
|
|
1316
1352
|
// 这条 DOM 扫描 —— 两条读法给出不一致的 context 只会让调用方怀疑读数。
|
|
1317
1353
|
async _readContext(view) {
|
|
1354
|
+
// 归属 tab 由 view 反查(本方法只收 view)。回执要认领 pending,就必须知道
|
|
1355
|
+
// 这条请求属于哪个 tab —— 见 shared/ipc_guard.cjs。
|
|
1356
|
+
const tid = this._tabIdForContents(view && view.webContents);
|
|
1318
1357
|
const res = await new Promise((resolve, reject) => {
|
|
1319
1358
|
const id = ++this._requestId;
|
|
1320
|
-
this._pendingRequests.set(id, { resolve, reject });
|
|
1359
|
+
this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'tree' });
|
|
1321
1360
|
view.webContents.send('ai:context', { id });
|
|
1322
1361
|
setTimeout(() => {
|
|
1323
1362
|
if (this._pendingRequests.has(id)) {
|
|
@@ -1472,8 +1511,15 @@ class PageManager {
|
|
|
1472
1511
|
}
|
|
1473
1512
|
}
|
|
1474
1513
|
// 未知参数不再静默丢弃:调用方传了什么没被用上,回执里点名。
|
|
1514
|
+
//
|
|
1515
|
+
// `tab` 必须排除:它是**路由参数**(已经用来选中 tid 了),不是截图选项。
|
|
1516
|
+
// 此前调用方照文档传 `{tab, format}` 会收到 `ignored_params:['tab']`,
|
|
1517
|
+
// 看起来像"你传的 tab 被忽略了" —— 而它恰恰是唯一生效的那个。
|
|
1518
|
+
// 同理 `heal` / `node_id` 这类"调用层参数"也不该出现在这里。
|
|
1475
1519
|
const known = { format: 1, quality: 1, fullPage: 1, clip: 1, path: 1 };
|
|
1476
|
-
const
|
|
1520
|
+
const ROUTING_ONLY = { tab: 1 };
|
|
1521
|
+
const ignored = Object.keys(opts || {})
|
|
1522
|
+
.filter((k) => !known[k] && !ROUTING_ONLY[k]);
|
|
1477
1523
|
return {
|
|
1478
1524
|
ok: true,
|
|
1479
1525
|
tab: tid,
|
|
@@ -2120,15 +2166,28 @@ class PageManager {
|
|
|
2120
2166
|
if (r) return r;
|
|
2121
2167
|
} catch (e) { /* fall through to preload */ }
|
|
2122
2168
|
} else if (action === 'upload') {
|
|
2169
|
+
// 路径闸门(存在性 / 大小 / 敏感位置)。判据在 shared/upload_guard.cjs:
|
|
2170
|
+
// 这条动作能把本机任意文件塞进站点,是"读本地文件"的原语,必须拦。
|
|
2171
|
+
const gate = uploadGuard.checkUploadPath(params.file || '');
|
|
2172
|
+
if (!gate.ok) return { success: false, error: gate.error, hint: gate.hint };
|
|
2173
|
+
const file = gate.path;
|
|
2123
2174
|
try {
|
|
2124
2175
|
await this._ensureAxHandles(view, tid);
|
|
2125
|
-
const r = await this._uploadViaCdp(view, target,
|
|
2126
|
-
|
|
2176
|
+
const r = await this._uploadViaCdp(view, target, file, tid);
|
|
2177
|
+
// ⚠️ 不许动 `uploaded` —— 它是**文件名字符串**(既有契约:e2e/richtext F-03
|
|
2178
|
+
// 与调用方都按这个读)。大小与放开标记另开字段,别覆盖。
|
|
2179
|
+
if (r && r.success !== false) {
|
|
2180
|
+
return {
|
|
2181
|
+
...r,
|
|
2182
|
+
...(Number.isFinite(gate.size) ? { upload_bytes: gate.size } : {}),
|
|
2183
|
+
...(gate.sensitive_override ? { sensitive_override: true } : {}),
|
|
2184
|
+
};
|
|
2185
|
+
}
|
|
2127
2186
|
} catch (e) { /* fall through */ }
|
|
2128
2187
|
// CDP 的 DOM.setFileInputFiles 只能写顶层文档里的 input;跨进程 iframe 里的
|
|
2129
2188
|
// 上传控件(B站封面、编辑器插图等都属于这一类)必须走帧内注入。
|
|
2130
2189
|
try {
|
|
2131
|
-
const r = await this._uploadViaFrameJs(view, target,
|
|
2190
|
+
const r = await this._uploadViaFrameJs(view, target, file, tid);
|
|
2132
2191
|
if (r) return r;
|
|
2133
2192
|
} catch (e) { /* fall through */ }
|
|
2134
2193
|
// 无 CDP 时 preload 无法真正赋值文件(受安全限制),返回失败让 agent 感知。
|
|
@@ -2410,7 +2469,7 @@ class PageManager {
|
|
|
2410
2469
|
|
|
2411
2470
|
return new Promise((resolve, reject) => {
|
|
2412
2471
|
const id = ++this._requestId;
|
|
2413
|
-
this._pendingRequests.set(id, { resolve, reject });
|
|
2472
|
+
this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'action' });
|
|
2414
2473
|
view.webContents.send('ai:action', { action, target, params, id });
|
|
2415
2474
|
setTimeout(() => {
|
|
2416
2475
|
if (this._pendingRequests.has(id)) {
|
|
@@ -2462,18 +2521,27 @@ class PageManager {
|
|
|
2462
2521
|
+ ' — the ref may be stale (page re-rendered). Re-read the tree and retry.');
|
|
2463
2522
|
}
|
|
2464
2523
|
}
|
|
2465
|
-
//
|
|
2466
|
-
//
|
|
2467
|
-
//
|
|
2468
|
-
//
|
|
2469
|
-
//
|
|
2470
|
-
//
|
|
2524
|
+
// 只有一条路:CDP Runtime.evaluate(页面的主世界,与页面自己的 JS 同权限)。
|
|
2525
|
+
//
|
|
2526
|
+
// ⚠️ 2026-10-31 删掉了原来的 `catch { return this._evaluateViaPreload(...) }`。
|
|
2527
|
+
// 那个 catch 把**页面脚本自己抛的异常**当成"CDP 不可用",于是任何会抛错的
|
|
2528
|
+
// 表达式都会被拿到 preload 用 Node 的 eval 重跑一次。实测
|
|
2529
|
+
// Function('return globalThis["pro"+"cess"].version')()
|
|
2530
|
+
// 拿到 "v20.18.3" —— 页面 → 宿主代码执行。guards.js 的正则只是字面量黑名单,
|
|
2531
|
+
// 拆词拼接即可绕过,所以"留一条降级路"不是安全选项。
|
|
2471
2532
|
try {
|
|
2472
2533
|
return await this._evaluateViaCdp(view, js);
|
|
2473
2534
|
} catch (e) {
|
|
2474
|
-
//
|
|
2475
|
-
//
|
|
2476
|
-
|
|
2535
|
+
// 分类后**如实**抛出:脚本错就说脚本错(调用方该改脚本),环境错才说环境错。
|
|
2536
|
+
// 判据在 shared/eval_route.cjs(纯函数,表驱动单测钉住每种消息)。
|
|
2537
|
+
const r = evalRoute.evalFailureResult(e);
|
|
2538
|
+
const err = new Error(
|
|
2539
|
+
r.error.code === 'script-error' ? r.error.message : r.error.message + ' — ' + r.error.hint
|
|
2540
|
+
);
|
|
2541
|
+
err.code = r.error.code;
|
|
2542
|
+
err.hint = r.error.hint;
|
|
2543
|
+
err.retryable = r.error.retryable;
|
|
2544
|
+
throw err;
|
|
2477
2545
|
}
|
|
2478
2546
|
}
|
|
2479
2547
|
|
|
@@ -2511,20 +2579,6 @@ class PageManager {
|
|
|
2511
2579
|
return r ? r.value : undefined;
|
|
2512
2580
|
}
|
|
2513
2581
|
|
|
2514
|
-
_evaluateViaPreload(view, js) {
|
|
2515
|
-
return new Promise((resolve, reject) => {
|
|
2516
|
-
const id = ++this._requestId;
|
|
2517
|
-
this._pendingRequests.set(id, { resolve, reject });
|
|
2518
|
-
view.webContents.send('ai:evaluate', { js, id });
|
|
2519
|
-
setTimeout(() => {
|
|
2520
|
-
if (this._pendingRequests.has(id)) {
|
|
2521
|
-
this._pendingRequests.delete(id);
|
|
2522
|
-
reject(new Error('evaluate timeout'));
|
|
2523
|
-
}
|
|
2524
|
-
}, 5000);
|
|
2525
|
-
});
|
|
2526
|
-
}
|
|
2527
|
-
|
|
2528
2582
|
// === CDP 受信输入(通用化,无框架特判)===
|
|
2529
2583
|
// 任何网页/富文本/编辑器(Draft、ProseMirror、Quill、antd、shadcn…)都无需
|
|
2530
2584
|
// 专项适配:点击/键盘/文本全部走 Chromium 真实输入管线(受信事件),等价于
|
|
@@ -3778,6 +3832,20 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
|
|
|
3778
3832
|
* agent 侧由 ws_server 显式传 false(见 shared/tab_route.cjs 的说明)。
|
|
3779
3833
|
*/
|
|
3780
3834
|
newTab(url = null, opts = {}) {
|
|
3835
|
+
// 缺 preload 的症状是"每一条读树都超时",而没有一条错误信息指向它。
|
|
3836
|
+
// 这里做一次性自检并落盘:宁可多一条 error_log,也不要让人从超时反推。
|
|
3837
|
+
if (this._preloadReported !== true) {
|
|
3838
|
+
let ok = false;
|
|
3839
|
+
try { ok = !!this._preloadPath && fs.existsSync(this._preloadPath); } catch (_e) { ok = false; }
|
|
3840
|
+
if (!ok) {
|
|
3841
|
+
this._preloadReported = true;
|
|
3842
|
+
console.error('[page_manager] preload missing:', this._preloadPath);
|
|
3843
|
+
recordError('preload_missing', {
|
|
3844
|
+
path: String(this._preloadPath),
|
|
3845
|
+
hint: 'Views will load but no bridge is injected — every get_tree/evaluate/act will time out. Check that src/preload/bridge.cjs is packaged.',
|
|
3846
|
+
});
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3781
3849
|
const tabId = ++this.tabCounter;
|
|
3782
3850
|
const self = this;
|
|
3783
3851
|
const view = new BrowserView({
|
|
@@ -5098,14 +5166,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
|
|
|
5098
5166
|
}
|
|
5099
5167
|
|
|
5100
5168
|
_layoutView(view) {
|
|
5101
|
-
|
|
5102
|
-
const inset = this._bottomInset || 0;
|
|
5103
|
-
view.setBounds({
|
|
5104
|
-
x: 0,
|
|
5105
|
-
y: config.tabBarHeight,
|
|
5106
|
-
width: bounds.width,
|
|
5107
|
-
height: Math.max(0, bounds.height - config.tabBarHeight - inset),
|
|
5108
|
-
});
|
|
5169
|
+
view.setBounds(this._viewBounds(this.window.getContentBounds()));
|
|
5109
5170
|
}
|
|
5110
5171
|
|
|
5111
5172
|
addSubscription(sessionId, events) {
|
|
@@ -5521,8 +5582,26 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
|
|
|
5521
5582
|
}
|
|
5522
5583
|
const entry = this._cdpTabs.get(tabId);
|
|
5523
5584
|
if (!entry.domains.has(domain)) {
|
|
5524
|
-
|
|
5585
|
+
// ⚠️ 记账必须能被撤销(2026-10-31 复核)。
|
|
5586
|
+
// 原实现是 `sendCommand(...); domains.add(domain)` —— 发出即算启用。
|
|
5587
|
+
// 一旦 enable 被 reject(导航中 / 域不可用),domains 里就**永久**留着
|
|
5588
|
+
// 一个没启用的域,之后所有依赖它的命令(Runtime.evaluate / Network.*)
|
|
5589
|
+
// 都以"看起来可用"的姿态失败,查起来像是工具本身坏了。
|
|
5590
|
+
// 这里返回 promise 并挂拒绝处理:失败就删掉记账、落盘一条原因,下次重试。
|
|
5525
5591
|
entry.domains.add(domain);
|
|
5592
|
+
const p = wc.debugger.sendCommand(domain + '.enable');
|
|
5593
|
+
if (p && typeof p.then === 'function') {
|
|
5594
|
+
p.catch((e) => {
|
|
5595
|
+
try { entry.domains.delete(domain); } catch (_e) {}
|
|
5596
|
+
recordError('cdp_enable_failed', {
|
|
5597
|
+
tab: tabId,
|
|
5598
|
+
domain,
|
|
5599
|
+
message: String((e && e.message) || e).slice(0, 300),
|
|
5600
|
+
note: 'CDP 域启用失败,已撤销记账(下次调用会重试)',
|
|
5601
|
+
});
|
|
5602
|
+
});
|
|
5603
|
+
}
|
|
5604
|
+
return p;
|
|
5526
5605
|
}
|
|
5527
5606
|
} catch (e) { /* mid-navigation / already-attached elsewhere; skip this tab */ }
|
|
5528
5607
|
}
|
|
@@ -5849,8 +5928,6 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
|
|
|
5849
5928
|
this.tabs.clear();
|
|
5850
5929
|
ipcMain.removeAllListeners('ai:tree');
|
|
5851
5930
|
ipcMain.removeAllListeners('ai:action_result');
|
|
5852
|
-
ipcMain.removeAllListeners('ai:evaluate_result');
|
|
5853
|
-
ipcMain.removeAllListeners('ai:diff');
|
|
5854
5931
|
ipcMain.removeAllListeners('ai:event');
|
|
5855
5932
|
}
|
|
5856
5933
|
}
|